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