LLVM 24.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 "BitReaderOptions.h"
11#include "ValueList.h"
12
13#include "llvm/ADT/APInt.h"
14#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
28#include "llvm/IR/Argument.h"
29#include "llvm/IR/AutoUpgrade.h"
30#include "llvm/IR/BasicBlock.h"
31#include "llvm/IR/Constants.h"
33#include "llvm/IR/Function.h"
36#include "llvm/IR/Instruction.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Metadata.h"
40#include "llvm/IR/Module.h"
42#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 <optional>
56#include <string>
57#include <tuple>
58#include <utility>
59#include <vector>
60
61using namespace llvm;
62
63#define DEBUG_TYPE "bitcode-reader"
64
65STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
66STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
67STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
68
69namespace {
70
71class BitcodeReaderMetadataList {
72 /// Array of metadata references.
73 ///
74 /// Don't use std::vector here. Some versions of libc++ copy (instead of
75 /// move) on resize, and TrackingMDRef is very expensive to copy.
77
78 /// The set of indices in MetadataPtrs above of forward references that were
79 /// generated.
80 SmallDenseSet<unsigned, 1> ForwardReference;
81
82 /// The set of indices in MetadataPtrs above of Metadata that need to be
83 /// resolved.
84 SmallDenseSet<unsigned, 1> UnresolvedNodes;
85
86 /// Structures for resolving old type refs.
87 struct {
92 } OldTypeRefs;
93
94 LLVMContext &Context;
95
96 /// Maximum number of valid references. Forward references exceeding the
97 /// maximum must be invalid.
98 unsigned RefsUpperBound;
99
100public:
101 BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
102 : Context(C),
103 RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
104 RefsUpperBound)) {}
105
106 using const_iterator = SmallVector<TrackingMDRef, 1>::const_iterator;
107
108 // vector compatibility methods
109 unsigned size() const { return MetadataPtrs.size(); }
110 void resize(unsigned N) { MetadataPtrs.resize(N); }
111 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
112 void clear() { MetadataPtrs.clear(); }
113 Metadata *back() const { return MetadataPtrs.back(); }
114 void pop_back() { MetadataPtrs.pop_back(); }
115 bool empty() const { return MetadataPtrs.empty(); }
116 const_iterator begin() const { return MetadataPtrs.begin(); }
117 const_iterator end() const { return MetadataPtrs.end(); }
118
119 Metadata *operator[](unsigned i) const { return MetadataPtrs[i]; }
120
121 Metadata *lookup(unsigned I) const {
122 if (I < MetadataPtrs.size())
123 return MetadataPtrs[I];
124 return nullptr;
125 }
126
127 void shrinkTo(unsigned N) {
128 assert(N <= size() && "Invalid shrinkTo request!");
129 assert(ForwardReference.empty() && "Unexpected forward refs");
130 assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
131 MetadataPtrs.resize(N);
132 }
133
134 /// Return the given metadata, creating a replaceable forward reference if
135 /// necessary.
136 Metadata *getMetadataFwdRef(unsigned Idx);
137
138 /// Return the given metadata only if it is fully resolved.
139 ///
140 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
141 /// would give \c false.
142 Metadata *getMetadataIfResolved(unsigned Idx);
143
144 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
145 void assignValue(Metadata *MD, unsigned Idx);
146 void tryToResolveCycles();
147 bool hasFwdRefs() const { return !ForwardReference.empty(); }
148 int getNextFwdRef() {
149 assert(hasFwdRefs());
150 return *ForwardReference.begin();
151 }
152
153 /// Upgrade a type that had an MDString reference.
154 void addTypeRef(MDString &UUID, DICompositeType &CT);
155
156 /// Upgrade a type that had an MDString reference.
157 Metadata *upgradeTypeRef(Metadata *MaybeUUID);
158
159 /// Upgrade a type array that may have MDString references.
160 Metadata *upgradeTypeArray(Metadata *MaybeTuple);
161
162private:
163 Metadata *resolveTypeArray(Metadata *MaybeTuple);
164};
165} // namespace
166
167static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
168
169void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
170 if (auto *MDN = dyn_cast<MDNode>(MD))
171 if (!MDN->isResolved())
172 UnresolvedNodes.insert(Idx);
173
174 if (Idx == size()) {
175 push_back(MD);
176 return;
177 }
178
179 if (Idx >= size())
180 resize(Idx + 1);
181
182 TrackingMDRef &OldMD = MetadataPtrs[Idx];
183 if (!OldMD) {
184 OldMD.reset(MD);
185 return;
186 }
187
188 // If there was a forward reference to this value, replace it.
189 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
190 PrevMD->replaceAllUsesWith(MD);
191 ForwardReference.erase(Idx);
192}
193
194Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
195 // Bail out for a clearly invalid value.
196 if (Idx >= RefsUpperBound)
197 return nullptr;
198
199 if (Idx >= size())
200 resize(Idx + 1);
201
202 if (Metadata *MD = MetadataPtrs[Idx])
203 return MD;
204
205 // Track forward refs to be resolved later.
206 ForwardReference.insert(Idx);
207
208 // Create and return a placeholder, which will later be RAUW'd.
209 ++NumMDNodeTemporary;
211 MetadataPtrs[Idx].reset(MD);
212 return MD;
213}
214
215Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
216 Metadata *MD = lookup(Idx);
217 if (auto *N = dyn_cast_or_null<MDNode>(MD))
218 if (!N->isResolved())
219 return nullptr;
220 return MD;
221}
222
223MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
224 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
225}
226
227void BitcodeReaderMetadataList::tryToResolveCycles() {
228 if (!ForwardReference.empty())
229 // Still forward references... can't resolve cycles.
230 return;
231
232 // Give up on finding a full definition for any forward decls that remain.
233 for (const auto &[UUID, CT] : OldTypeRefs.FwdDecls)
234 OldTypeRefs.Final.try_emplace(UUID, CT);
235 OldTypeRefs.FwdDecls.clear();
236
237 // Upgrade from old type ref arrays. In strange cases, this could add to
238 // OldTypeRefs.Unknown.
239 for (const auto &Array : OldTypeRefs.Arrays)
240 Array.second->replaceAllUsesWith(resolveTypeArray(Array.first.get()));
241 OldTypeRefs.Arrays.clear();
242
243 // Replace old string-based type refs with the resolved node, if possible.
244 // If we haven't seen the node, leave it to the verifier to complain about
245 // the invalid string reference.
246 for (const auto &Ref : OldTypeRefs.Unknown) {
247 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
248 Ref.second->replaceAllUsesWith(CT);
249 else
250 Ref.second->replaceAllUsesWith(Ref.first);
251 }
252 OldTypeRefs.Unknown.clear();
253
254 if (UnresolvedNodes.empty())
255 // Nothing to do.
256 return;
257
258 // Resolve any cycles.
259 for (unsigned I : UnresolvedNodes) {
260 auto &MD = MetadataPtrs[I];
261 auto *N = dyn_cast_or_null<MDNode>(MD);
262 if (!N)
263 continue;
264
265 assert(!N->isTemporary() && "Unexpected forward reference");
266 N->resolveCycles();
267 }
268
269 // Make sure we return early again until there's another unresolved ref.
270 UnresolvedNodes.clear();
271}
272
273void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
274 DICompositeType &CT) {
275 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
276 if (CT.isForwardDecl())
277 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
278 else
279 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
280}
281
282Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
283 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
284 if (LLVM_LIKELY(!UUID))
285 return MaybeUUID;
286
287 if (auto *CT = OldTypeRefs.Final.lookup(UUID))
288 return CT;
289
290 auto &Ref = OldTypeRefs.Unknown[UUID];
291 if (!Ref)
293 return Ref.get();
294}
295
296Metadata *BitcodeReaderMetadataList::upgradeTypeArray(Metadata *MaybeTuple) {
297 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
298 if (!Tuple || Tuple->isDistinct())
299 return MaybeTuple;
300
301 // Look through the array immediately if possible.
302 if (!Tuple->isTemporary())
303 return resolveTypeArray(Tuple);
304
305 // Create and return a placeholder to use for now. Eventually
306 // resolveTypeArrays() will be resolve this forward reference.
307 OldTypeRefs.Arrays.emplace_back(
308 std::piecewise_construct, std::forward_as_tuple(Tuple),
309 std::forward_as_tuple(MDTuple::getTemporary(Context, {})));
310 return OldTypeRefs.Arrays.back().second.get();
311}
312
313Metadata *BitcodeReaderMetadataList::resolveTypeArray(Metadata *MaybeTuple) {
314 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
315 if (!Tuple || Tuple->isDistinct())
316 return MaybeTuple;
317
318 // Look through the DITypeArray, upgrading each DIType *.
320 Ops.reserve(Tuple->getNumOperands());
321 for (Metadata *MD : Tuple->operands())
322 Ops.push_back(upgradeTypeRef(MD));
323
324 return MDTuple::get(Context, Ops);
325}
326
327namespace {
328
329class PlaceholderQueue {
330 // Placeholders would thrash around when moved, so store in a std::deque
331 // instead of some sort of vector.
332 std::deque<DistinctMDOperandPlaceholder> PHs;
333
334public:
335 ~PlaceholderQueue() {
336 assert(empty() &&
337 "PlaceholderQueue hasn't been flushed before being destroyed");
338 }
339 bool empty() const { return PHs.empty(); }
340 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
341 void flush(BitcodeReaderMetadataList &MetadataList);
342
343 /// Return the list of temporaries nodes in the queue, these need to be
344 /// loaded before we can flush the queue.
345 void getTemporaries(BitcodeReaderMetadataList &MetadataList,
346 DenseSet<unsigned> &Temporaries) {
347 for (auto &PH : PHs) {
348 auto ID = PH.getID();
349 auto *MD = MetadataList.lookup(ID);
350 if (!MD) {
351 Temporaries.insert(ID);
352 continue;
353 }
354 auto *N = dyn_cast_or_null<MDNode>(MD);
355 if (N && N->isTemporary())
356 Temporaries.insert(ID);
357 }
358 }
359};
360
361} // end anonymous namespace
362
363DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
364 PHs.emplace_back(ID);
365 return PHs.back();
366}
367
368void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
369 while (!PHs.empty()) {
370 auto *MD = MetadataList.lookup(PHs.front().getID());
371 assert(MD && "Flushing placeholder on unassigned MD");
372#ifndef NDEBUG
373 if (auto *MDN = dyn_cast<MDNode>(MD))
374 assert(MDN->isResolved() &&
375 "Flushing Placeholder while cycles aren't resolved");
376#endif
377 PHs.front().replaceUseWith(MD);
378 PHs.pop_front();
379 }
380}
381
382static Error error(const Twine &Message) {
385}
386
388 const BitReaderOptions &Opts;
389 BitcodeReaderMetadataList MetadataList;
390 BitcodeReaderValueList &ValueList;
391 BitstreamCursor &Stream;
392 LLVMContext &Context;
393 Module &TheModule;
394 MetadataLoaderCallbacks Callbacks;
395
396 /// Forward-reference tracking for MDFunctionLocalContext.
397 /// Each call to parseOneMetadata for a context adds an entry to these arrays
398 /// iff it contains at least one forward reference to a scope/context; flushed
399 /// when we resolve metadata references.
401 FLMDScopeMetadataIDs;
403 FLMDInlineeMetadataIDs;
404
405 /// Cursor associated with the lazy-loading of Metadata. This is the easy way
406 /// to keep around the right "context" (Abbrev list) to be able to jump in
407 /// the middle of the metadata block and load any record.
408 BitstreamCursor IndexCursor;
409
410 /// Index that keeps track of MDString values.
411 std::vector<StringRef> MDStringRef;
412
413 /// On-demand loading of a single MDString. Requires the index above to be
414 /// populated.
415 MDString *lazyLoadOneMDString(unsigned Idx);
416
417 /// Index that keeps track of where to find a metadata record in the stream.
418 std::vector<uint64_t> GlobalMetadataBitPosIndex;
419
420 /// Cursor position of the start of the global decl attachments, to enable
421 /// loading using the index built for lazy loading, instead of forward
422 /// references.
423 uint64_t GlobalDeclAttachmentPos = 0;
424
425#ifndef NDEBUG
426 /// Baisic correctness check that we end up parsing all of the global decl
427 /// attachments.
428 unsigned NumGlobalDeclAttachSkipped = 0;
429 unsigned NumGlobalDeclAttachParsed = 0;
430#endif
431
432 /// Load the global decl attachments, using the index built for lazy loading.
433 Expected<bool> loadGlobalDeclAttachments();
434
435 /// Populate the index above to enable lazily loading of metadata, and load
436 /// the named metadata as well as the transitively referenced global
437 /// Metadata.
438 Expected<bool> lazyLoadModuleMetadataBlock();
439
440 /// On-demand loading of a single metadata. Requires the index above to be
441 /// populated.
442 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
443
444 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
445 // point from SP to CU after a block is completly parsed.
446 std::vector<std::pair<DICompileUnit *, unsigned>> CUSubprograms;
447
448 /// Functions that need to be matched with subprograms when upgrading old
449 /// metadata.
451
452 /// retainedNodes of these subprograms should be cleaned up from incorrectly
453 /// scoped local types.
454 /// See \ref DISubprogram::cleanupRetainedNodes.
455 SmallVector<DISubprogram *> NewDistinctSPs;
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
463 /// Rebuilt alias scopes and domains, so that upgraded domains get reused
464 /// correctly and to memoize.
465 DenseMap<MDNode *, MDNode *> UpgradedAliasScopes;
466 bool NeedUpgradeToDIGlobalVariableExpression = false;
467 bool NeedDeclareExpressionUpgrade = false;
468
469 /// Map DIGlobalVariable to generated DIGlobalVariable, if any.
471 GlobalVariableExpression;
472
473 /// Map DILocalScope to the enclosing DISubprogram, if any.
475
476 /// True if metadata is being parsed for a module being ThinLTO imported.
477 bool IsImporting = false;
478
479 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
480 PlaceholderQueue &Placeholders, StringRef Blob,
481 unsigned &NextMetadataNo);
482 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
483 function_ref<void(StringRef)> CallBack);
484 Error parseGlobalObjectAttachment(GlobalObject &GO,
486 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
487
488 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
489
490 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
491 void upgradeCUSubprograms() {
492 for (auto CU_SP : CUSubprograms)
493 if (auto *SPs =
494 dyn_cast_or_null<MDTuple>(MetadataList.lookup(CU_SP.second - 1)))
495 for (auto &Op : SPs->operands())
496 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
497 SP->replaceUnit(CU_SP.first);
498 CUSubprograms.clear();
499 }
500
501 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
502 void upgradeCUVariables() {
503 if (!NeedUpgradeToDIGlobalVariableExpression)
504 return;
505
506 // Upgrade list of variables attached to the CUs.
507 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
508 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
509 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
510 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
511 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
512 if (auto *GV =
513 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
514 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[GV];
515 if (!DGVE) {
517 Context, GV, DIExpression::get(Context, {}));
518 }
519 GVs->replaceOperandWith(I, DGVE);
520 }
521 }
522
523 // Upgrade variables attached to globals.
524 for (auto &GV : TheModule.globals()) {
526 GV.getMetadata(LLVMContext::MD_dbg, MDs);
527 GV.eraseMetadata(LLVMContext::MD_dbg);
528 for (auto *MD : MDs)
529 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
530 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
531 if (!DGVE) {
533 Context, DGV, DIExpression::get(Context, {}));
534 }
535 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
536 } else
537 GV.addMetadata(LLVMContext::MD_dbg, *MD);
538 }
539 }
540
541 DISubprogram *findEnclosingSubprogram(DILocalScope *S) {
542 if (!S)
543 return nullptr;
544 if (auto *SP = ParentSubprogram[S]) {
545 return SP;
546 }
547
548 DILocalScope *InitialScope = S;
550 while (S && !isa<DISubprogram>(S)) {
552 if (!Visited.insert(S).second)
553 break;
554 }
555
556 return ParentSubprogram[InitialScope] =
558 }
559
560 /// Map SP -> {Metadata} to store CU locals that should be attached to
561 /// subprogram retainedNodes list during CU upgrade.
562 using SPToEntitiesMap =
564
565 /// Retrieve the CU operand at position ListIndex, treat it as an MDTuple, and
566 /// remove all local debug info nodes from it. Fill SPToEntities map with
567 /// removed local nodes.
568 template <typename NodeT>
569 void upgradeOneCULocalsList(SPToEntitiesMap &SPToEntities, DICompileUnit *CU,
570 unsigned ListIndex) {
571 MDTuple *List = cast_if_present<MDTuple>(CU->getOperand(ListIndex));
572 if (!List)
573 return;
574
575 if (llvm::all_of(List->operands(), [](Metadata *MD) {
576 return !isa_and_nonnull<DILocalScope>(getScope(cast<NodeT>(MD)));
577 }))
578 return;
579
581 for (Metadata *MD : List->operands()) {
582 DILocalScope *LS =
584 if (!LS)
585 MDs.push_back(MD);
586 else if (auto *SP = findEnclosingSubprogram(LS))
587 SPToEntities[SP].push_back(MD);
588 }
589
590 CU->replaceOperandWith(ListIndex, MDNode::get(CU->getContext(), MDs));
591 }
592
593 /// Move function-local entities from DICompileUnit's 'imports',
594 /// 'enums', and 'globals' fields to DISubprogram's retainedNodes.
595 void upgradeCULocals() {
596 NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu");
597 if (!CUNodes)
598 return;
599
600 SPToEntitiesMap SPToEntities;
601 for (MDNode *N : CUNodes->operands()) {
603 if (!CU)
604 continue;
605
606 // Remove all static local variables from CU's globals list.
607 upgradeOneCULocalsList<DIGlobalVariableExpression>(SPToEntities, CU, 6);
608 // Remove all local imports from CU's imports list.
609 upgradeOneCULocalsList<DIImportedEntity>(SPToEntities, CU, 7);
610 // Remove all local types from CU's enums list.
611 upgradeOneCULocalsList<DICompositeType>(SPToEntities, CU, 4);
612
613 // Retain local entities removed from the CU in their corresponding
614 // subprograms.
615 for (auto &[SP, Nodes] : SPToEntities)
616 SP->retainNodes(Nodes.begin(), Nodes.end());
617 SPToEntities.clear();
618 }
619
620 ParentSubprogram.clear();
621 }
622
623 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
624 /// describes a function argument.
625 void upgradeDeclareExpressions(Function &F) {
626 if (!NeedDeclareExpressionUpgrade)
627 return;
628
629 auto UpdateDeclareIfNeeded = [&](auto *Declare) {
630 auto *DIExpr = Declare->getExpression();
631 if (!DIExpr || !DIExpr->startsWithDeref() ||
632 !isa_and_nonnull<Argument>(Declare->getAddress()))
633 return;
635 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
636 Declare->setExpression(DIExpression::get(Context, Ops));
637 };
638
639 for (auto &BB : F)
640 for (auto &I : BB) {
641 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
642 if (DVR.isDbgDeclare())
643 UpdateDeclareIfNeeded(&DVR);
644 }
645 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
646 UpdateDeclareIfNeeded(DDI);
647 }
648 }
649
650 /// Upgrade the expression from previous versions.
651 Error upgradeDIExpression(uint64_t FromVersion,
654 auto N = Expr.size();
655 switch (FromVersion) {
656 default:
657 return error("Invalid record");
658 case 0:
659 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
660 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
661 [[fallthrough]];
662 case 1:
663 // Move DW_OP_deref to the end.
664 if (N && Expr[0] == dwarf::DW_OP_deref) {
665 auto End = Expr.end();
666 if (Expr.size() >= 3 &&
667 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
668 End = std::prev(End, 3);
669 std::move(std::next(Expr.begin()), End, Expr.begin());
670 *std::prev(End) = dwarf::DW_OP_deref;
671 }
672 NeedDeclareExpressionUpgrade = true;
673 [[fallthrough]];
674 case 2: {
675 // Change DW_OP_plus to DW_OP_plus_uconst.
676 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
677 auto SubExpr = ArrayRef<uint64_t>(Expr);
678 while (!SubExpr.empty()) {
679 // Skip past other operators with their operands
680 // for this version of the IR, obtained from
681 // from historic DIExpression::ExprOperand::getSize().
682 size_t HistoricSize;
683 switch (SubExpr.front()) {
684 default:
685 HistoricSize = 1;
686 break;
687 case dwarf::DW_OP_constu:
688 case dwarf::DW_OP_minus:
689 case dwarf::DW_OP_plus:
690 HistoricSize = 2;
691 break;
693 HistoricSize = 3;
694 break;
695 }
696
697 // If the expression is malformed, make sure we don't
698 // copy more elements than we should.
699 HistoricSize = std::min(SubExpr.size(), HistoricSize);
700 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
701
702 switch (SubExpr.front()) {
703 case dwarf::DW_OP_plus:
704 Buffer.push_back(dwarf::DW_OP_plus_uconst);
705 Buffer.append(Args.begin(), Args.end());
706 break;
707 case dwarf::DW_OP_minus:
708 Buffer.push_back(dwarf::DW_OP_constu);
709 Buffer.append(Args.begin(), Args.end());
710 Buffer.push_back(dwarf::DW_OP_minus);
711 break;
712 default:
713 Buffer.push_back(*SubExpr.begin());
714 Buffer.append(Args.begin(), Args.end());
715 break;
716 }
717
718 // Continue with remaining elements.
719 SubExpr = SubExpr.slice(HistoricSize);
720 }
721 Expr = MutableArrayRef<uint64_t>(Buffer);
722 [[fallthrough]];
723 }
724 case 3:
725 // Up-to-date!
726 break;
727 }
728
729 return Error::success();
730 }
731
732 /// Specifies which kind of debug info upgrade should be performed.
733 ///
734 /// The upgrade of compile units' enums: and imports: fields is performed
735 /// only when module level metadata block is loaded (i.e. all elements of
736 /// "llvm.dbg.cu" named metadata node are loaded).
737 enum class DebugInfoUpgradeMode {
738 /// No debug info upgrade.
739 None,
740 /// Debug info upgrade after loading function-level metadata block.
741 Partial,
742 /// Debug info upgrade after loading module-level metadata block.
743 ModuleLevel,
744 };
745
746 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
747 if (Mode == DebugInfoUpgradeMode::None)
748 return;
749 upgradeCUSubprograms();
750 upgradeCUVariables();
751 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
752 upgradeCULocals();
753 }
754
755 /// Prepare loaded metadata nodes to be used by loader clients.
756 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
757 DebugInfoUpgradeMode DIUpgradeMode) {
758 resolveForwardRefsAndPlaceholders(Placeholders);
759 upgradeDebugInfo(DIUpgradeMode);
761 LLVM_DEBUG(llvm::dbgs() << "Resolved loaded metadata. Cleaned up "
762 << NewDistinctSPs.size() << " subprogram(s).\n");
763 NewDistinctSPs.clear();
764 }
765
766 void callMDTypeCallback(Metadata **Val, unsigned TypeID);
767
768public:
770 BitcodeReaderValueList &ValueList,
771 MetadataLoaderCallbacks Callbacks, bool IsImporting)
772 : Opts(getBitReaderOptions(TheModule.getContext())),
773 MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
774 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
775 TheModule(TheModule), Callbacks(std::move(Callbacks)),
776 IsImporting(IsImporting) {}
777
778 Error parseMetadata(bool ModuleLevel);
779
780 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
781
783 if (ID < MDStringRef.size())
784 return lazyLoadOneMDString(ID);
785 if (auto *MD = MetadataList.lookup(ID))
786 return MD;
787 // If lazy-loading is enabled, we try recursively to load the operand
788 // instead of creating a temporary.
789 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
790 PlaceholderQueue Placeholders;
791 lazyLoadOneMetadata(ID, Placeholders);
792 LLVM_DEBUG(llvm::dbgs() << "\nLazy metadata loading: ");
793 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
794 return MetadataList.lookup(ID);
795 }
796 return MetadataList.getMetadataFwdRef(ID);
797 }
798
800 return FunctionsWithSPs.lookup(F);
801 }
802
803 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
804
806 return UpgradeAliasScopeList(*ScopeList, UpgradedAliasScopes);
807 }
808
810 ArrayRef<Instruction *> InstructionList);
811
813
814 void setStripTBAA(bool Value) { StripTBAA = Value; }
815 bool isStrippingTBAA() const { return StripTBAA; }
816
817 unsigned size() const { return MetadataList.size(); }
818 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
819 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
820};
821
823MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
824 IndexCursor = Stream;
826 GlobalDeclAttachmentPos = 0;
827 // Get the abbrevs, and preload record positions to make them lazy-loadable.
828 while (true) {
829 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
830 BitstreamEntry Entry;
831 if (Error E =
832 IndexCursor
833 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
834 .moveInto(Entry))
835 return std::move(E);
836
837 switch (Entry.Kind) {
838 case BitstreamEntry::SubBlock: // Handled for us already.
840 return error("Malformed block");
842 return true;
843 }
845 // The interesting case.
846 ++NumMDRecordLoaded;
847 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
848 unsigned Code;
849 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
850 return std::move(E);
851 switch (Code) {
853 // Rewind and parse the strings.
854 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
855 return std::move(Err);
856 StringRef Blob;
857 Record.clear();
858 if (Expected<unsigned> MaybeRecord =
859 IndexCursor.readRecord(Entry.ID, Record, &Blob))
860 ;
861 else
862 return MaybeRecord.takeError();
863 unsigned NumStrings = Record[0];
864 MDStringRef.reserve(NumStrings);
865 auto IndexNextMDString = [&](StringRef Str) {
866 MDStringRef.push_back(Str);
867 };
868 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
869 return std::move(Err);
870 break;
871 }
873 // This is the offset to the index, when we see this we skip all the
874 // records and load only an index to these.
875 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
876 return std::move(Err);
877 Record.clear();
878 if (Expected<unsigned> MaybeRecord =
879 IndexCursor.readRecord(Entry.ID, Record))
880 ;
881 else
882 return MaybeRecord.takeError();
883 if (Record.size() != 2)
884 return error("Invalid record");
885 auto Offset = Record[0] + (Record[1] << 32);
886 auto BeginPos = IndexCursor.GetCurrentBitNo();
887 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
888 return std::move(Err);
889 Expected<BitstreamEntry> MaybeEntry =
890 IndexCursor.advanceSkippingSubblocks(
892 if (!MaybeEntry)
893 return MaybeEntry.takeError();
894 Entry = MaybeEntry.get();
896 "Corrupted bitcode: Expected `Record` when trying to find the "
897 "Metadata index");
898 Record.clear();
899 if (Expected<unsigned> MaybeCode =
900 IndexCursor.readRecord(Entry.ID, Record))
901 assert(MaybeCode.get() == bitc::METADATA_INDEX &&
902 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
903 "find the Metadata index");
904 else
905 return MaybeCode.takeError();
906 // Delta unpack
907 auto CurrentValue = BeginPos;
908 GlobalMetadataBitPosIndex.reserve(Record.size());
909 for (auto &Elt : Record) {
910 CurrentValue += Elt;
911 GlobalMetadataBitPosIndex.push_back(CurrentValue);
912 }
913 break;
914 }
916 // We don't expect to get there, the Index is loaded when we encounter
917 // the offset.
918 return error("Corrupted Metadata block");
919 case bitc::METADATA_NAME: {
920 // Named metadata need to be materialized now and aren't deferred.
921 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
922 return std::move(Err);
923 Record.clear();
924
925 unsigned Code;
926 if (Expected<unsigned> MaybeCode =
927 IndexCursor.readRecord(Entry.ID, Record)) {
928 Code = MaybeCode.get();
930 } else
931 return MaybeCode.takeError();
932
933 // Read name of the named metadata.
934 SmallString<8> Name(Record.begin(), Record.end());
935 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
936 Code = MaybeCode.get();
937 else
938 return MaybeCode.takeError();
939
940 // Named Metadata comes in two parts, we expect the name to be followed
941 // by the node
942 Record.clear();
943 if (Expected<unsigned> MaybeNextBitCode =
944 IndexCursor.readRecord(Code, Record))
945 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
946 else
947 return MaybeNextBitCode.takeError();
948
949 // Read named metadata elements.
950 unsigned Size = Record.size();
951 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
952 for (unsigned i = 0; i != Size; ++i) {
953 // FIXME: We could use a placeholder here, however NamedMDNode are
954 // taking MDNode as operand and not using the Metadata infrastructure.
955 // It is acknowledged by 'TODO: Inherit from Metadata' in the
956 // NamedMDNode class definition.
957 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
958 assert(MD && "Invalid metadata: expect fwd ref to MDNode");
959 NMD->addOperand(MD);
960 }
961 break;
962 }
964 if (!GlobalDeclAttachmentPos)
965 GlobalDeclAttachmentPos = SavedPos;
966#ifndef NDEBUG
967 NumGlobalDeclAttachSkipped++;
968#endif
969 break;
970 }
1009 // We don't expect to see any of these, if we see one, give up on
1010 // lazy-loading and fallback.
1011 MDStringRef.clear();
1012 GlobalMetadataBitPosIndex.clear();
1013 return false;
1014 }
1015 break;
1016 }
1017 }
1018 }
1019}
1020
1021// Load the global decl attachments after building the lazy loading index.
1022// We don't load them "lazily" - all global decl attachments must be
1023// parsed since they aren't materialized on demand. However, by delaying
1024// their parsing until after the index is created, we can use the index
1025// instead of creating temporaries.
1026Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1027 // Nothing to do if we didn't find any of these metadata records.
1028 if (!GlobalDeclAttachmentPos)
1029 return true;
1030 // Use a temporary cursor so that we don't mess up the main Stream cursor or
1031 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
1032 BitstreamCursor TempCursor = Stream;
1033 SmallVector<uint64_t, 64> Record;
1034 // Jump to the position before the first global decl attachment, so we can
1035 // scan for the first BitstreamEntry record.
1036 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
1037 return std::move(Err);
1038 while (true) {
1039 BitstreamEntry Entry;
1040 if (Error E =
1041 TempCursor
1042 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
1043 .moveInto(Entry))
1044 return std::move(E);
1045
1046 switch (Entry.Kind) {
1047 case BitstreamEntry::SubBlock: // Handled for us already.
1049 return error("Malformed block");
1051 // Check that we parsed them all.
1052 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1053 return true;
1055 break;
1056 }
1057 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
1058 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
1059 if (!MaybeCode)
1060 return MaybeCode.takeError();
1061 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
1062 // Anything other than a global decl attachment signals the end of
1063 // these records. Check that we parsed them all.
1064 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1065 return true;
1066 }
1067#ifndef NDEBUG
1068 NumGlobalDeclAttachParsed++;
1069#endif
1070 // FIXME: we need to do this early because we don't materialize global
1071 // value explicitly.
1072 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1073 return std::move(Err);
1074 Record.clear();
1075 if (Expected<unsigned> MaybeRecord =
1076 TempCursor.readRecord(Entry.ID, Record))
1077 ;
1078 else
1079 return MaybeRecord.takeError();
1080 if (Record.size() % 2 == 0)
1081 return error("Invalid record");
1082 unsigned ValueID = Record[0];
1083 if (ValueID >= ValueList.size())
1084 return error("Invalid record");
1085 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
1086 // Need to save and restore the current position since
1087 // parseGlobalObjectAttachment will resolve all forward references which
1088 // would require parsing from locations stored in the index.
1089 CurrentPos = TempCursor.GetCurrentBitNo();
1090 if (Error Err = parseGlobalObjectAttachment(
1091 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1092 return std::move(Err);
1093 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1094 return std::move(Err);
1095 }
1096 }
1097}
1098
1099void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata **Val,
1100 unsigned TypeID) {
1101 if (Callbacks.MDType) {
1102 (*Callbacks.MDType)(Val, TypeID, Callbacks.GetTypeByID,
1103 Callbacks.GetContainedTypeID);
1104 }
1105}
1106
1107/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1108/// module level metadata.
1110 llvm::TimeTraceScope timeScope("Parse metadata");
1111 if (!ModuleLevel && MetadataList.hasFwdRefs())
1112 return error("Invalid metadata: fwd refs into function blocks");
1113
1114 // Record the entry position so that we can jump back here and efficiently
1115 // skip the whole block in case we lazy-load.
1116 auto EntryPos = Stream.GetCurrentBitNo();
1117
1118 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1119 return Err;
1120
1122 PlaceholderQueue Placeholders;
1123 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1124 : DebugInfoUpgradeMode::Partial;
1125
1126 // We lazy-load module-level metadata: we build an index for each record, and
1127 // then load individual record as needed, starting with the named metadata.
1128 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1129 Opts.ondemand_mds_loading) {
1130 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1131 if (!SuccessOrErr)
1132 return SuccessOrErr.takeError();
1133 if (SuccessOrErr.get()) {
1134 // An index was successfully created and we will be able to load metadata
1135 // on-demand.
1136 MetadataList.resize(MDStringRef.size() +
1137 GlobalMetadataBitPosIndex.size());
1138
1139 // Now that we have built the index, load the global decl attachments
1140 // that were deferred during that process. This avoids creating
1141 // temporaries.
1142 SuccessOrErr = loadGlobalDeclAttachments();
1143 if (!SuccessOrErr)
1144 return SuccessOrErr.takeError();
1145 assert(SuccessOrErr.get());
1146
1147 // Reading the named metadata created forward references and/or
1148 // placeholders, that we flush here.
1149 LLVM_DEBUG(llvm::dbgs() << "\nNamed metadata loading: ");
1150 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1151 // Return at the beginning of the block, since it is easy to skip it
1152 // entirely from there.
1153 Stream.ReadBlockEnd(); // Pop the abbrev block context.
1154 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1155 return Err;
1156 if (Error Err = Stream.SkipBlock()) {
1157 // FIXME this drops the error on the floor, which
1158 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1159 consumeError(std::move(Err));
1160 return Error::success();
1161 }
1162 return Error::success();
1163 }
1164 // Couldn't load an index, fallback to loading all the block "old-style".
1165 }
1166
1167 unsigned NextMetadataNo = MetadataList.size();
1168
1169 // Read all the records.
1170 while (true) {
1171 BitstreamEntry Entry;
1172 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1173 return E;
1174
1175 switch (Entry.Kind) {
1176 case BitstreamEntry::SubBlock: // Handled for us already.
1178 return error("Malformed block");
1180 LLVM_DEBUG(llvm::dbgs() << "\nEager metadata loading: ");
1181 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1182 return Error::success();
1184 // The interesting case.
1185 break;
1186 }
1187
1188 // Read a record.
1189 Record.clear();
1190 StringRef Blob;
1191 ++NumMDRecordLoaded;
1192 if (Expected<unsigned> MaybeCode =
1193 Stream.readRecord(Entry.ID, Record, &Blob)) {
1194 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1195 Blob, NextMetadataNo))
1196 return Err;
1197 } else
1198 return MaybeCode.takeError();
1199 }
1200}
1201
1202MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1203 ++NumMDStringLoaded;
1204 if (Metadata *MD = MetadataList.lookup(ID))
1205 return cast<MDString>(MD);
1206 auto MDS = MDString::get(Context, MDStringRef[ID]);
1207 MetadataList.assignValue(MDS, ID);
1208 return MDS;
1209}
1210
1211void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1212 unsigned ID, PlaceholderQueue &Placeholders) {
1213 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1214 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
1215 // Lookup first if the metadata hasn't already been loaded.
1216 if (auto *MD = MetadataList.lookup(ID)) {
1217 auto *N = dyn_cast<MDNode>(MD);
1218 // If the node is not an MDNode, or if it is not temporary, then
1219 // we're done.
1220 if (!N || !N->isTemporary())
1221 return;
1222 }
1224 StringRef Blob;
1225 if (Error Err = IndexCursor.JumpToBit(
1226 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1227 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1228 Twine(toString(std::move(Err))));
1229 BitstreamEntry Entry;
1230 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1231 // FIXME this drops the error on the floor.
1232 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1233 Twine(toString(std::move(E))));
1234 ++NumMDRecordLoaded;
1235 if (Expected<unsigned> MaybeCode =
1236 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
1237 if (Error Err =
1238 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1239 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1240 Twine(toString(std::move(Err))));
1241 } else
1242 report_fatal_error("Can't lazyload MD: " +
1243 Twine(toString(MaybeCode.takeError())));
1244}
1245
1246/// Ensure that all forward-references and placeholders are resolved.
1247/// Iteratively lazy-loading metadata on-demand if needed.
1248void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1249 PlaceholderQueue &Placeholders) {
1250 DenseSet<unsigned> Temporaries;
1251 while (true) {
1252 // Populate Temporaries with the placeholders that haven't been loaded yet.
1253 Placeholders.getTemporaries(MetadataList, Temporaries);
1254
1255 // If we don't have any temporary, or FwdReference, we're done!
1256 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1257 break;
1258
1259 // First, load all the temporaries. This can add new placeholders or
1260 // forward references.
1261 for (auto ID : Temporaries)
1262 lazyLoadOneMetadata(ID, Placeholders);
1263 Temporaries.clear();
1264
1265 // Second, load the forward-references. This can also add new placeholders
1266 // or forward references.
1267 while (MetadataList.hasFwdRefs())
1268 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1269 }
1270 // At this point we don't have any forward reference remaining, or temporary
1271 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1272 // as resolved.
1273 MetadataList.tryToResolveCycles();
1274
1275 // Finally, everything is in place, we can replace the placeholders operands
1276 // with the final node they refer to.
1277 Placeholders.flush(MetadataList);
1278
1279 // Now that we've flushed, we can resolve the FLMD fwd refs too.
1280 for (auto &[FLMD, ScopeMDs] : FLMDScopeMetadataIDs) {
1281 for (size_t ScopeIdx = 0; ScopeIdx < FLMD->Scopes.size(); ++ScopeIdx) {
1282 // Forward references are the expected case, but not guaranteed, so skip
1283 // anything that isn't a forward reference now.
1284 if (FLMD->Scopes[ScopeIdx].Scope)
1285 continue;
1286 Metadata *ScopeMD = MetadataList.lookup(ScopeMDs[ScopeIdx]);
1287 // If the cast here fails, the scope will be left with a nullptr Scope,
1288 // which should fail in the verifier.
1289 FLMD->Scopes[ScopeIdx].Scope = dyn_cast_or_null<DILocalScope>(ScopeMD);
1290 }
1291 }
1292 for (auto &[FLMD, InlineeMDs] : FLMDInlineeMetadataIDs) {
1293 for (size_t InlinedCallIdx = 0; InlinedCallIdx < FLMD->InlinedCalls.size();
1294 ++InlinedCallIdx) {
1295 // Forward references are the expected case, but not guaranteed, so skip
1296 // anything that isn't a forward reference now.
1297 if (FLMD->InlinedCalls[InlinedCallIdx].InlineeContext)
1298 continue;
1299 Metadata *InlineeContextMD =
1300 MetadataList.lookup(InlineeMDs[InlinedCallIdx]);
1301 // If the cast here fails, the InlinedCall will be left with a nullptr
1302 // InlineeContext, which should fail in the verifier.
1303 FLMD->InlinedCalls[InlinedCallIdx].InlineeContext =
1305 }
1306 }
1307 FLMDScopeMetadataIDs.clear();
1308 FLMDInlineeMetadataIDs.clear();
1309}
1310
1311static Value *getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx,
1312 Type *Ty, unsigned TyID) {
1313 Value *V = ValueList.getValueFwdRef(Idx, Ty, TyID,
1314 /*ConstExprInsertBB*/ nullptr);
1315 if (V)
1316 return V;
1317
1318 // This is a reference to a no longer supported constant expression.
1319 // Pretend that the constant was deleted, which will replace metadata
1320 // references with poison.
1321 // TODO: This is a rather indirect check. It would be more elegant to use
1322 // a separate ErrorInfo for constant materialization failure and thread
1323 // the error reporting through getValueFwdRef().
1324 if (Idx < ValueList.size() && ValueList[Idx] &&
1325 ValueList[Idx]->getType() == Ty)
1326 return PoisonValue::get(Ty);
1327
1328 return nullptr;
1329}
1330
1331Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1332 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1333 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1334
1335 bool IsDistinct = false;
1336 auto getMD = [&](unsigned ID, bool ForceLazyLoad = false) -> Metadata * {
1337 if (ID < MDStringRef.size())
1338 return lazyLoadOneMDString(ID);
1339 if (!IsDistinct || ForceLazyLoad) {
1340 if (auto *MD = MetadataList.lookup(ID))
1341 return MD;
1342 // If lazy-loading is enabled, we try recursively to load the operand
1343 // instead of creating a temporary.
1344 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1345 // Create a temporary for the node that is referencing the operand we
1346 // will lazy-load. It is needed before recursing in case there are
1347 // uniquing cycles.
1348 MetadataList.getMetadataFwdRef(NextMetadataNo);
1349 lazyLoadOneMetadata(ID, Placeholders);
1350 return MetadataList.lookup(ID);
1351 }
1352 if (!IsDistinct)
1353 // Return a temporary.
1354 return MetadataList.getMetadataFwdRef(ID);
1355 }
1356 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1357 return MD;
1358 return &Placeholders.getPlaceholderOp(ID);
1359 };
1360 auto getMDOrNull = [&](unsigned ID,
1361 bool ForceLazyLoad = false) -> Metadata * {
1362 if (ID)
1363 return getMD(ID - 1, ForceLazyLoad);
1364 return nullptr;
1365 };
1366 auto getMDString = [&](unsigned ID) -> MDString * {
1367 // This requires that the ID is not really a forward reference. In
1368 // particular, the MDString must already have been resolved.
1369 auto MDS = getMDOrNull(ID);
1370 return cast_or_null<MDString>(MDS);
1371 };
1372
1373 // Support for old type refs.
1374 auto getDITypeRefOrNull = [&](unsigned ID) {
1375 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1376 };
1377
1378 auto getMetadataOrConstant = [&](bool IsMetadata, uint64_t Entry,
1379 bool ForceLazyLoad = false) -> Metadata * {
1380 if (IsMetadata)
1381 return getMDOrNull(Entry, ForceLazyLoad);
1383 ConstantInt::get(Type::getInt64Ty(Context), Entry));
1384 };
1385
1386#define GET_OR_DISTINCT(CLASS, ARGS) \
1387 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1388
1389 switch (Code) {
1390 default: // Default behavior: ignore.
1391 break;
1392 case bitc::METADATA_NAME: {
1393 // Read name of the named metadata.
1394 SmallString<8> Name(Record.begin(), Record.end());
1395 Record.clear();
1396 if (Error E = Stream.ReadCode().moveInto(Code))
1397 return E;
1398
1399 ++NumMDRecordLoaded;
1400 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1401 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1402 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1403 } else
1404 return MaybeNextBitCode.takeError();
1405
1406 // Read named metadata elements.
1407 unsigned Size = Record.size();
1408 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1409 for (unsigned i = 0; i != Size; ++i) {
1410 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1411 if (!MD)
1412 return error("Invalid named metadata: expect fwd ref to MDNode");
1413 NMD->addOperand(MD);
1414 }
1415 break;
1416 }
1418 // Deprecated, but still needed to read old bitcode files.
1419 // This is a LocalAsMetadata record, the only type of function-local
1420 // metadata.
1421 if (Record.size() % 2 == 1)
1422 return error("Invalid record");
1423
1424 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1425 // to be legal, but there's no upgrade path.
1426 auto dropRecord = [&] {
1427 MetadataList.assignValue(MDNode::get(Context, {}), NextMetadataNo);
1428 NextMetadataNo++;
1429 };
1430 if (Record.size() != 2) {
1431 dropRecord();
1432 break;
1433 }
1434
1435 unsigned TyID = Record[0];
1436 Type *Ty = Callbacks.GetTypeByID(TyID);
1437 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy()) {
1438 dropRecord();
1439 break;
1440 }
1441
1442 Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1443 /*ConstExprInsertBB*/ nullptr);
1444 if (!V)
1445 return error("Invalid value reference from old fn metadata");
1446
1447 MetadataList.assignValue(LocalAsMetadata::get(V), NextMetadataNo);
1448 NextMetadataNo++;
1449 break;
1450 }
1452 // Deprecated, but still needed to read old bitcode files.
1453 if (Record.size() % 2 == 1)
1454 return error("Invalid record");
1455
1456 unsigned Size = Record.size();
1458 for (unsigned i = 0; i != Size; i += 2) {
1459 unsigned TyID = Record[i];
1460 Type *Ty = Callbacks.GetTypeByID(TyID);
1461 if (!Ty)
1462 return error("Invalid record");
1463 if (Ty->isMetadataTy())
1464 Elts.push_back(getMD(Record[i + 1]));
1465 else if (!Ty->isVoidTy()) {
1466 Value *V = getValueFwdRef(ValueList, Record[i + 1], Ty, TyID);
1467 if (!V)
1468 return error("Invalid value reference from old metadata");
1471 "Expected non-function-local metadata");
1472 callMDTypeCallback(&MD, TyID);
1473 Elts.push_back(MD);
1474 } else
1475 Elts.push_back(nullptr);
1476 }
1477 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1478 NextMetadataNo++;
1479 break;
1480 }
1481 case bitc::METADATA_VALUE: {
1482 if (Record.size() != 2)
1483 return error("Invalid record");
1484
1485 unsigned TyID = Record[0];
1486 Type *Ty = Callbacks.GetTypeByID(TyID);
1487 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy())
1488 return error("Invalid record");
1489
1490 Value *V = getValueFwdRef(ValueList, Record[1], Ty, TyID);
1491 if (!V)
1492 return error("Invalid value reference from metadata");
1493
1495 callMDTypeCallback(&MD, TyID);
1496 MetadataList.assignValue(MD, NextMetadataNo);
1497 NextMetadataNo++;
1498 break;
1499 }
1501 IsDistinct = true;
1502 [[fallthrough]];
1503 case bitc::METADATA_NODE: {
1505 Elts.reserve(Record.size());
1506 for (unsigned ID : Record)
1507 Elts.push_back(getMDOrNull(ID));
1508 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1509 : MDNode::get(Context, Elts),
1510 NextMetadataNo);
1511 NextMetadataNo++;
1512 break;
1513 }
1515 // 5: inlinedAt, 6: isImplicit, 8: Key Instructions fields, 9: irlayers.
1516 if (Record.size() < 5 || Record.size() == 7 || Record.size() > 9)
1517 return error("Invalid record");
1518
1519 IsDistinct = Record[0];
1520 unsigned Line = Record[1];
1521 unsigned Column = Record[2];
1522 Metadata *Scope = getMD(Record[3]);
1523 Metadata *InlinedAt = getMDOrNull(Record[4]);
1524 bool ImplicitCode = Record.size() >= 6 && Record[5];
1525 uint64_t AtomGroup = Record.size() >= 8 ? Record[6] : 0;
1526 uint8_t AtomRank = Record.size() >= 8 ? Record[7] : 0;
1527 Metadata *IRLayers = Record.size() >= 9 ? getMDOrNull(Record[8]) : nullptr;
1528 MetadataList.assignValue(
1529 GET_OR_DISTINCT(DILocation,
1530 (Context, Line, Column, Scope, InlinedAt, ImplicitCode,
1531 AtomGroup, AtomRank, IRLayers)),
1532 NextMetadataNo);
1533 NextMetadataNo++;
1534 break;
1535 }
1537 if (Record.size() != 5)
1538 return error("Invalid record");
1539
1540 IsDistinct = Record[0];
1541 unsigned Line = Record[1];
1542 unsigned Column = Record[2];
1543 Metadata *File = getMD(Record[3]);
1544 // Read the kind opaquely and let the verifier report a bad type, as the
1545 // other DI readers do: an unchecked cast would assert on malformed bitcode.
1546 MDString *Kind = dyn_cast_if_present<MDString>(getMD(Record[4]));
1547 MetadataList.assignValue(
1548 GET_OR_DISTINCT(DILayerLoc, (Context, Kind, File, Line, Column)),
1549 NextMetadataNo);
1550 NextMetadataNo++;
1551 break;
1552 }
1554 if (Record.empty())
1555 return error("Invalid record");
1556
1557 IsDistinct = Record[0];
1559 for (unsigned I = 1, E = Record.size(); I != E; ++I)
1560 Elts.push_back(getMD(Record[I]));
1561 MetadataList.assignValue(GET_OR_DISTINCT(DILayerLocList, (Context, Elts)),
1562 NextMetadataNo);
1563 NextMetadataNo++;
1564 break;
1565 }
1567 if (Record.size() < 4)
1568 return error("Invalid record");
1569
1570 IsDistinct = Record[0];
1571 unsigned Tag = Record[1];
1572 unsigned Version = Record[2];
1573
1574 if (Tag >= 1u << 16 || Version != 0)
1575 return error("Invalid record");
1576
1577 auto *Header = getMDString(Record[3]);
1579 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1580 DwarfOps.push_back(getMDOrNull(Record[I]));
1581 MetadataList.assignValue(
1582 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1583 NextMetadataNo);
1584 NextMetadataNo++;
1585 break;
1586 }
1588 Metadata *Val = nullptr;
1589 // Operand 'count' is interpreted as:
1590 // - Signed integer (version 0)
1591 // - Metadata node (version 1)
1592 // Operand 'lowerBound' is interpreted as:
1593 // - Signed integer (version 0 and 1)
1594 // - Metadata node (version 2)
1595 // Operands 'upperBound' and 'stride' are interpreted as:
1596 // - Metadata node (version 2)
1597 switch (Record[0] >> 1) {
1598 case 0:
1599 Val = GET_OR_DISTINCT(DISubrange,
1600 (Context, Record[1], unrotateSign(Record[2])));
1601 break;
1602 case 1:
1603 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1604 unrotateSign(Record[2])));
1605 break;
1606 case 2:
1607 Val = GET_OR_DISTINCT(
1608 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1609 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1610 break;
1611 default:
1612 return error("Invalid record: Unsupported version of DISubrange");
1613 }
1614
1615 MetadataList.assignValue(Val, NextMetadataNo);
1616 IsDistinct = Record[0] & 1;
1617 NextMetadataNo++;
1618 break;
1619 }
1621 Metadata *Val = nullptr;
1622 Val = GET_OR_DISTINCT(DIGenericSubrange,
1623 (Context, getMDOrNull(Record[1]),
1624 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1625 getMDOrNull(Record[4])));
1626
1627 MetadataList.assignValue(Val, NextMetadataNo);
1628 IsDistinct = Record[0] & 1;
1629 NextMetadataNo++;
1630 break;
1631 }
1633 if (Record.size() < 3)
1634 return error("Invalid record");
1635
1636 IsDistinct = Record[0] & 1;
1637 bool IsUnsigned = Record[0] & 2;
1638 bool IsBigInt = Record[0] & 4;
1639 APInt Value;
1640
1641 if (IsBigInt) {
1642 const uint64_t BitWidth = Record[1];
1643 const size_t NumWords = Record.size() - 3;
1644 Value = readWideAPInt(ArrayRef(&Record[3], NumWords), BitWidth);
1645 } else
1646 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1647
1648 MetadataList.assignValue(
1649 GET_OR_DISTINCT(DIEnumerator,
1650 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1651 NextMetadataNo);
1652 NextMetadataNo++;
1653 break;
1654 }
1656 if (Record.size() < 6 || Record.size() > 12)
1657 return error("Invalid record");
1658
1659 IsDistinct = Record[0] & 1;
1660 bool SizeIsMetadata = Record[0] & 2;
1661 DINode::DIFlags Flags = (Record.size() > 6)
1662 ? static_cast<DINode::DIFlags>(Record[6])
1663 : DINode::FlagZero;
1664 uint32_t NumExtraInhabitants = (Record.size() > 7) ? Record[7] : 0;
1665 uint32_t DataSizeInBits = (Record.size() > 8) ? Record[8] : 0;
1666 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1667 Metadata *File = nullptr;
1668 unsigned LineNo = 0;
1669 Metadata *Scope = nullptr;
1670 if (Record.size() > 9) {
1671 File = getMDOrNull(Record[9]);
1672 LineNo = Record[10];
1673 Scope = getMDOrNull(Record[11]);
1674 }
1675 MetadataList.assignValue(
1676 GET_OR_DISTINCT(DIBasicType,
1677 (Context, Record[1], getMDString(Record[2]), File,
1678 LineNo, Scope, SizeInBits, Record[4], Record[5],
1679 NumExtraInhabitants, DataSizeInBits, Flags)),
1680 NextMetadataNo);
1681 NextMetadataNo++;
1682 break;
1683 }
1685 if (Record.size() < 11)
1686 return error("Invalid record");
1687
1688 IsDistinct = Record[0] & 1;
1689 bool SizeIsMetadata = Record[0] & 2;
1690 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[6]);
1691
1692 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1693
1694 size_t Offset = 9;
1695
1696 auto ReadWideInt = [&]() {
1698 unsigned NumWords = Encoded >> 32;
1699 unsigned BitWidth = Encoded & 0xffffffff;
1700 auto Value = readWideAPInt(ArrayRef(&Record[Offset], NumWords), BitWidth);
1701 Offset += NumWords;
1702 return Value;
1703 };
1704
1705 APInt Numerator = ReadWideInt();
1706 APInt Denominator = ReadWideInt();
1707
1708 Metadata *File = nullptr;
1709 unsigned LineNo = 0;
1710 Metadata *Scope = nullptr;
1711
1712 if (Offset + 3 == Record.size()) {
1713 File = getMDOrNull(Record[Offset]);
1714 LineNo = Record[Offset + 1];
1715 Scope = getMDOrNull(Record[Offset + 2]);
1716 } else if (Offset != Record.size())
1717 return error("Invalid record");
1718
1719 MetadataList.assignValue(
1720 GET_OR_DISTINCT(DIFixedPointType,
1721 (Context, Record[1], getMDString(Record[2]), File,
1722 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1723 Record[7], Record[8], Numerator, Denominator)),
1724 NextMetadataNo);
1725 NextMetadataNo++;
1726 break;
1727 }
1729 if (Record.size() > 10 || Record.size() < 8)
1730 return error("Invalid record");
1731
1732 IsDistinct = Record[0] & 1;
1733 bool SizeIsMetadata = Record[0] & 2;
1734 // StringLocationExp (i.e. Record[5]) was added at a later time
1735 // than most of the other fields, and CharType (Record[9]) was
1736 // added even later.
1737 // The code here enables backward compatibility.
1738 Metadata *StringLocationExp = nullptr;
1739 Metadata *CharType = nullptr;
1740
1741 bool StringLocPresent = Record.size() > 8;
1742 size_t SizeOffset = StringLocPresent ? 6 : 5;
1743
1744 Metadata *SizeInBits =
1745 getMetadataOrConstant(SizeIsMetadata, Record[SizeOffset]);
1746 if (StringLocPresent) {
1747 StringLocationExp = getMDOrNull(Record[5]);
1748 }
1749 if (Record.size() == 10) {
1750 CharType = getMDOrNull(Record[9]);
1751 }
1752
1753 MetadataList.assignValue(
1754 GET_OR_DISTINCT(DIStringType,
1755 (Context, Record[1], getMDString(Record[2]),
1756 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1757 StringLocationExp, SizeInBits, Record[SizeOffset + 1],
1758 Record[SizeOffset + 2], CharType)),
1759 NextMetadataNo);
1760 NextMetadataNo++;
1761 break;
1762 }
1764 if (Record.size() < 12 || Record.size() > 15)
1765 return error("Invalid record");
1766
1767 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1768 // that there is no DWARF address space associated with DIDerivedType.
1769 std::optional<unsigned> DWARFAddressSpace;
1770 if (Record.size() > 12 && Record[12])
1771 DWARFAddressSpace = Record[12] - 1;
1772
1773 Metadata *Annotations = nullptr;
1774 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1775
1776 // Only look for annotations/ptrauth if both are allocated.
1777 // If not, we can't tell which was intended to be embedded, as both ptrauth
1778 // and annotations have been expected at Record[13] at various times.
1779 if (Record.size() > 14) {
1780 if (Record[13])
1781 Annotations = getMDOrNull(Record[13]);
1782 if (Record[14])
1783 PtrAuthData.emplace(Record[14]);
1784 }
1785
1786 IsDistinct = Record[0] & 1;
1787 bool SizeIsMetadata = Record[0] & 2;
1788 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1789
1790 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1791 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1792
1793 MetadataList.assignValue(
1794 GET_OR_DISTINCT(DIDerivedType,
1795 (Context, Record[1], getMDString(Record[2]),
1796 getMDOrNull(Record[3]), Record[4],
1797 getDITypeRefOrNull(Record[5]),
1798 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1799 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1800 getDITypeRefOrNull(Record[11]), Annotations)),
1801 NextMetadataNo);
1802 NextMetadataNo++;
1803 break;
1804 }
1806 if (Record.size() != 13)
1807 return error("Invalid record");
1808
1809 IsDistinct = Record[0] & 1;
1810 bool SizeIsMetadata = Record[0] & 2;
1811 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7]);
1812
1813 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1814
1815 MetadataList.assignValue(
1816 GET_OR_DISTINCT(DISubrangeType,
1817 (Context, getMDString(Record[1]),
1818 getMDOrNull(Record[2]), Record[3],
1819 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1820 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1821 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1822 getMDOrNull(Record[12]))),
1823 NextMetadataNo);
1824 NextMetadataNo++;
1825 break;
1826 }
1828 if (Record.size() < 16 || Record.size() > 26)
1829 return error("Invalid record");
1830
1831 // If we have a UUID and this is not a forward declaration, lookup the
1832 // mapping.
1833 IsDistinct = Record[0] & 0x1;
1834 bool IsNotUsedInTypeRef = Record[0] & 2;
1835 bool SizeIsMetadata = Record[0] & 4;
1836 unsigned Tag = Record[1];
1837 MDString *Name = getMDString(Record[2]);
1838 Metadata *File = getMDOrNull(Record[3]);
1839 unsigned Line = Record[4];
1840 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1841 Metadata *BaseType = nullptr;
1842 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1843 return error("Alignment value is too large");
1844 uint32_t AlignInBits = Record[8];
1845 Metadata *OffsetInBits = nullptr;
1846 uint32_t NumExtraInhabitants = (Record.size() > 22) ? Record[22] : 0;
1847 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1848 Metadata *Elements = nullptr;
1849 unsigned RuntimeLang = Record[12];
1850 std::optional<uint32_t> EnumKind;
1851
1852 Metadata *VTableHolder = nullptr;
1853 Metadata *TemplateParams = nullptr;
1854 Metadata *Discriminator = nullptr;
1855 Metadata *DataLocation = nullptr;
1856 Metadata *Associated = nullptr;
1857 Metadata *Allocated = nullptr;
1858 Metadata *Rank = nullptr;
1859 Metadata *Annotations = nullptr;
1860 Metadata *Specification = nullptr;
1861 Metadata *BitStride = nullptr;
1862 auto *Identifier = getMDString(Record[15]);
1863 // If this module is being parsed so that it can be ThinLTO imported
1864 // into another module, composite types only need to be imported as
1865 // type declarations (unless full type definitions are requested).
1866 // Create type declarations up front to save memory. This is only
1867 // done for types which have an Identifier, and are therefore
1868 // subject to the ODR.
1869 //
1870 // buildODRType handles the case where this is type ODRed with a
1871 // definition needed by the importing module, in which case the
1872 // existing definition is used.
1873 //
1874 // We always import full definitions for anonymous composite types,
1875 // as without a name, debuggers cannot easily resolve a declaration
1876 // to its definition.
1877 if (IsImporting && !Opts.import_full_type_definitions && Identifier &&
1878 Name &&
1879 (Tag == dwarf::DW_TAG_enumeration_type ||
1880 Tag == dwarf::DW_TAG_class_type ||
1881 Tag == dwarf::DW_TAG_structure_type ||
1882 Tag == dwarf::DW_TAG_union_type)) {
1883 Flags = Flags | DINode::FlagFwdDecl;
1884 // This is a hack around preserving template parameters for simplified
1885 // template names - it should probably be replaced with a
1886 // DICompositeType flag specifying whether template parameters are
1887 // required on declarations of this type.
1888 StringRef NameStr = Name->getString();
1889 if (!NameStr.contains('<') || NameStr.starts_with("_STN|"))
1890 TemplateParams = getMDOrNull(Record[14]);
1891 } else {
1892 BaseType = getDITypeRefOrNull(Record[6]);
1893
1894 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1895
1896 Elements = getMDOrNull(Record[11]);
1897 VTableHolder = getDITypeRefOrNull(Record[13]);
1898 TemplateParams = getMDOrNull(Record[14]);
1899 if (Record.size() > 16)
1900 Discriminator = getMDOrNull(Record[16]);
1901 if (Record.size() > 17)
1902 DataLocation = getMDOrNull(Record[17]);
1903 if (Record.size() > 19) {
1904 Associated = getMDOrNull(Record[18]);
1905 Allocated = getMDOrNull(Record[19]);
1906 }
1907 if (Record.size() > 20) {
1908 Rank = getMDOrNull(Record[20]);
1909 }
1910 if (Record.size() > 21) {
1911 Annotations = getMDOrNull(Record[21]);
1912 }
1913 if (Record.size() > 23) {
1914 Specification = getMDOrNull(Record[23]);
1915 }
1916 if (Record.size() > 25)
1917 BitStride = getMDOrNull(Record[25]);
1918 }
1919
1920 if (Record.size() > 24 && Record[24] != dwarf::DW_APPLE_ENUM_KIND_invalid)
1921 EnumKind = Record[24];
1922
1923 // Eagerly resolve SizeInBits when ODR uniquing is enabled so buildODRType
1924 // can compare actual sizes rather than unresolved lazy-load placeholders.
1925 Metadata *SizeInBits = getMetadataOrConstant(
1926 SizeIsMetadata, Record[7],
1927 /*ForceLazyLoad=*/Identifier && Context.isODRUniquingDebugTypes());
1928
1929 DICompositeType *CT = nullptr;
1930 if (Identifier)
1932 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1933 SizeInBits, AlignInBits, OffsetInBits, Specification,
1934 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1935 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1936 Allocated, Rank, Annotations, BitStride);
1937
1938 // Create a node if we didn't get a lazy ODR type.
1939 if (!CT)
1940 CT = GET_OR_DISTINCT(
1941 DICompositeType,
1942 (Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1943 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1944 VTableHolder, TemplateParams, Identifier, Discriminator,
1945 DataLocation, Associated, Allocated, Rank, Annotations,
1946 Specification, NumExtraInhabitants, BitStride));
1947 if (!IsNotUsedInTypeRef && Identifier)
1948 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1949
1950 MetadataList.assignValue(CT, NextMetadataNo);
1951 NextMetadataNo++;
1952 break;
1953 }
1955 if (Record.size() < 3 || Record.size() > 4)
1956 return error("Invalid record");
1957 bool IsOldTypeArray = Record[0] < 2;
1958 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1959
1960 IsDistinct = Record[0] & 0x1;
1961 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1962 Metadata *Types = getMDOrNull(Record[2]);
1963 if (LLVM_UNLIKELY(IsOldTypeArray))
1964 Types = MetadataList.upgradeTypeArray(Types);
1965
1966 MetadataList.assignValue(
1967 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1968 NextMetadataNo);
1969 NextMetadataNo++;
1970 break;
1971 }
1972
1973 case bitc::METADATA_MODULE: {
1974 if (Record.size() < 5 || Record.size() > 9)
1975 return error("Invalid record");
1976
1977 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1978 IsDistinct = Record[0];
1979 MetadataList.assignValue(
1981 DIModule,
1982 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1983 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1984 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1985 getMDString(Record[4 + Offset]),
1986 Record.size() <= 7 ? 0 : Record[7],
1987 Record.size() <= 8 ? false : Record[8])),
1988 NextMetadataNo);
1989 NextMetadataNo++;
1990 break;
1991 }
1992
1993 case bitc::METADATA_FILE: {
1994 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1995 return error("Invalid record");
1996
1997 IsDistinct = Record[0];
1998 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1999 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
2000 // is not present. This matches up with the old internal representation,
2001 // and the old encoding for CSK_None in the ChecksumKind. The new
2002 // representation reserves the value 0 in the ChecksumKind to continue to
2003 // encode None in a backwards-compatible way.
2004 if (Record.size() > 4 && Record[3] && Record[4])
2005 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
2006 getMDString(Record[4]));
2007 MetadataList.assignValue(
2008 GET_OR_DISTINCT(DIFile,
2009 (Context, getMDString(Record[1]),
2010 getMDString(Record[2]), Checksum,
2011 Record.size() > 5 ? getMDString(Record[5]) : nullptr)),
2012 NextMetadataNo);
2013 NextMetadataNo++;
2014 break;
2015 }
2017 if (Record.size() < 14 || Record.size() > 24)
2018 return error("Invalid record");
2019
2020 // Ignore Record[0], which indicates whether this compile unit is
2021 // distinct. It's always distinct.
2022 IsDistinct = true;
2023
2024 const auto LangVersionMask = (uint64_t(1) << 63);
2025 const bool HasVersionedLanguage = Record[1] & LangVersionMask;
2026 const uint32_t LanguageVersion = Record.size() > 22 ? Record[22] : 0;
2027 // The dialect field is written by writeDICompileUnit as a small enum
2028 // value (see dwarf::LanguageDialectAttribute). Reject out-of-range
2029 // values rather than silently truncating to uint16_t; this keeps the
2030 // writer/reader invariant symmetric and surfaces malformed inputs.
2031 // Value 0 means "no dialect specified".
2032 if (Record.size() > 23 &&
2033 Record[23] > static_cast<uint64_t>(dwarf::DW_LLVM_LANG_DIALECT_max))
2034 return error("Invalid DICompileUnit dialect value");
2035 const uint16_t Dialect =
2036 Record.size() > 23 ? static_cast<uint16_t>(Record[23]) : uint16_t(0);
2037
2038 auto *CU = DICompileUnit::getDistinct(
2039 Context,
2040 HasVersionedLanguage
2041 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
2042 LanguageVersion, Dialect)
2043 : DISourceLanguageName(Record[1], Dialect),
2044 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
2045 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
2046 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2047 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
2048 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
2049 Record.size() <= 14 ? 0 : Record[14],
2050 Record.size() <= 16 ? true : Record[16],
2051 Record.size() <= 17 ? false : Record[17],
2052 Record.size() <= 18 ? 0 : Record[18],
2053 Record.size() <= 19 ? false : Record[19],
2054 // Keep these guarded for backwards-compatibility with older bitcode
2055 // records. Keep this index layout in sync with writeDICompileUnit:
2056 // index 20 is sysroot, 21 is SDK, 22 is source-language version, and
2057 // 23 is dialect (read above as raw enum value, where 0 means unset).
2058 Record.size() <= 20 ? nullptr : getMDString(Record[20]),
2059 Record.size() <= 21 ? nullptr : getMDString(Record[21]));
2060
2061 MetadataList.assignValue(CU, NextMetadataNo);
2062 NextMetadataNo++;
2063
2064 // Move the Upgrade the list of subprograms.
2065 if (Record[11])
2066 CUSubprograms.push_back({CU, Record[11]});
2067 break;
2068 }
2070 if (Record.size() < 18 || Record.size() > 22)
2071 return error("Invalid record");
2072
2073 bool HasSPFlags = Record[0] & 4;
2074
2077 if (!HasSPFlags)
2078 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
2079 else {
2080 Flags = static_cast<DINode::DIFlags>(Record[11]);
2081 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
2082 }
2083
2084 // Support for old metadata when
2085 // subprogram specific flags are placed in DIFlags.
2086 const unsigned DIFlagMainSubprogram = 1 << 21;
2087 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
2088 if (HasOldMainSubprogramFlag)
2089 // Remove old DIFlagMainSubprogram from DIFlags.
2090 // Note: This assumes that any future use of bit 21 defaults to it
2091 // being 0.
2092 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2093
2094 if (HasOldMainSubprogramFlag && HasSPFlags)
2095 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2096 else if (!HasSPFlags)
2097 SPFlags = DISubprogram::toSPFlags(
2098 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
2099 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
2100 /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
2101
2102 // All definitions should be distinct.
2103 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2104 // Version 1 has a Function as Record[15].
2105 // Version 2 has removed Record[15].
2106 // Version 3 has the Unit as Record[15].
2107 // Version 4 added thisAdjustment.
2108 // Version 5 repacked flags into DISPFlags, changing many element numbers.
2109 bool HasUnit = Record[0] & 2;
2110 if (!HasSPFlags && HasUnit && Record.size() < 19)
2111 return error("Invalid record");
2112 if (HasSPFlags && !HasUnit)
2113 return error("Invalid record");
2114 // Accommodate older formats.
2115 bool HasFn = false;
2116 bool HasThisAdj = true;
2117 bool HasThrownTypes = true;
2118 bool HasAnnotations = false;
2119 bool HasTargetFuncName = false;
2120 unsigned OffsetA = 0;
2121 unsigned OffsetB = 0;
2122 // Key instructions won't be enabled in old-format bitcode, so only
2123 // check it if HasSPFlags is true.
2124 bool UsesKeyInstructions = false;
2125 if (!HasSPFlags) {
2126 OffsetA = 2;
2127 OffsetB = 2;
2128 if (Record.size() >= 19) {
2129 HasFn = !HasUnit;
2130 OffsetB++;
2131 }
2132 HasThisAdj = Record.size() >= 20;
2133 HasThrownTypes = Record.size() >= 21;
2134 } else {
2135 HasAnnotations = Record.size() >= 19;
2136 HasTargetFuncName = Record.size() >= 20;
2137 UsesKeyInstructions = Record.size() >= 21 ? Record[20] : 0;
2138 }
2139
2140 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2141 DISubprogram *SP = GET_OR_DISTINCT(
2142 DISubprogram,
2143 (Context,
2144 getDITypeRefOrNull(Record[1]), // scope
2145 getMDString(Record[2]), // name
2146 getMDString(Record[3]), // linkageName
2147 getMDOrNull(Record[4]), // file
2148 Record[5], // line
2149 getMDOrNull(Record[6]), // type
2150 Record[7 + OffsetA], // scopeLine
2151 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
2152 Record[10 + OffsetA], // virtualIndex
2153 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
2154 Flags, // flags
2155 SPFlags, // SPFlags
2156 HasUnit ? CUorFn : nullptr, // unit
2157 getMDOrNull(Record[13 + OffsetB]), // templateParams
2158 getMDOrNull(Record[14 + OffsetB]), // declaration
2159 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
2160 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2161 : nullptr, // thrownTypes
2162 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2163 : nullptr, // annotations
2164 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2165 : nullptr, // targetFuncName
2166 UsesKeyInstructions));
2167 MetadataList.assignValue(SP, NextMetadataNo);
2168 NextMetadataNo++;
2169
2170 if (IsDistinct)
2171 NewDistinctSPs.push_back(SP);
2172
2173 // Upgrade sp->function mapping to function->sp mapping.
2174 if (HasFn) {
2175 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
2176 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2177 if (F->isMaterializable())
2178 // Defer until materialized; unmaterialized functions may not have
2179 // metadata.
2180 FunctionsWithSPs[F] = SP;
2181 else if (!F->empty())
2182 F->setSubprogram(SP);
2183 }
2184 }
2185 break;
2186 }
2188 if (Record.size() != 5)
2189 return error("Invalid record");
2190
2191 IsDistinct = Record[0];
2192 MetadataList.assignValue(
2193 GET_OR_DISTINCT(DILexicalBlock,
2194 (Context, getMDOrNull(Record[1]),
2195 getMDOrNull(Record[2]), Record[3], Record[4])),
2196 NextMetadataNo);
2197 NextMetadataNo++;
2198 break;
2199 }
2201 if (Record.size() != 4)
2202 return error("Invalid record");
2203
2204 IsDistinct = Record[0];
2205 MetadataList.assignValue(
2206 GET_OR_DISTINCT(DILexicalBlockFile,
2207 (Context, getMDOrNull(Record[1]),
2208 getMDOrNull(Record[2]), Record[3])),
2209 NextMetadataNo);
2210 NextMetadataNo++;
2211 break;
2212 }
2214 IsDistinct = Record[0] & 1;
2215 MetadataList.assignValue(
2216 GET_OR_DISTINCT(DICommonBlock,
2217 (Context, getMDOrNull(Record[1]),
2218 getMDOrNull(Record[2]), getMDString(Record[3]),
2219 getMDOrNull(Record[4]), Record[5])),
2220 NextMetadataNo);
2221 NextMetadataNo++;
2222 break;
2223 }
2225 // Newer versions of DINamespace dropped file and line.
2226 MDString *Name;
2227 if (Record.size() == 3)
2228 Name = getMDString(Record[2]);
2229 else if (Record.size() == 5)
2230 Name = getMDString(Record[3]);
2231 else
2232 return error("Invalid record");
2233
2234 IsDistinct = Record[0] & 1;
2235 bool ExportSymbols = Record[0] & 2;
2236 MetadataList.assignValue(
2237 GET_OR_DISTINCT(DINamespace,
2238 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2239 NextMetadataNo);
2240 NextMetadataNo++;
2241 break;
2242 }
2243 case bitc::METADATA_MACRO: {
2244 if (Record.size() != 5)
2245 return error("Invalid record");
2246
2247 IsDistinct = Record[0];
2248 MetadataList.assignValue(
2249 GET_OR_DISTINCT(DIMacro,
2250 (Context, Record[1], Record[2], getMDString(Record[3]),
2251 getMDString(Record[4]))),
2252 NextMetadataNo);
2253 NextMetadataNo++;
2254 break;
2255 }
2257 if (Record.size() != 5)
2258 return error("Invalid record");
2259
2260 IsDistinct = Record[0];
2261 MetadataList.assignValue(
2262 GET_OR_DISTINCT(DIMacroFile,
2263 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
2264 getMDOrNull(Record[4]))),
2265 NextMetadataNo);
2266 NextMetadataNo++;
2267 break;
2268 }
2270 if (Record.size() < 3 || Record.size() > 4)
2271 return error("Invalid record");
2272
2273 IsDistinct = Record[0];
2274 MetadataList.assignValue(
2275 GET_OR_DISTINCT(DITemplateTypeParameter,
2276 (Context, getMDString(Record[1]),
2277 getDITypeRefOrNull(Record[2]),
2278 (Record.size() == 4) ? getMDOrNull(Record[3])
2279 : getMDOrNull(false))),
2280 NextMetadataNo);
2281 NextMetadataNo++;
2282 break;
2283 }
2285 if (Record.size() < 5 || Record.size() > 6)
2286 return error("Invalid record");
2287
2288 IsDistinct = Record[0];
2289
2290 MetadataList.assignValue(
2292 DITemplateValueParameter,
2293 (Context, Record[1], getMDString(Record[2]),
2294 getDITypeRefOrNull(Record[3]),
2295 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
2296 (Record.size() == 6) ? getMDOrNull(Record[5])
2297 : getMDOrNull(Record[4]))),
2298 NextMetadataNo);
2299 NextMetadataNo++;
2300 break;
2301 }
2303 if (Record.size() < 11 || Record.size() > 13)
2304 return error("Invalid record");
2305
2306 IsDistinct = Record[0] & 1;
2307 unsigned Version = Record[0] >> 1;
2308
2309 if (Version == 2) {
2310 Metadata *Annotations = nullptr;
2311 if (Record.size() > 12)
2312 Annotations = getMDOrNull(Record[12]);
2313
2314 MetadataList.assignValue(
2315 GET_OR_DISTINCT(DIGlobalVariable,
2316 (Context, getMDOrNull(Record[1]),
2317 getMDString(Record[2]), getMDString(Record[3]),
2318 getMDOrNull(Record[4]), Record[5],
2319 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2320 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2321 Record[11], Annotations)),
2322 NextMetadataNo);
2323
2324 NextMetadataNo++;
2325 } else if (Version == 1) {
2326 // No upgrade necessary. A null field will be introduced to indicate
2327 // that no parameter information is available.
2328 MetadataList.assignValue(
2330 DIGlobalVariable,
2331 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2332 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2333 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2334 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
2335 NextMetadataNo);
2336
2337 NextMetadataNo++;
2338 } else if (Version == 0) {
2339 // Upgrade old metadata, which stored a global variable reference or a
2340 // ConstantInt here.
2341 NeedUpgradeToDIGlobalVariableExpression = true;
2342 Metadata *Expr = getMDOrNull(Record[9]);
2343 uint32_t AlignInBits = 0;
2344 if (Record.size() > 11) {
2345 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2346 return error("Alignment value is too large");
2347 AlignInBits = Record[11];
2348 }
2349 GlobalVariable *Attach = nullptr;
2350 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2351 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2352 Attach = GV;
2353 Expr = nullptr;
2354 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
2355 Expr = DIExpression::get(Context,
2356 {dwarf::DW_OP_constu, CI->getZExtValue(),
2357 dwarf::DW_OP_stack_value});
2358 } else {
2359 Expr = nullptr;
2360 }
2361 }
2362 DIGlobalVariable *DGV = GET_OR_DISTINCT(
2363 DIGlobalVariable,
2364 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2365 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2366 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2367 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
2368
2369 DIGlobalVariableExpression *&DGVE = GlobalVariableExpression[DGV];
2370 if (Attach || Expr) {
2371 if (!DGVE) {
2372 DGVE = DIGlobalVariableExpression::getDistinct(
2373 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
2374 }
2375 }
2376 if (Attach)
2377 Attach->addDebugInfo(DGVE);
2378
2379 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
2380 MetadataList.assignValue(MDNode, NextMetadataNo);
2381 NextMetadataNo++;
2382 } else
2383 return error("Invalid record");
2384
2385 break;
2386 }
2388 if (Record.size() != 1)
2389 return error("Invalid DIAssignID record.");
2390
2391 IsDistinct = Record[0] & 1;
2392 if (!IsDistinct)
2393 return error("Invalid DIAssignID record. Must be distinct");
2394
2395 MetadataList.assignValue(DIAssignID::getDistinct(Context), NextMetadataNo);
2396 NextMetadataNo++;
2397 break;
2398 }
2400 // 10th field is for the obseleted 'inlinedAt:' field.
2401 if (Record.size() < 8 || Record.size() > 10)
2402 return error("Invalid record");
2403
2404 IsDistinct = Record[0] & 1;
2405 bool HasAlignment = Record[0] & 2;
2406 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2407 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
2408 // this is newer version of record which doesn't have artificial tag.
2409 bool HasTag = !HasAlignment && Record.size() > 8;
2410 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
2411 uint32_t AlignInBits = 0;
2412 Metadata *Annotations = nullptr;
2413 if (HasAlignment) {
2414 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2415 return error("Alignment value is too large");
2416 AlignInBits = Record[8];
2417 if (Record.size() > 9)
2418 Annotations = getMDOrNull(Record[9]);
2419 }
2420
2421 MetadataList.assignValue(
2422 GET_OR_DISTINCT(DILocalVariable,
2423 (Context, getMDOrNull(Record[1 + HasTag]),
2424 getMDString(Record[2 + HasTag]),
2425 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2426 getDITypeRefOrNull(Record[5 + HasTag]),
2427 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2428 NextMetadataNo);
2429 NextMetadataNo++;
2430 break;
2431 }
2432 case bitc::METADATA_LABEL: {
2433 if (Record.size() < 5 || Record.size() > 7)
2434 return error("Invalid record");
2435
2436 IsDistinct = Record[0] & 1;
2437 uint64_t Line = Record[4];
2438 uint64_t Column = Record.size() > 5 ? Record[5] : 0;
2439 bool IsArtificial = Record[0] & 2;
2440 std::optional<unsigned> CoroSuspendIdx;
2441 if (Record.size() > 6) {
2442 uint64_t RawSuspendIdx = Record[6];
2443 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2444 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2445 return error("CoroSuspendIdx value is too large");
2446 CoroSuspendIdx = RawSuspendIdx;
2447 }
2448 }
2449
2450 MetadataList.assignValue(
2451 GET_OR_DISTINCT(DILabel,
2452 (Context, getMDOrNull(Record[1]),
2453 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2454 Column, IsArtificial, CoroSuspendIdx)),
2455 NextMetadataNo);
2456 NextMetadataNo++;
2457 break;
2458 }
2460 if (Record.size() < 1)
2461 return error("Invalid record");
2462
2463 IsDistinct = Record[0] & 1;
2464 uint64_t Version = Record[0] >> 1;
2465 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2466
2468 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2469 return Err;
2470
2471 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2472 NextMetadataNo);
2473 NextMetadataNo++;
2474 break;
2475 }
2477 if (Record.size() != 3)
2478 return error("Invalid record");
2479
2480 IsDistinct = Record[0];
2481 Metadata *Expr = getMDOrNull(Record[2]);
2482 if (!Expr)
2483 Expr = DIExpression::get(Context, {});
2484 MetadataList.assignValue(
2485 GET_OR_DISTINCT(DIGlobalVariableExpression,
2486 (Context, getMDOrNull(Record[1]), Expr)),
2487 NextMetadataNo);
2488 NextMetadataNo++;
2489 break;
2490 }
2492 if (Record.size() != 8)
2493 return error("Invalid record");
2494
2495 IsDistinct = Record[0];
2496 MetadataList.assignValue(
2497 GET_OR_DISTINCT(DIObjCProperty,
2498 (Context, getMDString(Record[1]),
2499 getMDOrNull(Record[2]), Record[3],
2500 /*GetterName=*/getMDString(Record[5]),
2501 /*SetterName=*/getMDString(Record[4]), Record[6],
2502 getDITypeRefOrNull(Record[7]))),
2503 NextMetadataNo);
2504 NextMetadataNo++;
2505 break;
2506 }
2508 if (Record.size() != 6)
2509 return error("Invalid record");
2510
2511 IsDistinct = Record[0];
2512 MetadataList.assignValue(
2513 GET_OR_DISTINCT(DIProperty, (Context, getMDString(Record[1]),
2514 getMDOrNull(Record[2]), Record[3],
2515 getDITypeRefOrNull(Record[4]),
2516 getMDOrNull(Record[5]))),
2517 NextMetadataNo);
2518 NextMetadataNo++;
2519 break;
2520 }
2522 if (Record.size() < 6 || Record.size() > 8)
2523 return error("Invalid DIImportedEntity record");
2524
2525 IsDistinct = Record[0];
2526 bool HasFile = (Record.size() >= 7);
2527 bool HasElements = (Record.size() >= 8);
2528 MetadataList.assignValue(
2529 GET_OR_DISTINCT(DIImportedEntity,
2530 (Context, Record[1], getMDOrNull(Record[2]),
2531 getDITypeRefOrNull(Record[3]),
2532 HasFile ? getMDOrNull(Record[6]) : nullptr,
2533 HasFile ? Record[4] : 0, getMDString(Record[5]),
2534 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2535 NextMetadataNo);
2536 NextMetadataNo++;
2537 break;
2538 }
2540 std::string String(Record.begin(), Record.end());
2541
2542 // Test for upgrading !llvm.loop.
2543 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2544 ++NumMDStringLoaded;
2546 MetadataList.assignValue(MD, NextMetadataNo);
2547 NextMetadataNo++;
2548 break;
2549 }
2551 auto CreateNextMDString = [&](StringRef Str) {
2552 // Modern bitcode encodes MDStrings via this bulk record, so mirror the
2553 // METADATA_STRING check above to arm the loop-attachment upgrader.
2554 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(Str);
2555 ++NumMDStringLoaded;
2556 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2557 NextMetadataNo++;
2558 };
2559 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2560 return Err;
2561 break;
2562 }
2564 if (Record.size() % 2 == 0)
2565 return error("Invalid record");
2566 unsigned ValueID = Record[0];
2567 if (ValueID >= ValueList.size())
2568 return error("Invalid record");
2569 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2570 if (Error Err = parseGlobalObjectAttachment(
2571 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2572 return Err;
2573 break;
2574 }
2575 case bitc::METADATA_KIND: {
2576 // Support older bitcode files that had METADATA_KIND records in a
2577 // block with METADATA_BLOCK_ID.
2578 if (Error Err = parseMetadataKindRecord(Record))
2579 return Err;
2580 break;
2581 }
2584 Elts.reserve(Record.size());
2585 for (uint64_t Elt : Record) {
2586 Metadata *MD = getMD(Elt);
2587 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2588 return error(
2589 "Invalid record: DIArgList should not contain forward refs");
2590 if (!isa<ValueAsMetadata>(MD))
2591 return error("Invalid record");
2593 }
2594
2595 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2596 NextMetadataNo++;
2597 break;
2598 }
2599 case bitc::METADATA_FLMD: {
2600 // MDFunctionLocalContext is never uniqued.
2601 IsDistinct = true;
2602 // Since we have several variable-length arrays in this metadata, we'll be
2603 // checking the number of records multiple times.
2604 size_t NumRecords = Record.size();
2605 // Minimal possible case, 1 Version/NonDebug record + 4 "size" records.
2606 if (NumRecords < 5)
2607 return error("Invalid record");
2608 bool IsNonDebug = Record[0] & 1;
2609 uint64_t Version = Record[0] >> 1;
2610 (void)Version;
2611 // FLMD comprises 3 arrays with a leading length field.
2612 uint64_t CurrentRecord = 1;
2613 MDFunctionLocalContext *NewFLMD =
2615 // Assign the metadata number now, so that we don't have to use forward
2616 // references for ourself.
2617 MetadataList.assignValue(NewFLMD, NextMetadataNo);
2618 // We don't represent SrcLocs or Scopes for nodebug contexts; we can simply
2619 // skip reading them.
2620 if (!IsNonDebug) {
2621 // Scopes
2622 uint64_t NumScopes = Record[CurrentRecord++];
2623 // Check we have enough remaining records for NumScopes and 2 more sizes.
2624 if (NumRecords - CurrentRecord < NumScopes + 2)
2625 return error("Invalid record");
2626 // NB: Keeping the FwdRefs array as a raw pointer won't work if this
2627 // function recurses from here or if the root array otherwise ends up
2628 // being written to.
2629 SmallVectorImpl<uint64_t> *ScopeFwdRefs = nullptr;
2630 for (uint64_t ScopeIdx = 0; ScopeIdx < NumScopes; ++ScopeIdx) {
2631 uint64_t Scope = Record[CurrentRecord++];
2632 auto *ScopeMD = getMD(Scope);
2633 // If the Scope metadata has already been loaded then use it, otherwise
2634 // track the forward reference.
2635 if (auto *ScopeNode = dyn_cast<DILocalScope>(ScopeMD)) {
2636 NewFLMD->Scopes.push_back(FLScope(ScopeNode));
2637 } else {
2638 if (!ScopeFwdRefs) {
2639 FLMDScopeMetadataIDs.push_back({NewFLMD, {}});
2640 ScopeFwdRefs = &FLMDScopeMetadataIDs.back().second;
2641 ScopeFwdRefs->resize_for_overwrite(NumScopes);
2642 }
2643 (*ScopeFwdRefs)[ScopeIdx] = Scope;
2644 NewFLMD->Scopes.push_back(FLScope(nullptr));
2645 }
2646 }
2647 // SrcLocs
2648 uint64_t NumSrcLocs = Record[CurrentRecord++];
2649 // Check we have enough remaining records for NumSrcLocs and 1 more size.
2650 if (NumRecords - CurrentRecord < (NumSrcLocs * 3) + 1)
2651 return error("Invalid record");
2652 for (uint64_t SrcLocIdx = 0; SrcLocIdx < NumSrcLocs; ++SrcLocIdx) {
2653 uint32_t Line = Record[CurrentRecord++];
2654 uint16_t Column = Record[CurrentRecord++];
2655 uint16_t RawScopeIdx = Record[CurrentRecord++];
2656 NewFLMD->SrcLocs.push_back(
2657 FLSrcLoc(Line, Column, FLIndex<FLScope>::fromRaw(RawScopeIdx)));
2658 }
2659 }
2660 // InlinedCalls
2661 uint64_t NumInlinedCalls = Record[CurrentRecord++];
2662 // Check we have exactly enough remaining records for NumInlinedCalls.
2663 if (NumRecords - CurrentRecord != (NumInlinedCalls * 3))
2664 return error("Invalid record");
2665 // NB: Keeping the FwdRefs array as a raw pointer won't work if this
2666 // function recurses from here or if the root array otherwise ends up being
2667 // written to.
2668 SmallVectorImpl<uint64_t> *InlinedCallFwdRefs = nullptr;
2669 for (uint64_t InlinedCallIdx = 0; InlinedCallIdx < NumInlinedCalls;
2670 ++InlinedCallIdx) {
2671 uint32_t RawSrcLocIdx = Record[CurrentRecord++];
2672 // InlinedAtIdx + Uniquable share a record to save space.
2673 uint32_t RawInlinedAtUniquable = Record[CurrentRecord++];
2674 uint16_t RawInlinedAtIdx = RawInlinedAtUniquable >> 1;
2675 bool Uniquable = RawInlinedAtUniquable & 1;
2676 uint64_t InlineeContext = Record[CurrentRecord++];
2677 auto *InlineeMD = getMD(InlineeContext);
2678 if (MDFunctionLocalContext *InlineeFLContext =
2680 NewFLMD->InlinedCalls.push_back(
2681 FLInlinedCall(FLIndex<FLSrcLoc>::fromRaw(RawSrcLocIdx),
2682 FLIndex<FLInlinedCall>::fromRaw(RawInlinedAtIdx),
2683 InlineeFLContext, Uniquable));
2684 } else {
2685 if (!InlinedCallFwdRefs) {
2686 FLMDInlineeMetadataIDs.push_back({NewFLMD, {}});
2687 InlinedCallFwdRefs = &FLMDInlineeMetadataIDs.back().second;
2688 InlinedCallFwdRefs->resize_for_overwrite(NumInlinedCalls);
2689 }
2690 (*InlinedCallFwdRefs)[InlinedCallIdx] = InlineeContext;
2691 NewFLMD->InlinedCalls.push_back(
2692 FLInlinedCall(FLIndex<FLSrcLoc>::fromRaw(RawSrcLocIdx),
2693 FLIndex<FLInlinedCall>::fromRaw(RawInlinedAtIdx),
2694 nullptr, Uniquable));
2695 }
2696 }
2697 NextMetadataNo++;
2698 break;
2699 }
2700 }
2701 return Error::success();
2702#undef GET_OR_DISTINCT
2703}
2704
2705Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2706 ArrayRef<uint64_t> Record, StringRef Blob,
2707 function_ref<void(StringRef)> CallBack) {
2708 // All the MDStrings in the block are emitted together in a single
2709 // record. The strings are concatenated and stored in a blob along with
2710 // their sizes.
2711 if (Record.size() != 2)
2712 return error("Invalid record: metadata strings layout");
2713
2714 unsigned NumStrings = Record[0];
2715 unsigned StringsOffset = Record[1];
2716 if (!NumStrings)
2717 return error("Invalid record: metadata strings with no strings");
2718 if (StringsOffset > Blob.size())
2719 return error("Invalid record: metadata strings corrupt offset");
2720
2721 StringRef Lengths = Blob.slice(0, StringsOffset);
2722 SimpleBitstreamCursor R(Lengths);
2723
2724 StringRef Strings = Blob.drop_front(StringsOffset);
2725 do {
2726 if (R.AtEndOfStream())
2727 return error("Invalid record: metadata strings bad length");
2728
2729 uint32_t Size;
2730 if (Error E = R.ReadVBR(6).moveInto(Size))
2731 return E;
2732 if (Strings.size() < Size)
2733 return error("Invalid record: metadata strings truncated chars");
2734
2735 CallBack(Strings.slice(0, Size));
2736 Strings = Strings.drop_front(Size);
2737 } while (--NumStrings);
2738
2739 return Error::success();
2740}
2741
2742Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2743 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2744 assert(Record.size() % 2 == 0);
2745 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2746 auto K = MDKindMap.find(Record[I]);
2747 if (K == MDKindMap.end())
2748 return error("Invalid ID");
2749 MDNode *MD =
2750 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2751 if (!MD)
2752 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2753 GO.addMetadata(K->second, *MD);
2754 }
2755 return Error::success();
2756}
2757
2758/// Parse metadata attachments.
2760 Function &F, ArrayRef<Instruction *> InstructionList) {
2761 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2762 return Err;
2763
2765 PlaceholderQueue Placeholders;
2766
2767 while (true) {
2768 BitstreamEntry Entry;
2769 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2770 return E;
2771
2772 switch (Entry.Kind) {
2773 case BitstreamEntry::SubBlock: // Handled for us already.
2775 return error("Malformed block");
2777 LLVM_DEBUG(llvm::dbgs() << "\nAttachment metadata loading: ");
2778 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2779 return Error::success();
2781 // The interesting case.
2782 break;
2783 }
2784
2785 // Read a metadata attachment record.
2786 Record.clear();
2787 ++NumMDRecordLoaded;
2788 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2789 if (!MaybeRecord)
2790 return MaybeRecord.takeError();
2791 switch (MaybeRecord.get()) {
2792 default: // Default behavior: ignore.
2793 break;
2795 unsigned RecordLength = Record.size();
2796 if (Record.empty())
2797 return error("Invalid record");
2798 if (RecordLength % 2 == 0) {
2799 // A function attachment.
2800 if (Error Err = parseGlobalObjectAttachment(F, Record))
2801 return Err;
2802 continue;
2803 }
2804
2805 // An instruction attachment.
2806 Instruction *Inst = InstructionList[Record[0]];
2807 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2808 unsigned Kind = Record[i];
2809 auto I = MDKindMap.find(Kind);
2810 if (I == MDKindMap.end())
2811 return error("Invalid ID");
2812 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2813 continue;
2814
2815 auto Idx = Record[i + 1];
2816 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2817 !MetadataList.lookup(Idx)) {
2818 // Load the attachment if it is in the lazy-loadable range and hasn't
2819 // been loaded yet.
2820 lazyLoadOneMetadata(Idx, Placeholders);
2821 LLVM_DEBUG(llvm::dbgs() << "\nLazy attachment metadata loading: ");
2822 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2823 }
2824
2825 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2827 // Drop the attachment. This used to be legal, but there's no
2828 // upgrade path.
2829 break;
2831 if (!MD)
2832 return error("Invalid metadata attachment");
2833
2834 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2836
2837 if (I->second == LLVMContext::MD_tbaa) {
2838 assert(!MD->isTemporary() && "should load MDs before attachments");
2839 MD = UpgradeTBAANode(*MD);
2840 } else if (I->second == LLVMContext::MD_tbaa_struct) {
2841 assert(!MD->isTemporary() && "should load MDs before attachments");
2842 MD = UpgradeTBAAStructNode(*MD);
2843 }
2844
2845 if (I->second == LLVMContext::MD_alias_scope ||
2846 I->second == LLVMContext::MD_noalias)
2847 MD = upgradeAliasScopeList(MD);
2848
2849 Inst->setMetadata(I->second, MD);
2850 }
2851 break;
2852 }
2853 }
2854 }
2855}
2856
2857/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2858Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2860 if (Record.size() < 2)
2861 return error("Invalid record");
2862
2863 unsigned Kind = Record[0];
2864 SmallString<8> Name(Record.begin() + 1, Record.end());
2865
2866 unsigned NewKind = TheModule.getMDKindID(Name.str());
2867 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2868 return error("Conflicting METADATA_KIND records");
2869 return Error::success();
2870}
2871
2872/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2874 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2875 return Err;
2876
2878
2879 // Read all the records.
2880 while (true) {
2881 BitstreamEntry Entry;
2882 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2883 return E;
2884
2885 switch (Entry.Kind) {
2886 case BitstreamEntry::SubBlock: // Handled for us already.
2888 return error("Malformed block");
2890 return Error::success();
2892 // The interesting case.
2893 break;
2894 }
2895
2896 // Read a record.
2897 Record.clear();
2898 ++NumMDRecordLoaded;
2899 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2900 if (!MaybeCode)
2901 return MaybeCode.takeError();
2902 switch (MaybeCode.get()) {
2903 default: // Default behavior: ignore.
2904 break;
2905 case bitc::METADATA_KIND: {
2906 if (Error Err = parseMetadataKindRecord(Record))
2907 return Err;
2908 break;
2909 }
2910 }
2911 }
2912}
2913
2915 Pimpl = std::move(RHS.Pimpl);
2916 return *this;
2917}
2919 : Pimpl(std::move(RHS.Pimpl)) {}
2920
2923 BitcodeReaderValueList &ValueList,
2924 bool IsImporting,
2925 MetadataLoaderCallbacks Callbacks)
2926 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2927 Stream, TheModule, ValueList, std::move(Callbacks), IsImporting)) {}
2928
2929Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2930 return Pimpl->parseMetadata(ModuleLevel);
2931}
2932
2933bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2934
2935/// Return the given metadata, creating a replaceable forward reference if
2936/// necessary.
2938 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2939}
2940
2942 return Pimpl->lookupSubprogramForFunction(F);
2943}
2944
2946 Function &F, ArrayRef<Instruction *> InstructionList) {
2947 return Pimpl->parseMetadataAttachment(F, InstructionList);
2948}
2949
2951 return Pimpl->parseMetadataKinds();
2952}
2953
2954void MetadataLoader::setStripTBAA(bool StripTBAA) {
2955 return Pimpl->setStripTBAA(StripTBAA);
2956}
2957
2958bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2959
2960unsigned MetadataLoader::size() const { return Pimpl->size(); }
2961void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2962
2964 return Pimpl->upgradeDebugIntrinsics(F);
2965}
2966
2968 return Pimpl->upgradeAliasScopeList(ScopeList);
2969}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:348
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:347
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.
static APFloat flush(APFloat Value, DenormalMode::DenormalModeKind Mode)
Definition FPFold.cpp:22
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, GsymDataExtractor &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:54
#define I(x, y, z)
Definition MD5.cpp:57
static Value * getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx, Type *Ty, unsigned TyID)
static int64_t unrotateSign(uint64_t U)
This file contains the declarations for metadata subclasses.
Type::TypeID TypeID
RISCVCC::CondCode CC
Func getContext().diagnose(DiagnosticInfoUnsupported(Func
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
static bool parseMetadata(const StringRef &Input, uint64_t &FunctionHash, uint32_t &Attributes)
Parse Input that contains metadata.
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:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
#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.
MDNode * upgradeAliasScopeList(MDNode *ScopeList)
Error parseMetadata(bool ModuleLevel)
Parse a METADATA_BLOCK.
DISubprogram * lookupSubprogramForFunction(Function *F)
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
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.
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...
Error JumpToBit(uint64_t NewBitNo)
Reset the stream to the specified bit number.
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:549
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 pair of DIGlobalVariable and DIExpression.
A scope for locals.
DIFlags
Debug info flags.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
LLVM_ABI void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
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....
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
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
static FLIndex fromRaw(IndexType RawIndex)
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:76
static LocalAsMetadata * get(Value *Local)
Definition Metadata.h:575
static LLVM_ABI MDFunctionLocalContext * getDistinct(LLVMContext &Context, bool NonDebug=false)
Metadata node.
Definition Metadata.h:1087
LLVM_ABI void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1596
bool isTemporary() const
Definition Metadata.h:1271
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1600
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
A single uniqued string.
Definition Metadata.h:734
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:595
Tuple of metadata.
Definition Metadata.h:1505
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1534
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1554
MDNode * upgradeAliasScopeList(MDNode *ScopeList)
Mark any domains in ScopeList that don't have a disjointness flag as non-disjoint.
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:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator end() const
Definition ArrayRef.h:339
iterator begin() const
Definition ArrayRef.h:338
A tuple of MDNodes.
Definition Metadata.h:1806
iterator_range< op_iterator > operands()
Definition Metadata.h:1902
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:295
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:627
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:712
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool contains(StringRef Other) const
Return true if the given string is a substring of *this, and false otherwise.
Definition StringRef.h:438
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:46
bool isVoidTy() const
Return true if this is 'void'.
Definition Type.h:141
bool isMetadataTy() const
Return true if this is 'metadata'.
Definition Type.h:228
static LLVM_ABI ValueAsMetadata * get(Value *V)
Definition Metadata.cpp:512
LLVM Value Representation.
Definition Value.h:75
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
An efficient, type-erasing, non-owning reference to a callable.
constexpr char LanguageVersion[]
Key for Kernel::Metadata::mLanguageVersion.
@ Entry
Definition COFF.h:862
constexpr MCPhysReg SP
@ 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_LAYERLOCLIST
@ 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
@ DW_LLVM_LANG_DIALECT_max
Definition Dwarf.h:212
@ DW_OP_LLVM_fragment
Only used in LLVM metadata.
Definition Dwarf.h:144
@ DW_APPLE_ENUM_KIND_invalid
Enum kind for invalid results.
Definition Dwarf.h:51
NodeAddr< CodeNode * > Code
Definition RDFGraph.h:388
bool empty() const
Definition BasicBlock.h:101
iterator end() const
Definition BasicBlock.h:89
LLVM_ABI Instruction & back() const
LLVM_ABI iterator begin() const
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto cast_if_present(const Y &Val)
cast_if_present<X> - Functionally identical to cast, except that a null value is accepted.
Definition Casting.h:683
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
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:1685
@ Unknown
Not known to have no common set bits.
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:643
constexpr NextUseDistance min(NextUseDistance A, NextUseDistance B)
LLVM_ABI MDNode * upgradeInstructionLoopAttachment(MDNode &N)
Upgrade the loop attachment metadata node.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
auto cast_or_null(const Y &Val)
Definition Casting.h:714
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
static const DIScope * getScope(const NodeT *N)
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
const BitReaderOptions & getBitReaderOptions(const LLVMContext &C)
bool mayBeOldLoopAttachmentTag(StringRef Name)
Check whether a string looks like an old loop attachment tag.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI MDNode * UpgradeTBAAStructNode(MDNode &TBAAStructNode)
If the given !tbaa.struct node has old-style scalar field tags, return an equivalent node with each f...
LLVM_ABI MDNode * UpgradeAliasScopeList(MDNode &ScopeList, DenseMap< MDNode *, MDNode * > &UpgradedAliasScopes)
Mark any domains from scopes in ScopeList that don't have a disjointness flag as non-disjoint.
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:547
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
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
constexpr NextUseDistance max(NextUseDistance A, NextUseDistance B)
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:1933
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI APInt readWideAPInt(ArrayRef< uint64_t > Vals, unsigned TypeBits)
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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:1106
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...