LLVM 23.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 DILocalScope to the enclosing DISubprogram, if any.
470
471 /// True if metadata is being parsed for a module being ThinLTO imported.
472 bool IsImporting = false;
473
474 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
475 PlaceholderQueue &Placeholders, StringRef Blob,
476 unsigned &NextMetadataNo);
477 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
478 function_ref<void(StringRef)> CallBack);
479 Error parseGlobalObjectAttachment(GlobalObject &GO,
481 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
482
483 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
484
485 /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
486 void upgradeCUSubprograms() {
487 for (auto CU_SP : CUSubprograms)
488 if (auto *SPs =
489 dyn_cast_or_null<MDTuple>(MetadataList.lookup(CU_SP.second - 1)))
490 for (auto &Op : SPs->operands())
491 if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
492 SP->replaceUnit(CU_SP.first);
493 CUSubprograms.clear();
494 }
495
496 /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
497 void upgradeCUVariables() {
498 if (!NeedUpgradeToDIGlobalVariableExpression)
499 return;
500
501 // Upgrade list of variables attached to the CUs.
502 if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
503 for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
504 auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
505 if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
506 for (unsigned I = 0; I < GVs->getNumOperands(); I++)
507 if (auto *GV =
508 dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
510 Context, GV, DIExpression::get(Context, {}));
511 GVs->replaceOperandWith(I, DGVE);
512 }
513 }
514
515 // Upgrade variables attached to globals.
516 for (auto &GV : TheModule.globals()) {
518 GV.getMetadata(LLVMContext::MD_dbg, MDs);
519 GV.eraseMetadata(LLVMContext::MD_dbg);
520 for (auto *MD : MDs)
521 if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
523 Context, DGV, DIExpression::get(Context, {}));
524 GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
525 } else
526 GV.addMetadata(LLVMContext::MD_dbg, *MD);
527 }
528 }
529
530 DISubprogram *findEnclosingSubprogram(DILocalScope *S) {
531 if (!S)
532 return nullptr;
533 if (auto *SP = ParentSubprogram[S]) {
534 return SP;
535 }
536
537 DILocalScope *InitialScope = S;
539 while (S && !isa<DISubprogram>(S)) {
541 if (!Visited.insert(S).second)
542 break;
543 }
544
545 return ParentSubprogram[InitialScope] =
547 }
548
549 /// Move local imports from DICompileUnit's 'imports' field to
550 /// DISubprogram's retainedNodes.
551 /// Move function-local enums from DICompileUnit's enums
552 /// to DISubprogram's retainedNodes.
553 void upgradeCULocals() {
554 NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu");
555 if (!CUNodes)
556 return;
557
558 // Filter out elements of ToRemove from tuple T.
559 auto FilterTuple = [this](MDNode *T,
562 for (Metadata *Op : T->operands())
563 if (!ToRemove.contains(Op))
564 Result.push_back(Op);
565 return MDTuple::get(Context, Result);
566 };
567
568 // For each CU:
569 // - Collect local metadata nodes from CU's imports: and enums: lists in
570 // MetadataToRemove set.
571 // - Remove metadata nodes of MetadataToRemove set from CU's imports: and
572 // enums: lists.
573 // - Group MetadataToRemove items by their parent subprograms (in
574 // SPToEntities map).
575 // - For each subprogram SP in SPToEntities:
576 // - Append collected local metadata nodes to SP's retainedNodes: list.
577 for (MDNode *N : CUNodes->operands()) {
579 if (!CU)
580 continue;
581
582 SetVector<Metadata *> MetadataToRemove;
583 // Collect imported entities to be moved.
584 if (CU->getRawImportedEntities())
585 for (Metadata *Op : CU->getImportedEntities()->operands()) {
586 auto *IE = cast<DIImportedEntity>(Op);
587 if (isa_and_nonnull<DILocalScope>(IE->getScope()))
588 MetadataToRemove.insert(IE);
589 }
590 // Collect enums to be moved.
591 if (CU->getRawEnumTypes())
592 for (Metadata *Op : CU->getEnumTypes()->operands()) {
593 auto *Enum = cast<DICompositeType>(Op);
594 if (isa_and_nonnull<DILocalScope>(Enum->getScope()))
595 MetadataToRemove.insert(Enum);
596 }
597
598 if (MetadataToRemove.empty())
599 continue;
600
601 // Remove entities with local scope from CU.
602 if (CU->getRawImportedEntities())
603 CU->replaceImportedEntities(
604 FilterTuple(CU->getImportedEntities().get(), MetadataToRemove));
605
606 // Remove enums with local scope from CU.
607 if (CU->getRawEnumTypes())
608 CU->replaceEnumTypes(
609 FilterTuple(CU->getEnumTypes().get(), MetadataToRemove));
610
611 // Find DISubprogram corresponding to each entity.
613 for (auto *I : MetadataToRemove) {
614 DILocalScope *Scope =
616 if (auto *SP = findEnclosingSubprogram(Scope))
617 SPToEntities[SP].push_back(I);
618 }
619
620 // Update DISubprograms' retainedNodes.
621 for (auto I = SPToEntities.begin(); I != SPToEntities.end(); ++I) {
622 auto *SP = I->first;
623 auto RetainedNodes = SP->getRetainedNodes();
624 SmallVector<Metadata *> MDs(RetainedNodes.begin(), RetainedNodes.end());
625 MDs.append(I->second);
626 SP->replaceRetainedNodes(MDNode::get(Context, MDs));
627 }
628 }
629
630 ParentSubprogram.clear();
631 }
632
633 /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
634 /// describes a function argument.
635 void upgradeDeclareExpressions(Function &F) {
636 if (!NeedDeclareExpressionUpgrade)
637 return;
638
639 auto UpdateDeclareIfNeeded = [&](auto *Declare) {
640 auto *DIExpr = Declare->getExpression();
641 if (!DIExpr || !DIExpr->startsWithDeref() ||
642 !isa_and_nonnull<Argument>(Declare->getAddress()))
643 return;
645 Ops.append(std::next(DIExpr->elements_begin()), DIExpr->elements_end());
646 Declare->setExpression(DIExpression::get(Context, Ops));
647 };
648
649 for (auto &BB : F)
650 for (auto &I : BB) {
651 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange())) {
652 if (DVR.isDbgDeclare())
653 UpdateDeclareIfNeeded(&DVR);
654 }
655 if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
656 UpdateDeclareIfNeeded(DDI);
657 }
658 }
659
660 /// Upgrade the expression from previous versions.
661 Error upgradeDIExpression(uint64_t FromVersion,
664 auto N = Expr.size();
665 switch (FromVersion) {
666 default:
667 return error("Invalid record");
668 case 0:
669 if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
670 Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
671 [[fallthrough]];
672 case 1:
673 // Move DW_OP_deref to the end.
674 if (N && Expr[0] == dwarf::DW_OP_deref) {
675 auto End = Expr.end();
676 if (Expr.size() >= 3 &&
677 *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
678 End = std::prev(End, 3);
679 std::move(std::next(Expr.begin()), End, Expr.begin());
680 *std::prev(End) = dwarf::DW_OP_deref;
681 }
682 NeedDeclareExpressionUpgrade = true;
683 [[fallthrough]];
684 case 2: {
685 // Change DW_OP_plus to DW_OP_plus_uconst.
686 // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
687 auto SubExpr = ArrayRef<uint64_t>(Expr);
688 while (!SubExpr.empty()) {
689 // Skip past other operators with their operands
690 // for this version of the IR, obtained from
691 // from historic DIExpression::ExprOperand::getSize().
692 size_t HistoricSize;
693 switch (SubExpr.front()) {
694 default:
695 HistoricSize = 1;
696 break;
697 case dwarf::DW_OP_constu:
698 case dwarf::DW_OP_minus:
699 case dwarf::DW_OP_plus:
700 HistoricSize = 2;
701 break;
703 HistoricSize = 3;
704 break;
705 }
706
707 // If the expression is malformed, make sure we don't
708 // copy more elements than we should.
709 HistoricSize = std::min(SubExpr.size(), HistoricSize);
710 ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize - 1);
711
712 switch (SubExpr.front()) {
713 case dwarf::DW_OP_plus:
714 Buffer.push_back(dwarf::DW_OP_plus_uconst);
715 Buffer.append(Args.begin(), Args.end());
716 break;
717 case dwarf::DW_OP_minus:
718 Buffer.push_back(dwarf::DW_OP_constu);
719 Buffer.append(Args.begin(), Args.end());
720 Buffer.push_back(dwarf::DW_OP_minus);
721 break;
722 default:
723 Buffer.push_back(*SubExpr.begin());
724 Buffer.append(Args.begin(), Args.end());
725 break;
726 }
727
728 // Continue with remaining elements.
729 SubExpr = SubExpr.slice(HistoricSize);
730 }
731 Expr = MutableArrayRef<uint64_t>(Buffer);
732 [[fallthrough]];
733 }
734 case 3:
735 // Up-to-date!
736 break;
737 }
738
739 return Error::success();
740 }
741
742 /// Specifies which kind of debug info upgrade should be performed.
743 ///
744 /// The upgrade of compile units' enums: and imports: fields is performed
745 /// only when module level metadata block is loaded (i.e. all elements of
746 /// "llvm.dbg.cu" named metadata node are loaded).
747 enum class DebugInfoUpgradeMode {
748 /// No debug info upgrade.
749 None,
750 /// Debug info upgrade after loading function-level metadata block.
751 Partial,
752 /// Debug info upgrade after loading module-level metadata block.
753 ModuleLevel,
754 };
755
756 void upgradeDebugInfo(DebugInfoUpgradeMode Mode) {
757 if (Mode == DebugInfoUpgradeMode::None)
758 return;
759 upgradeCUSubprograms();
760 upgradeCUVariables();
761 if (Mode == DebugInfoUpgradeMode::ModuleLevel)
762 upgradeCULocals();
763 }
764
765 /// Prepare loaded metadata nodes to be used by loader clients.
766 void resolveLoadedMetadata(PlaceholderQueue &Placeholders,
767 DebugInfoUpgradeMode DIUpgradeMode) {
768 resolveForwardRefsAndPlaceholders(Placeholders);
769 upgradeDebugInfo(DIUpgradeMode);
771 LLVM_DEBUG(llvm::dbgs() << "Resolved loaded metadata. Cleaned up "
772 << NewDistinctSPs.size() << " subprogram(s).\n");
773 NewDistinctSPs.clear();
774 }
775
776 void callMDTypeCallback(Metadata **Val, unsigned TypeID);
777
778public:
780 BitcodeReaderValueList &ValueList,
781 MetadataLoaderCallbacks Callbacks, bool IsImporting)
782 : MetadataList(TheModule.getContext(), Stream.SizeInBytes()),
783 ValueList(ValueList), Stream(Stream), Context(TheModule.getContext()),
784 TheModule(TheModule), Callbacks(std::move(Callbacks)),
785 IsImporting(IsImporting) {}
786
787 Error parseMetadata(bool ModuleLevel);
788
789 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
790
792 if (ID < MDStringRef.size())
793 return lazyLoadOneMDString(ID);
794 if (auto *MD = MetadataList.lookup(ID))
795 return MD;
796 // If lazy-loading is enabled, we try recursively to load the operand
797 // instead of creating a temporary.
798 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
799 PlaceholderQueue Placeholders;
800 lazyLoadOneMetadata(ID, Placeholders);
801 LLVM_DEBUG(llvm::dbgs() << "\nLazy metadata loading: ");
802 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
803 return MetadataList.lookup(ID);
804 }
805 return MetadataList.getMetadataFwdRef(ID);
806 }
807
809 return FunctionsWithSPs.lookup(F);
810 }
811
812 bool hasSeenOldLoopTags() const { return HasSeenOldLoopTags; }
813
815 ArrayRef<Instruction *> InstructionList);
816
818
819 void setStripTBAA(bool Value) { StripTBAA = Value; }
820 bool isStrippingTBAA() const { return StripTBAA; }
821
822 unsigned size() const { return MetadataList.size(); }
823 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
824 void upgradeDebugIntrinsics(Function &F) { upgradeDeclareExpressions(F); }
825};
826
828MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
829 IndexCursor = Stream;
831 GlobalDeclAttachmentPos = 0;
832 // Get the abbrevs, and preload record positions to make them lazy-loadable.
833 while (true) {
834 uint64_t SavedPos = IndexCursor.GetCurrentBitNo();
835 BitstreamEntry Entry;
836 if (Error E =
837 IndexCursor
838 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
839 .moveInto(Entry))
840 return std::move(E);
841
842 switch (Entry.Kind) {
843 case BitstreamEntry::SubBlock: // Handled for us already.
845 return error("Malformed block");
847 return true;
848 }
850 // The interesting case.
851 ++NumMDRecordLoaded;
852 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
853 unsigned Code;
854 if (Error E = IndexCursor.skipRecord(Entry.ID).moveInto(Code))
855 return std::move(E);
856 switch (Code) {
858 // Rewind and parse the strings.
859 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
860 return std::move(Err);
861 StringRef Blob;
862 Record.clear();
863 if (Expected<unsigned> MaybeRecord =
864 IndexCursor.readRecord(Entry.ID, Record, &Blob))
865 ;
866 else
867 return MaybeRecord.takeError();
868 unsigned NumStrings = Record[0];
869 MDStringRef.reserve(NumStrings);
870 auto IndexNextMDString = [&](StringRef Str) {
871 MDStringRef.push_back(Str);
872 };
873 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
874 return std::move(Err);
875 break;
876 }
878 // This is the offset to the index, when we see this we skip all the
879 // records and load only an index to these.
880 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
881 return std::move(Err);
882 Record.clear();
883 if (Expected<unsigned> MaybeRecord =
884 IndexCursor.readRecord(Entry.ID, Record))
885 ;
886 else
887 return MaybeRecord.takeError();
888 if (Record.size() != 2)
889 return error("Invalid record");
890 auto Offset = Record[0] + (Record[1] << 32);
891 auto BeginPos = IndexCursor.GetCurrentBitNo();
892 if (Error Err = IndexCursor.JumpToBit(BeginPos + Offset))
893 return std::move(Err);
894 Expected<BitstreamEntry> MaybeEntry =
895 IndexCursor.advanceSkippingSubblocks(
897 if (!MaybeEntry)
898 return MaybeEntry.takeError();
899 Entry = MaybeEntry.get();
901 "Corrupted bitcode: Expected `Record` when trying to find the "
902 "Metadata index");
903 Record.clear();
904 if (Expected<unsigned> MaybeCode =
905 IndexCursor.readRecord(Entry.ID, Record))
906 assert(MaybeCode.get() == bitc::METADATA_INDEX &&
907 "Corrupted bitcode: Expected `METADATA_INDEX` when trying to "
908 "find the Metadata index");
909 else
910 return MaybeCode.takeError();
911 // Delta unpack
912 auto CurrentValue = BeginPos;
913 GlobalMetadataBitPosIndex.reserve(Record.size());
914 for (auto &Elt : Record) {
915 CurrentValue += Elt;
916 GlobalMetadataBitPosIndex.push_back(CurrentValue);
917 }
918 break;
919 }
921 // We don't expect to get there, the Index is loaded when we encounter
922 // the offset.
923 return error("Corrupted Metadata block");
924 case bitc::METADATA_NAME: {
925 // Named metadata need to be materialized now and aren't deferred.
926 if (Error Err = IndexCursor.JumpToBit(CurrentPos))
927 return std::move(Err);
928 Record.clear();
929
930 unsigned Code;
931 if (Expected<unsigned> MaybeCode =
932 IndexCursor.readRecord(Entry.ID, Record)) {
933 Code = MaybeCode.get();
935 } else
936 return MaybeCode.takeError();
937
938 // Read name of the named metadata.
939 SmallString<8> Name(Record.begin(), Record.end());
940 if (Expected<unsigned> MaybeCode = IndexCursor.ReadCode())
941 Code = MaybeCode.get();
942 else
943 return MaybeCode.takeError();
944
945 // Named Metadata comes in two parts, we expect the name to be followed
946 // by the node
947 Record.clear();
948 if (Expected<unsigned> MaybeNextBitCode =
949 IndexCursor.readRecord(Code, Record))
950 assert(MaybeNextBitCode.get() == bitc::METADATA_NAMED_NODE);
951 else
952 return MaybeNextBitCode.takeError();
953
954 // Read named metadata elements.
955 unsigned Size = Record.size();
956 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
957 for (unsigned i = 0; i != Size; ++i) {
958 // FIXME: We could use a placeholder here, however NamedMDNode are
959 // taking MDNode as operand and not using the Metadata infrastructure.
960 // It is acknowledged by 'TODO: Inherit from Metadata' in the
961 // NamedMDNode class definition.
962 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
963 assert(MD && "Invalid metadata: expect fwd ref to MDNode");
964 NMD->addOperand(MD);
965 }
966 break;
967 }
969 if (!GlobalDeclAttachmentPos)
970 GlobalDeclAttachmentPos = SavedPos;
971#ifndef NDEBUG
972 NumGlobalDeclAttachSkipped++;
973#endif
974 break;
975 }
1013 // We don't expect to see any of these, if we see one, give up on
1014 // lazy-loading and fallback.
1015 MDStringRef.clear();
1016 GlobalMetadataBitPosIndex.clear();
1017 return false;
1018 }
1019 break;
1020 }
1021 }
1022 }
1023}
1024
1025// Load the global decl attachments after building the lazy loading index.
1026// We don't load them "lazily" - all global decl attachments must be
1027// parsed since they aren't materialized on demand. However, by delaying
1028// their parsing until after the index is created, we can use the index
1029// instead of creating temporaries.
1030Expected<bool> MetadataLoader::MetadataLoaderImpl::loadGlobalDeclAttachments() {
1031 // Nothing to do if we didn't find any of these metadata records.
1032 if (!GlobalDeclAttachmentPos)
1033 return true;
1034 // Use a temporary cursor so that we don't mess up the main Stream cursor or
1035 // the lazy loading IndexCursor (which holds the necessary abbrev ids).
1036 BitstreamCursor TempCursor = Stream;
1037 SmallVector<uint64_t, 64> Record;
1038 // Jump to the position before the first global decl attachment, so we can
1039 // scan for the first BitstreamEntry record.
1040 if (Error Err = TempCursor.JumpToBit(GlobalDeclAttachmentPos))
1041 return std::move(Err);
1042 while (true) {
1043 BitstreamEntry Entry;
1044 if (Error E =
1045 TempCursor
1046 .advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd)
1047 .moveInto(Entry))
1048 return std::move(E);
1049
1050 switch (Entry.Kind) {
1051 case BitstreamEntry::SubBlock: // Handled for us already.
1053 return error("Malformed block");
1055 // Check that we parsed them all.
1056 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1057 return true;
1059 break;
1060 }
1061 uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
1062 Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
1063 if (!MaybeCode)
1064 return MaybeCode.takeError();
1065 if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
1066 // Anything other than a global decl attachment signals the end of
1067 // these records. Check that we parsed them all.
1068 assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
1069 return true;
1070 }
1071#ifndef NDEBUG
1072 NumGlobalDeclAttachParsed++;
1073#endif
1074 // FIXME: we need to do this early because we don't materialize global
1075 // value explicitly.
1076 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1077 return std::move(Err);
1078 Record.clear();
1079 if (Expected<unsigned> MaybeRecord =
1080 TempCursor.readRecord(Entry.ID, Record))
1081 ;
1082 else
1083 return MaybeRecord.takeError();
1084 if (Record.size() % 2 == 0)
1085 return error("Invalid record");
1086 unsigned ValueID = Record[0];
1087 if (ValueID >= ValueList.size())
1088 return error("Invalid record");
1089 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
1090 // Need to save and restore the current position since
1091 // parseGlobalObjectAttachment will resolve all forward references which
1092 // would require parsing from locations stored in the index.
1093 CurrentPos = TempCursor.GetCurrentBitNo();
1094 if (Error Err = parseGlobalObjectAttachment(
1095 *GO, ArrayRef<uint64_t>(Record).slice(1)))
1096 return std::move(Err);
1097 if (Error Err = TempCursor.JumpToBit(CurrentPos))
1098 return std::move(Err);
1099 }
1100 }
1101}
1102
1103void MetadataLoader::MetadataLoaderImpl::callMDTypeCallback(Metadata **Val,
1104 unsigned TypeID) {
1105 if (Callbacks.MDType) {
1106 (*Callbacks.MDType)(Val, TypeID, Callbacks.GetTypeByID,
1107 Callbacks.GetContainedTypeID);
1108 }
1109}
1110
1111/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1112/// module level metadata.
1114 llvm::TimeTraceScope timeScope("Parse metadata");
1115 if (!ModuleLevel && MetadataList.hasFwdRefs())
1116 return error("Invalid metadata: fwd refs into function blocks");
1117
1118 // Record the entry position so that we can jump back here and efficiently
1119 // skip the whole block in case we lazy-load.
1120 auto EntryPos = Stream.GetCurrentBitNo();
1121
1122 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1123 return Err;
1124
1126 PlaceholderQueue Placeholders;
1127 auto DIUpgradeMode = ModuleLevel ? DebugInfoUpgradeMode::ModuleLevel
1128 : DebugInfoUpgradeMode::Partial;
1129
1130 // We lazy-load module-level metadata: we build an index for each record, and
1131 // then load individual record as needed, starting with the named metadata.
1132 if (ModuleLevel && IsImporting && MetadataList.empty() &&
1134 auto SuccessOrErr = lazyLoadModuleMetadataBlock();
1135 if (!SuccessOrErr)
1136 return SuccessOrErr.takeError();
1137 if (SuccessOrErr.get()) {
1138 // An index was successfully created and we will be able to load metadata
1139 // on-demand.
1140 MetadataList.resize(MDStringRef.size() +
1141 GlobalMetadataBitPosIndex.size());
1142
1143 // Now that we have built the index, load the global decl attachments
1144 // that were deferred during that process. This avoids creating
1145 // temporaries.
1146 SuccessOrErr = loadGlobalDeclAttachments();
1147 if (!SuccessOrErr)
1148 return SuccessOrErr.takeError();
1149 assert(SuccessOrErr.get());
1150
1151 // Reading the named metadata created forward references and/or
1152 // placeholders, that we flush here.
1153 LLVM_DEBUG(llvm::dbgs() << "\nNamed metadata loading: ");
1154 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1155 // Return at the beginning of the block, since it is easy to skip it
1156 // entirely from there.
1157 Stream.ReadBlockEnd(); // Pop the abbrev block context.
1158 if (Error Err = IndexCursor.JumpToBit(EntryPos))
1159 return Err;
1160 if (Error Err = Stream.SkipBlock()) {
1161 // FIXME this drops the error on the floor, which
1162 // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1163 consumeError(std::move(Err));
1164 return Error::success();
1165 }
1166 return Error::success();
1167 }
1168 // Couldn't load an index, fallback to loading all the block "old-style".
1169 }
1170
1171 unsigned NextMetadataNo = MetadataList.size();
1172
1173 // Read all the records.
1174 while (true) {
1175 BitstreamEntry Entry;
1176 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
1177 return E;
1178
1179 switch (Entry.Kind) {
1180 case BitstreamEntry::SubBlock: // Handled for us already.
1182 return error("Malformed block");
1184 LLVM_DEBUG(llvm::dbgs() << "\nEager metadata loading: ");
1185 resolveLoadedMetadata(Placeholders, DIUpgradeMode);
1186 return Error::success();
1188 // The interesting case.
1189 break;
1190 }
1191
1192 // Read a record.
1193 Record.clear();
1194 StringRef Blob;
1195 ++NumMDRecordLoaded;
1196 if (Expected<unsigned> MaybeCode =
1197 Stream.readRecord(Entry.ID, Record, &Blob)) {
1198 if (Error Err = parseOneMetadata(Record, MaybeCode.get(), Placeholders,
1199 Blob, NextMetadataNo))
1200 return Err;
1201 } else
1202 return MaybeCode.takeError();
1203 }
1204}
1205
1206MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
1207 ++NumMDStringLoaded;
1208 if (Metadata *MD = MetadataList.lookup(ID))
1209 return cast<MDString>(MD);
1210 auto MDS = MDString::get(Context, MDStringRef[ID]);
1211 MetadataList.assignValue(MDS, ID);
1212 return MDS;
1213}
1214
1215void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
1216 unsigned ID, PlaceholderQueue &Placeholders) {
1217 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
1218 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
1219 // Lookup first if the metadata hasn't already been loaded.
1220 if (auto *MD = MetadataList.lookup(ID)) {
1221 auto *N = dyn_cast<MDNode>(MD);
1222 // If the node is not an MDNode, or if it is not temporary, then
1223 // we're done.
1224 if (!N || !N->isTemporary())
1225 return;
1226 }
1228 StringRef Blob;
1229 if (Error Err = IndexCursor.JumpToBit(
1230 GlobalMetadataBitPosIndex[ID - MDStringRef.size()]))
1231 report_fatal_error("lazyLoadOneMetadata failed jumping: " +
1232 Twine(toString(std::move(Err))));
1233 BitstreamEntry Entry;
1234 if (Error E = IndexCursor.advanceSkippingSubblocks().moveInto(Entry))
1235 // FIXME this drops the error on the floor.
1236 report_fatal_error("lazyLoadOneMetadata failed advanceSkippingSubblocks: " +
1237 Twine(toString(std::move(E))));
1238 ++NumMDRecordLoaded;
1239 if (Expected<unsigned> MaybeCode =
1240 IndexCursor.readRecord(Entry.ID, Record, &Blob)) {
1241 if (Error Err =
1242 parseOneMetadata(Record, MaybeCode.get(), Placeholders, Blob, ID))
1243 report_fatal_error("Can't lazyload MD, parseOneMetadata: " +
1244 Twine(toString(std::move(Err))));
1245 } else
1246 report_fatal_error("Can't lazyload MD: " +
1247 Twine(toString(MaybeCode.takeError())));
1248}
1249
1250/// Ensure that all forward-references and placeholders are resolved.
1251/// Iteratively lazy-loading metadata on-demand if needed.
1252void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
1253 PlaceholderQueue &Placeholders) {
1254 DenseSet<unsigned> Temporaries;
1255 while (true) {
1256 // Populate Temporaries with the placeholders that haven't been loaded yet.
1257 Placeholders.getTemporaries(MetadataList, Temporaries);
1258
1259 // If we don't have any temporary, or FwdReference, we're done!
1260 if (Temporaries.empty() && !MetadataList.hasFwdRefs())
1261 break;
1262
1263 // First, load all the temporaries. This can add new placeholders or
1264 // forward references.
1265 for (auto ID : Temporaries)
1266 lazyLoadOneMetadata(ID, Placeholders);
1267 Temporaries.clear();
1268
1269 // Second, load the forward-references. This can also add new placeholders
1270 // or forward references.
1271 while (MetadataList.hasFwdRefs())
1272 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
1273 }
1274 // At this point we don't have any forward reference remaining, or temporary
1275 // that haven't been loaded. We can safely drop RAUW support and mark cycles
1276 // as resolved.
1277 MetadataList.tryToResolveCycles();
1278
1279 // Finally, everything is in place, we can replace the placeholders operands
1280 // with the final node they refer to.
1281 Placeholders.flush(MetadataList);
1282}
1283
1284static Value *getValueFwdRef(BitcodeReaderValueList &ValueList, unsigned Idx,
1285 Type *Ty, unsigned TyID) {
1286 Value *V = ValueList.getValueFwdRef(Idx, Ty, TyID,
1287 /*ConstExprInsertBB*/ nullptr);
1288 if (V)
1289 return V;
1290
1291 // This is a reference to a no longer supported constant expression.
1292 // Pretend that the constant was deleted, which will replace metadata
1293 // references with poison.
1294 // TODO: This is a rather indirect check. It would be more elegant to use
1295 // a separate ErrorInfo for constant materialization failure and thread
1296 // the error reporting through getValueFwdRef().
1297 if (Idx < ValueList.size() && ValueList[Idx] &&
1298 ValueList[Idx]->getType() == Ty)
1299 return PoisonValue::get(Ty);
1300
1301 return nullptr;
1302}
1303
1304Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
1305 SmallVectorImpl<uint64_t> &Record, unsigned Code,
1306 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
1307
1308 bool IsDistinct = false;
1309 auto getMD = [&](unsigned ID) -> Metadata * {
1310 if (ID < MDStringRef.size())
1311 return lazyLoadOneMDString(ID);
1312 if (!IsDistinct) {
1313 if (auto *MD = MetadataList.lookup(ID))
1314 return MD;
1315 // If lazy-loading is enabled, we try recursively to load the operand
1316 // instead of creating a temporary.
1317 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
1318 // Create a temporary for the node that is referencing the operand we
1319 // will lazy-load. It is needed before recursing in case there are
1320 // uniquing cycles.
1321 MetadataList.getMetadataFwdRef(NextMetadataNo);
1322 lazyLoadOneMetadata(ID, Placeholders);
1323 return MetadataList.lookup(ID);
1324 }
1325 // Return a temporary.
1326 return MetadataList.getMetadataFwdRef(ID);
1327 }
1328 if (auto *MD = MetadataList.getMetadataIfResolved(ID))
1329 return MD;
1330 return &Placeholders.getPlaceholderOp(ID);
1331 };
1332 auto getMDOrNull = [&](unsigned ID) -> Metadata * {
1333 if (ID)
1334 return getMD(ID - 1);
1335 return nullptr;
1336 };
1337 auto getMDString = [&](unsigned ID) -> MDString * {
1338 // This requires that the ID is not really a forward reference. In
1339 // particular, the MDString must already have been resolved.
1340 auto MDS = getMDOrNull(ID);
1341 return cast_or_null<MDString>(MDS);
1342 };
1343
1344 // Support for old type refs.
1345 auto getDITypeRefOrNull = [&](unsigned ID) {
1346 return MetadataList.upgradeTypeRef(getMDOrNull(ID));
1347 };
1348
1349 auto getMetadataOrConstant = [&](bool IsMetadata,
1350 uint64_t Entry) -> Metadata * {
1351 if (IsMetadata)
1352 return getMDOrNull(Entry);
1354 ConstantInt::get(Type::getInt64Ty(Context), Entry));
1355 };
1356
1357#define GET_OR_DISTINCT(CLASS, ARGS) \
1358 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1359
1360 switch (Code) {
1361 default: // Default behavior: ignore.
1362 break;
1363 case bitc::METADATA_NAME: {
1364 // Read name of the named metadata.
1365 SmallString<8> Name(Record.begin(), Record.end());
1366 Record.clear();
1367 if (Error E = Stream.ReadCode().moveInto(Code))
1368 return E;
1369
1370 ++NumMDRecordLoaded;
1371 if (Expected<unsigned> MaybeNextBitCode = Stream.readRecord(Code, Record)) {
1372 if (MaybeNextBitCode.get() != bitc::METADATA_NAMED_NODE)
1373 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
1374 } else
1375 return MaybeNextBitCode.takeError();
1376
1377 // Read named metadata elements.
1378 unsigned Size = Record.size();
1379 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
1380 for (unsigned i = 0; i != Size; ++i) {
1381 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
1382 if (!MD)
1383 return error("Invalid named metadata: expect fwd ref to MDNode");
1384 NMD->addOperand(MD);
1385 }
1386 break;
1387 }
1389 // Deprecated, but still needed to read old bitcode files.
1390 // This is a LocalAsMetadata record, the only type of function-local
1391 // metadata.
1392 if (Record.size() % 2 == 1)
1393 return error("Invalid record");
1394
1395 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1396 // to be legal, but there's no upgrade path.
1397 auto dropRecord = [&] {
1398 MetadataList.assignValue(MDNode::get(Context, {}), NextMetadataNo);
1399 NextMetadataNo++;
1400 };
1401 if (Record.size() != 2) {
1402 dropRecord();
1403 break;
1404 }
1405
1406 unsigned TyID = Record[0];
1407 Type *Ty = Callbacks.GetTypeByID(TyID);
1408 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy()) {
1409 dropRecord();
1410 break;
1411 }
1412
1413 Value *V = ValueList.getValueFwdRef(Record[1], Ty, TyID,
1414 /*ConstExprInsertBB*/ nullptr);
1415 if (!V)
1416 return error("Invalid value reference from old fn metadata");
1417
1418 MetadataList.assignValue(LocalAsMetadata::get(V), NextMetadataNo);
1419 NextMetadataNo++;
1420 break;
1421 }
1423 // Deprecated, but still needed to read old bitcode files.
1424 if (Record.size() % 2 == 1)
1425 return error("Invalid record");
1426
1427 unsigned Size = Record.size();
1429 for (unsigned i = 0; i != Size; i += 2) {
1430 unsigned TyID = Record[i];
1431 Type *Ty = Callbacks.GetTypeByID(TyID);
1432 if (!Ty)
1433 return error("Invalid record");
1434 if (Ty->isMetadataTy())
1435 Elts.push_back(getMD(Record[i + 1]));
1436 else if (!Ty->isVoidTy()) {
1437 Value *V = getValueFwdRef(ValueList, Record[i + 1], Ty, TyID);
1438 if (!V)
1439 return error("Invalid value reference from old metadata");
1442 "Expected non-function-local metadata");
1443 callMDTypeCallback(&MD, TyID);
1444 Elts.push_back(MD);
1445 } else
1446 Elts.push_back(nullptr);
1447 }
1448 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1449 NextMetadataNo++;
1450 break;
1451 }
1452 case bitc::METADATA_VALUE: {
1453 if (Record.size() != 2)
1454 return error("Invalid record");
1455
1456 unsigned TyID = Record[0];
1457 Type *Ty = Callbacks.GetTypeByID(TyID);
1458 if (!Ty || Ty->isMetadataTy() || Ty->isVoidTy())
1459 return error("Invalid record");
1460
1461 Value *V = getValueFwdRef(ValueList, Record[1], Ty, TyID);
1462 if (!V)
1463 return error("Invalid value reference from metadata");
1464
1466 callMDTypeCallback(&MD, TyID);
1467 MetadataList.assignValue(MD, NextMetadataNo);
1468 NextMetadataNo++;
1469 break;
1470 }
1472 IsDistinct = true;
1473 [[fallthrough]];
1474 case bitc::METADATA_NODE: {
1476 Elts.reserve(Record.size());
1477 for (unsigned ID : Record)
1478 Elts.push_back(getMDOrNull(ID));
1479 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1480 : MDNode::get(Context, Elts),
1481 NextMetadataNo);
1482 NextMetadataNo++;
1483 break;
1484 }
1486 // 5: inlinedAt, 6: isImplicit, 8: Key Instructions fields.
1487 if (Record.size() != 5 && Record.size() != 6 && Record.size() != 8)
1488 return error("Invalid record");
1489
1490 IsDistinct = Record[0];
1491 unsigned Line = Record[1];
1492 unsigned Column = Record[2];
1493 Metadata *Scope = getMD(Record[3]);
1494 Metadata *InlinedAt = getMDOrNull(Record[4]);
1495 bool ImplicitCode = Record.size() >= 6 && Record[5];
1496 uint64_t AtomGroup = Record.size() == 8 ? Record[6] : 0;
1497 uint8_t AtomRank = Record.size() == 8 ? Record[7] : 0;
1498 MetadataList.assignValue(
1499 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt,
1500 ImplicitCode, AtomGroup, AtomRank)),
1501 NextMetadataNo);
1502 NextMetadataNo++;
1503 break;
1504 }
1506 if (Record.size() < 4)
1507 return error("Invalid record");
1508
1509 IsDistinct = Record[0];
1510 unsigned Tag = Record[1];
1511 unsigned Version = Record[2];
1512
1513 if (Tag >= 1u << 16 || Version != 0)
1514 return error("Invalid record");
1515
1516 auto *Header = getMDString(Record[3]);
1518 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1519 DwarfOps.push_back(getMDOrNull(Record[I]));
1520 MetadataList.assignValue(
1521 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1522 NextMetadataNo);
1523 NextMetadataNo++;
1524 break;
1525 }
1527 Metadata *Val = nullptr;
1528 // Operand 'count' is interpreted as:
1529 // - Signed integer (version 0)
1530 // - Metadata node (version 1)
1531 // Operand 'lowerBound' is interpreted as:
1532 // - Signed integer (version 0 and 1)
1533 // - Metadata node (version 2)
1534 // Operands 'upperBound' and 'stride' are interpreted as:
1535 // - Metadata node (version 2)
1536 switch (Record[0] >> 1) {
1537 case 0:
1538 Val = GET_OR_DISTINCT(DISubrange,
1539 (Context, Record[1], unrotateSign(Record[2])));
1540 break;
1541 case 1:
1542 Val = GET_OR_DISTINCT(DISubrange, (Context, getMDOrNull(Record[1]),
1543 unrotateSign(Record[2])));
1544 break;
1545 case 2:
1546 Val = GET_OR_DISTINCT(
1547 DISubrange, (Context, getMDOrNull(Record[1]), getMDOrNull(Record[2]),
1548 getMDOrNull(Record[3]), getMDOrNull(Record[4])));
1549 break;
1550 default:
1551 return error("Invalid record: Unsupported version of DISubrange");
1552 }
1553
1554 MetadataList.assignValue(Val, NextMetadataNo);
1555 IsDistinct = Record[0] & 1;
1556 NextMetadataNo++;
1557 break;
1558 }
1560 Metadata *Val = nullptr;
1561 Val = GET_OR_DISTINCT(DIGenericSubrange,
1562 (Context, getMDOrNull(Record[1]),
1563 getMDOrNull(Record[2]), getMDOrNull(Record[3]),
1564 getMDOrNull(Record[4])));
1565
1566 MetadataList.assignValue(Val, NextMetadataNo);
1567 IsDistinct = Record[0] & 1;
1568 NextMetadataNo++;
1569 break;
1570 }
1572 if (Record.size() < 3)
1573 return error("Invalid record");
1574
1575 IsDistinct = Record[0] & 1;
1576 bool IsUnsigned = Record[0] & 2;
1577 bool IsBigInt = Record[0] & 4;
1578 APInt Value;
1579
1580 if (IsBigInt) {
1581 const uint64_t BitWidth = Record[1];
1582 const size_t NumWords = Record.size() - 3;
1583 Value = readWideAPInt(ArrayRef(&Record[3], NumWords), BitWidth);
1584 } else
1585 Value = APInt(64, unrotateSign(Record[1]), !IsUnsigned);
1586
1587 MetadataList.assignValue(
1588 GET_OR_DISTINCT(DIEnumerator,
1589 (Context, Value, IsUnsigned, getMDString(Record[2]))),
1590 NextMetadataNo);
1591 NextMetadataNo++;
1592 break;
1593 }
1595 if (Record.size() < 6 || Record.size() > 12)
1596 return error("Invalid record");
1597
1598 IsDistinct = Record[0] & 1;
1599 bool SizeIsMetadata = Record[0] & 2;
1600 DINode::DIFlags Flags = (Record.size() > 6)
1601 ? static_cast<DINode::DIFlags>(Record[6])
1602 : DINode::FlagZero;
1603 uint32_t NumExtraInhabitants = (Record.size() > 7) ? Record[7] : 0;
1604 uint32_t DataSizeInBits = (Record.size() > 8) ? Record[8] : 0;
1605 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1606 Metadata *File = nullptr;
1607 unsigned LineNo = 0;
1608 Metadata *Scope = nullptr;
1609 if (Record.size() > 9) {
1610 File = getMDOrNull(Record[9]);
1611 LineNo = Record[10];
1612 Scope = getMDOrNull(Record[11]);
1613 }
1614 MetadataList.assignValue(
1615 GET_OR_DISTINCT(DIBasicType,
1616 (Context, Record[1], getMDString(Record[2]), File,
1617 LineNo, Scope, SizeInBits, Record[4], Record[5],
1618 NumExtraInhabitants, DataSizeInBits, Flags)),
1619 NextMetadataNo);
1620 NextMetadataNo++;
1621 break;
1622 }
1624 if (Record.size() < 11)
1625 return error("Invalid record");
1626
1627 IsDistinct = Record[0] & 1;
1628 bool SizeIsMetadata = Record[0] & 2;
1629 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[6]);
1630
1631 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[3]);
1632
1633 size_t Offset = 9;
1634
1635 auto ReadWideInt = [&]() {
1636 uint64_t Encoded = Record[Offset++];
1637 unsigned NumWords = Encoded >> 32;
1638 unsigned BitWidth = Encoded & 0xffffffff;
1639 auto Value = readWideAPInt(ArrayRef(&Record[Offset], NumWords), BitWidth);
1640 Offset += NumWords;
1641 return Value;
1642 };
1643
1644 APInt Numerator = ReadWideInt();
1645 APInt Denominator = ReadWideInt();
1646
1647 Metadata *File = nullptr;
1648 unsigned LineNo = 0;
1649 Metadata *Scope = nullptr;
1650
1651 if (Offset + 3 == Record.size()) {
1652 File = getMDOrNull(Record[Offset]);
1653 LineNo = Record[Offset + 1];
1654 Scope = getMDOrNull(Record[Offset + 2]);
1655 } else if (Offset != Record.size())
1656 return error("Invalid record");
1657
1658 MetadataList.assignValue(
1659 GET_OR_DISTINCT(DIFixedPointType,
1660 (Context, Record[1], getMDString(Record[2]), File,
1661 LineNo, Scope, SizeInBits, Record[4], Record[5], Flags,
1662 Record[7], Record[8], Numerator, Denominator)),
1663 NextMetadataNo);
1664 NextMetadataNo++;
1665 break;
1666 }
1668 if (Record.size() > 9 || Record.size() < 8)
1669 return error("Invalid record");
1670
1671 IsDistinct = Record[0] & 1;
1672 bool SizeIsMetadata = Record[0] & 2;
1673 bool SizeIs8 = Record.size() == 8;
1674 // StringLocationExp (i.e. Record[5]) is added at a later time
1675 // than the other fields. The code here enables backward compatibility.
1676 Metadata *StringLocationExp = SizeIs8 ? nullptr : getMDOrNull(Record[5]);
1677 unsigned Offset = SizeIs8 ? 5 : 6;
1678 Metadata *SizeInBits =
1679 getMetadataOrConstant(SizeIsMetadata, Record[Offset]);
1680
1681 MetadataList.assignValue(
1682 GET_OR_DISTINCT(DIStringType,
1683 (Context, Record[1], getMDString(Record[2]),
1684 getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1685 StringLocationExp, SizeInBits, Record[Offset + 1],
1686 Record[Offset + 2])),
1687 NextMetadataNo);
1688 NextMetadataNo++;
1689 break;
1690 }
1692 if (Record.size() < 12 || Record.size() > 15)
1693 return error("Invalid record");
1694
1695 // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1696 // that there is no DWARF address space associated with DIDerivedType.
1697 std::optional<unsigned> DWARFAddressSpace;
1698 if (Record.size() > 12 && Record[12])
1699 DWARFAddressSpace = Record[12] - 1;
1700
1701 Metadata *Annotations = nullptr;
1702 std::optional<DIDerivedType::PtrAuthData> PtrAuthData;
1703
1704 // Only look for annotations/ptrauth if both are allocated.
1705 // If not, we can't tell which was intended to be embedded, as both ptrauth
1706 // and annotations have been expected at Record[13] at various times.
1707 if (Record.size() > 14) {
1708 if (Record[13])
1709 Annotations = getMDOrNull(Record[13]);
1710 if (Record[14])
1711 PtrAuthData.emplace(Record[14]);
1712 }
1713
1714 IsDistinct = Record[0] & 1;
1715 bool SizeIsMetadata = Record[0] & 2;
1716 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1717
1718 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1719 Metadata *OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1720
1721 MetadataList.assignValue(
1722 GET_OR_DISTINCT(DIDerivedType,
1723 (Context, Record[1], getMDString(Record[2]),
1724 getMDOrNull(Record[3]), Record[4],
1725 getDITypeRefOrNull(Record[5]),
1726 getDITypeRefOrNull(Record[6]), SizeInBits, Record[8],
1727 OffsetInBits, DWARFAddressSpace, PtrAuthData, Flags,
1728 getDITypeRefOrNull(Record[11]), Annotations)),
1729 NextMetadataNo);
1730 NextMetadataNo++;
1731 break;
1732 }
1734 if (Record.size() != 13)
1735 return error("Invalid record");
1736
1737 IsDistinct = Record[0] & 1;
1738 bool SizeIsMetadata = Record[0] & 2;
1739 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7]);
1740
1741 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[5]);
1742
1743 MetadataList.assignValue(
1744 GET_OR_DISTINCT(DISubrangeType,
1745 (Context, getMDString(Record[1]),
1746 getMDOrNull(Record[2]), Record[3],
1747 getMDOrNull(Record[4]), SizeInBits, Record[6], Flags,
1748 getDITypeRefOrNull(Record[8]), getMDOrNull(Record[9]),
1749 getMDOrNull(Record[10]), getMDOrNull(Record[11]),
1750 getMDOrNull(Record[12]))),
1751 NextMetadataNo);
1752 NextMetadataNo++;
1753 break;
1754 }
1756 if (Record.size() < 16 || Record.size() > 26)
1757 return error("Invalid record");
1758
1759 // If we have a UUID and this is not a forward declaration, lookup the
1760 // mapping.
1761 IsDistinct = Record[0] & 0x1;
1762 bool IsNotUsedInTypeRef = Record[0] & 2;
1763 bool SizeIsMetadata = Record[0] & 4;
1764 unsigned Tag = Record[1];
1765 MDString *Name = getMDString(Record[2]);
1766 Metadata *File = getMDOrNull(Record[3]);
1767 unsigned Line = Record[4];
1768 Metadata *Scope = getDITypeRefOrNull(Record[5]);
1769 Metadata *BaseType = nullptr;
1770 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1771 return error("Alignment value is too large");
1772 uint32_t AlignInBits = Record[8];
1773 Metadata *OffsetInBits = nullptr;
1774 uint32_t NumExtraInhabitants = (Record.size() > 22) ? Record[22] : 0;
1775 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1776 Metadata *Elements = nullptr;
1777 unsigned RuntimeLang = Record[12];
1778 std::optional<uint32_t> EnumKind;
1779
1780 Metadata *VTableHolder = nullptr;
1781 Metadata *TemplateParams = nullptr;
1782 Metadata *Discriminator = nullptr;
1783 Metadata *DataLocation = nullptr;
1784 Metadata *Associated = nullptr;
1785 Metadata *Allocated = nullptr;
1786 Metadata *Rank = nullptr;
1787 Metadata *Annotations = nullptr;
1788 Metadata *Specification = nullptr;
1789 Metadata *BitStride = nullptr;
1790 auto *Identifier = getMDString(Record[15]);
1791 // If this module is being parsed so that it can be ThinLTO imported
1792 // into another module, composite types only need to be imported as
1793 // type declarations (unless full type definitions are requested).
1794 // Create type declarations up front to save memory. This is only
1795 // done for types which have an Identifier, and are therefore
1796 // subject to the ODR.
1797 //
1798 // buildODRType handles the case where this is type ODRed with a
1799 // definition needed by the importing module, in which case the
1800 // existing definition is used.
1801 //
1802 // We always import full definitions for anonymous composite types,
1803 // as without a name, debuggers cannot easily resolve a declaration
1804 // to its definition.
1805 if (IsImporting && !ImportFullTypeDefinitions && Identifier && Name &&
1806 (Tag == dwarf::DW_TAG_enumeration_type ||
1807 Tag == dwarf::DW_TAG_class_type ||
1808 Tag == dwarf::DW_TAG_structure_type ||
1809 Tag == dwarf::DW_TAG_union_type)) {
1810 Flags = Flags | DINode::FlagFwdDecl;
1811 // This is a hack around preserving template parameters for simplified
1812 // template names - it should probably be replaced with a
1813 // DICompositeType flag specifying whether template parameters are
1814 // required on declarations of this type.
1815 StringRef NameStr = Name->getString();
1816 if (!NameStr.contains('<') || NameStr.starts_with("_STN|"))
1817 TemplateParams = getMDOrNull(Record[14]);
1818 } else {
1819 BaseType = getDITypeRefOrNull(Record[6]);
1820
1821 OffsetInBits = getMetadataOrConstant(SizeIsMetadata, Record[9]);
1822
1823 Elements = getMDOrNull(Record[11]);
1824 VTableHolder = getDITypeRefOrNull(Record[13]);
1825 TemplateParams = getMDOrNull(Record[14]);
1826 if (Record.size() > 16)
1827 Discriminator = getMDOrNull(Record[16]);
1828 if (Record.size() > 17)
1829 DataLocation = getMDOrNull(Record[17]);
1830 if (Record.size() > 19) {
1831 Associated = getMDOrNull(Record[18]);
1832 Allocated = getMDOrNull(Record[19]);
1833 }
1834 if (Record.size() > 20) {
1835 Rank = getMDOrNull(Record[20]);
1836 }
1837 if (Record.size() > 21) {
1838 Annotations = getMDOrNull(Record[21]);
1839 }
1840 if (Record.size() > 23) {
1841 Specification = getMDOrNull(Record[23]);
1842 }
1843 if (Record.size() > 25)
1844 BitStride = getMDOrNull(Record[25]);
1845 }
1846
1847 if (Record.size() > 24 && Record[24] != dwarf::DW_APPLE_ENUM_KIND_invalid)
1848 EnumKind = Record[24];
1849
1850 Metadata *SizeInBits = getMetadataOrConstant(SizeIsMetadata, Record[7]);
1851
1852 DICompositeType *CT = nullptr;
1853 if (Identifier)
1855 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1856 SizeInBits, AlignInBits, OffsetInBits, Specification,
1857 NumExtraInhabitants, Flags, Elements, RuntimeLang, EnumKind,
1858 VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1859 Allocated, Rank, Annotations, BitStride);
1860
1861 // Create a node if we didn't get a lazy ODR type.
1862 if (!CT)
1863 CT = GET_OR_DISTINCT(
1864 DICompositeType,
1865 (Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1866 AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, EnumKind,
1867 VTableHolder, TemplateParams, Identifier, Discriminator,
1868 DataLocation, Associated, Allocated, Rank, Annotations,
1869 Specification, NumExtraInhabitants, BitStride));
1870 if (!IsNotUsedInTypeRef && Identifier)
1871 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1872
1873 MetadataList.assignValue(CT, NextMetadataNo);
1874 NextMetadataNo++;
1875 break;
1876 }
1878 if (Record.size() < 3 || Record.size() > 4)
1879 return error("Invalid record");
1880 bool IsOldTypeArray = Record[0] < 2;
1881 unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1882
1883 IsDistinct = Record[0] & 0x1;
1884 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1885 Metadata *Types = getMDOrNull(Record[2]);
1886 if (LLVM_UNLIKELY(IsOldTypeArray))
1887 Types = MetadataList.upgradeTypeArray(Types);
1888
1889 MetadataList.assignValue(
1890 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1891 NextMetadataNo);
1892 NextMetadataNo++;
1893 break;
1894 }
1895
1896 case bitc::METADATA_MODULE: {
1897 if (Record.size() < 5 || Record.size() > 9)
1898 return error("Invalid record");
1899
1900 unsigned Offset = Record.size() >= 8 ? 2 : 1;
1901 IsDistinct = Record[0];
1902 MetadataList.assignValue(
1904 DIModule,
1905 (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1906 getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1907 getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1908 getMDString(Record[4 + Offset]),
1909 Record.size() <= 7 ? 0 : Record[7],
1910 Record.size() <= 8 ? false : Record[8])),
1911 NextMetadataNo);
1912 NextMetadataNo++;
1913 break;
1914 }
1915
1916 case bitc::METADATA_FILE: {
1917 if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1918 return error("Invalid record");
1919
1920 IsDistinct = Record[0];
1921 std::optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1922 // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1923 // is not present. This matches up with the old internal representation,
1924 // and the old encoding for CSK_None in the ChecksumKind. The new
1925 // representation reserves the value 0 in the ChecksumKind to continue to
1926 // encode None in a backwards-compatible way.
1927 if (Record.size() > 4 && Record[3] && Record[4])
1928 Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1929 getMDString(Record[4]));
1930 MetadataList.assignValue(
1931 GET_OR_DISTINCT(DIFile,
1932 (Context, getMDString(Record[1]),
1933 getMDString(Record[2]), Checksum,
1934 Record.size() > 5 ? getMDString(Record[5]) : nullptr)),
1935 NextMetadataNo);
1936 NextMetadataNo++;
1937 break;
1938 }
1940 if (Record.size() < 14 || Record.size() > 24)
1941 return error("Invalid record");
1942
1943 // Ignore Record[0], which indicates whether this compile unit is
1944 // distinct. It's always distinct.
1945 IsDistinct = true;
1946
1947 const auto LangVersionMask = (uint64_t(1) << 63);
1948 const bool HasVersionedLanguage = Record[1] & LangVersionMask;
1949 const uint32_t LanguageVersion = Record.size() > 22 ? Record[22] : 0;
1950 // The dialect field is written by writeDICompileUnit as a small enum
1951 // value (see dwarf::LanguageDialectAttribute). Reject out-of-range
1952 // values rather than silently truncating to uint16_t; this keeps the
1953 // writer/reader invariant symmetric and surfaces malformed inputs.
1954 // Value 0 means "no dialect specified".
1955 if (Record.size() > 23 &&
1956 Record[23] > static_cast<uint64_t>(dwarf::DW_LLVM_LANG_DIALECT_max))
1957 return error("Invalid DICompileUnit dialect value");
1958 const uint16_t Dialect =
1959 Record.size() > 23 ? static_cast<uint16_t>(Record[23]) : uint16_t(0);
1960
1961 auto *CU = DICompileUnit::getDistinct(
1962 Context,
1963 HasVersionedLanguage
1964 ? DISourceLanguageName(Record[1] & ~LangVersionMask,
1965 LanguageVersion, Dialect)
1966 : DISourceLanguageName(Record[1], Dialect),
1967 getMDOrNull(Record[2]), getMDString(Record[3]), Record[4],
1968 getMDString(Record[5]), Record[6], getMDString(Record[7]), Record[8],
1969 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1970 getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1971 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1972 Record.size() <= 14 ? 0 : Record[14],
1973 Record.size() <= 16 ? true : Record[16],
1974 Record.size() <= 17 ? false : Record[17],
1975 Record.size() <= 18 ? 0 : Record[18],
1976 Record.size() <= 19 ? false : Record[19],
1977 // Keep these guarded for backwards-compatibility with older bitcode
1978 // records. Keep this index layout in sync with writeDICompileUnit:
1979 // index 20 is sysroot, 21 is SDK, 22 is source-language version, and
1980 // 23 is dialect (read above as raw enum value, where 0 means unset).
1981 Record.size() <= 20 ? nullptr : getMDString(Record[20]),
1982 Record.size() <= 21 ? nullptr : getMDString(Record[21]));
1983
1984 MetadataList.assignValue(CU, NextMetadataNo);
1985 NextMetadataNo++;
1986
1987 // Move the Upgrade the list of subprograms.
1988 if (Record[11])
1989 CUSubprograms.push_back({CU, Record[11]});
1990 break;
1991 }
1993 if (Record.size() < 18 || Record.size() > 22)
1994 return error("Invalid record");
1995
1996 bool HasSPFlags = Record[0] & 4;
1997
2000 if (!HasSPFlags)
2001 Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
2002 else {
2003 Flags = static_cast<DINode::DIFlags>(Record[11]);
2004 SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
2005 }
2006
2007 // Support for old metadata when
2008 // subprogram specific flags are placed in DIFlags.
2009 const unsigned DIFlagMainSubprogram = 1 << 21;
2010 bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
2011 if (HasOldMainSubprogramFlag)
2012 // Remove old DIFlagMainSubprogram from DIFlags.
2013 // Note: This assumes that any future use of bit 21 defaults to it
2014 // being 0.
2015 Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
2016
2017 if (HasOldMainSubprogramFlag && HasSPFlags)
2018 SPFlags |= DISubprogram::SPFlagMainSubprogram;
2019 else if (!HasSPFlags)
2020 SPFlags = DISubprogram::toSPFlags(
2021 /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
2022 /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
2023 /*IsMainSubprogram=*/HasOldMainSubprogramFlag);
2024
2025 // All definitions should be distinct.
2026 IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
2027 // Version 1 has a Function as Record[15].
2028 // Version 2 has removed Record[15].
2029 // Version 3 has the Unit as Record[15].
2030 // Version 4 added thisAdjustment.
2031 // Version 5 repacked flags into DISPFlags, changing many element numbers.
2032 bool HasUnit = Record[0] & 2;
2033 if (!HasSPFlags && HasUnit && Record.size() < 19)
2034 return error("Invalid record");
2035 if (HasSPFlags && !HasUnit)
2036 return error("Invalid record");
2037 // Accommodate older formats.
2038 bool HasFn = false;
2039 bool HasThisAdj = true;
2040 bool HasThrownTypes = true;
2041 bool HasAnnotations = false;
2042 bool HasTargetFuncName = false;
2043 unsigned OffsetA = 0;
2044 unsigned OffsetB = 0;
2045 // Key instructions won't be enabled in old-format bitcode, so only
2046 // check it if HasSPFlags is true.
2047 bool UsesKeyInstructions = false;
2048 if (!HasSPFlags) {
2049 OffsetA = 2;
2050 OffsetB = 2;
2051 if (Record.size() >= 19) {
2052 HasFn = !HasUnit;
2053 OffsetB++;
2054 }
2055 HasThisAdj = Record.size() >= 20;
2056 HasThrownTypes = Record.size() >= 21;
2057 } else {
2058 HasAnnotations = Record.size() >= 19;
2059 HasTargetFuncName = Record.size() >= 20;
2060 UsesKeyInstructions = Record.size() >= 21 ? Record[20] : 0;
2061 }
2062
2063 Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
2064 DISubprogram *SP = GET_OR_DISTINCT(
2065 DISubprogram,
2066 (Context,
2067 getDITypeRefOrNull(Record[1]), // scope
2068 getMDString(Record[2]), // name
2069 getMDString(Record[3]), // linkageName
2070 getMDOrNull(Record[4]), // file
2071 Record[5], // line
2072 getMDOrNull(Record[6]), // type
2073 Record[7 + OffsetA], // scopeLine
2074 getDITypeRefOrNull(Record[8 + OffsetA]), // containingType
2075 Record[10 + OffsetA], // virtualIndex
2076 HasThisAdj ? Record[16 + OffsetB] : 0, // thisAdjustment
2077 Flags, // flags
2078 SPFlags, // SPFlags
2079 HasUnit ? CUorFn : nullptr, // unit
2080 getMDOrNull(Record[13 + OffsetB]), // templateParams
2081 getMDOrNull(Record[14 + OffsetB]), // declaration
2082 getMDOrNull(Record[15 + OffsetB]), // retainedNodes
2083 HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
2084 : nullptr, // thrownTypes
2085 HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
2086 : nullptr, // annotations
2087 HasTargetFuncName ? getMDString(Record[19 + OffsetB])
2088 : nullptr, // targetFuncName
2089 UsesKeyInstructions));
2090 MetadataList.assignValue(SP, NextMetadataNo);
2091 NextMetadataNo++;
2092
2093 if (IsDistinct)
2094 NewDistinctSPs.push_back(SP);
2095
2096 // Upgrade sp->function mapping to function->sp mapping.
2097 if (HasFn) {
2098 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
2099 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2100 if (F->isMaterializable())
2101 // Defer until materialized; unmaterialized functions may not have
2102 // metadata.
2103 FunctionsWithSPs[F] = SP;
2104 else if (!F->empty())
2105 F->setSubprogram(SP);
2106 }
2107 }
2108 break;
2109 }
2111 if (Record.size() != 5)
2112 return error("Invalid record");
2113
2114 IsDistinct = Record[0];
2115 MetadataList.assignValue(
2116 GET_OR_DISTINCT(DILexicalBlock,
2117 (Context, getMDOrNull(Record[1]),
2118 getMDOrNull(Record[2]), Record[3], Record[4])),
2119 NextMetadataNo);
2120 NextMetadataNo++;
2121 break;
2122 }
2124 if (Record.size() != 4)
2125 return error("Invalid record");
2126
2127 IsDistinct = Record[0];
2128 MetadataList.assignValue(
2129 GET_OR_DISTINCT(DILexicalBlockFile,
2130 (Context, getMDOrNull(Record[1]),
2131 getMDOrNull(Record[2]), Record[3])),
2132 NextMetadataNo);
2133 NextMetadataNo++;
2134 break;
2135 }
2137 IsDistinct = Record[0] & 1;
2138 MetadataList.assignValue(
2139 GET_OR_DISTINCT(DICommonBlock,
2140 (Context, getMDOrNull(Record[1]),
2141 getMDOrNull(Record[2]), getMDString(Record[3]),
2142 getMDOrNull(Record[4]), Record[5])),
2143 NextMetadataNo);
2144 NextMetadataNo++;
2145 break;
2146 }
2148 // Newer versions of DINamespace dropped file and line.
2149 MDString *Name;
2150 if (Record.size() == 3)
2151 Name = getMDString(Record[2]);
2152 else if (Record.size() == 5)
2153 Name = getMDString(Record[3]);
2154 else
2155 return error("Invalid record");
2156
2157 IsDistinct = Record[0] & 1;
2158 bool ExportSymbols = Record[0] & 2;
2159 MetadataList.assignValue(
2160 GET_OR_DISTINCT(DINamespace,
2161 (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
2162 NextMetadataNo);
2163 NextMetadataNo++;
2164 break;
2165 }
2166 case bitc::METADATA_MACRO: {
2167 if (Record.size() != 5)
2168 return error("Invalid record");
2169
2170 IsDistinct = Record[0];
2171 MetadataList.assignValue(
2172 GET_OR_DISTINCT(DIMacro,
2173 (Context, Record[1], Record[2], getMDString(Record[3]),
2174 getMDString(Record[4]))),
2175 NextMetadataNo);
2176 NextMetadataNo++;
2177 break;
2178 }
2180 if (Record.size() != 5)
2181 return error("Invalid record");
2182
2183 IsDistinct = Record[0];
2184 MetadataList.assignValue(
2185 GET_OR_DISTINCT(DIMacroFile,
2186 (Context, Record[1], Record[2], getMDOrNull(Record[3]),
2187 getMDOrNull(Record[4]))),
2188 NextMetadataNo);
2189 NextMetadataNo++;
2190 break;
2191 }
2193 if (Record.size() < 3 || Record.size() > 4)
2194 return error("Invalid record");
2195
2196 IsDistinct = Record[0];
2197 MetadataList.assignValue(
2198 GET_OR_DISTINCT(DITemplateTypeParameter,
2199 (Context, getMDString(Record[1]),
2200 getDITypeRefOrNull(Record[2]),
2201 (Record.size() == 4) ? getMDOrNull(Record[3])
2202 : getMDOrNull(false))),
2203 NextMetadataNo);
2204 NextMetadataNo++;
2205 break;
2206 }
2208 if (Record.size() < 5 || Record.size() > 6)
2209 return error("Invalid record");
2210
2211 IsDistinct = Record[0];
2212
2213 MetadataList.assignValue(
2215 DITemplateValueParameter,
2216 (Context, Record[1], getMDString(Record[2]),
2217 getDITypeRefOrNull(Record[3]),
2218 (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
2219 (Record.size() == 6) ? getMDOrNull(Record[5])
2220 : getMDOrNull(Record[4]))),
2221 NextMetadataNo);
2222 NextMetadataNo++;
2223 break;
2224 }
2226 if (Record.size() < 11 || Record.size() > 13)
2227 return error("Invalid record");
2228
2229 IsDistinct = Record[0] & 1;
2230 unsigned Version = Record[0] >> 1;
2231
2232 if (Version == 2) {
2233 Metadata *Annotations = nullptr;
2234 if (Record.size() > 12)
2235 Annotations = getMDOrNull(Record[12]);
2236
2237 MetadataList.assignValue(
2238 GET_OR_DISTINCT(DIGlobalVariable,
2239 (Context, getMDOrNull(Record[1]),
2240 getMDString(Record[2]), getMDString(Record[3]),
2241 getMDOrNull(Record[4]), Record[5],
2242 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2243 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2244 Record[11], Annotations)),
2245 NextMetadataNo);
2246
2247 NextMetadataNo++;
2248 } else if (Version == 1) {
2249 // No upgrade necessary. A null field will be introduced to indicate
2250 // that no parameter information is available.
2251 MetadataList.assignValue(
2253 DIGlobalVariable,
2254 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2255 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2256 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2257 getMDOrNull(Record[10]), nullptr, Record[11], nullptr)),
2258 NextMetadataNo);
2259
2260 NextMetadataNo++;
2261 } else if (Version == 0) {
2262 // Upgrade old metadata, which stored a global variable reference or a
2263 // ConstantInt here.
2264 NeedUpgradeToDIGlobalVariableExpression = true;
2265 Metadata *Expr = getMDOrNull(Record[9]);
2266 uint32_t AlignInBits = 0;
2267 if (Record.size() > 11) {
2268 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
2269 return error("Alignment value is too large");
2270 AlignInBits = Record[11];
2271 }
2272 GlobalVariable *Attach = nullptr;
2273 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
2274 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
2275 Attach = GV;
2276 Expr = nullptr;
2277 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
2278 Expr = DIExpression::get(Context,
2279 {dwarf::DW_OP_constu, CI->getZExtValue(),
2280 dwarf::DW_OP_stack_value});
2281 } else {
2282 Expr = nullptr;
2283 }
2284 }
2285 DIGlobalVariable *DGV = GET_OR_DISTINCT(
2286 DIGlobalVariable,
2287 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2288 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2289 getDITypeRefOrNull(Record[6]), Record[7], Record[8],
2290 getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
2291
2292 DIGlobalVariableExpression *DGVE = nullptr;
2293 if (Attach || Expr)
2294 DGVE = DIGlobalVariableExpression::getDistinct(
2295 Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
2296 if (Attach)
2297 Attach->addDebugInfo(DGVE);
2298
2299 auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
2300 MetadataList.assignValue(MDNode, NextMetadataNo);
2301 NextMetadataNo++;
2302 } else
2303 return error("Invalid record");
2304
2305 break;
2306 }
2308 if (Record.size() != 1)
2309 return error("Invalid DIAssignID record.");
2310
2311 IsDistinct = Record[0] & 1;
2312 if (!IsDistinct)
2313 return error("Invalid DIAssignID record. Must be distinct");
2314
2315 MetadataList.assignValue(DIAssignID::getDistinct(Context), NextMetadataNo);
2316 NextMetadataNo++;
2317 break;
2318 }
2320 // 10th field is for the obseleted 'inlinedAt:' field.
2321 if (Record.size() < 8 || Record.size() > 10)
2322 return error("Invalid record");
2323
2324 IsDistinct = Record[0] & 1;
2325 bool HasAlignment = Record[0] & 2;
2326 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2327 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
2328 // this is newer version of record which doesn't have artificial tag.
2329 bool HasTag = !HasAlignment && Record.size() > 8;
2330 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
2331 uint32_t AlignInBits = 0;
2332 Metadata *Annotations = nullptr;
2333 if (HasAlignment) {
2334 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
2335 return error("Alignment value is too large");
2336 AlignInBits = Record[8];
2337 if (Record.size() > 9)
2338 Annotations = getMDOrNull(Record[9]);
2339 }
2340
2341 MetadataList.assignValue(
2342 GET_OR_DISTINCT(DILocalVariable,
2343 (Context, getMDOrNull(Record[1 + HasTag]),
2344 getMDString(Record[2 + HasTag]),
2345 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2346 getDITypeRefOrNull(Record[5 + HasTag]),
2347 Record[6 + HasTag], Flags, AlignInBits, Annotations)),
2348 NextMetadataNo);
2349 NextMetadataNo++;
2350 break;
2351 }
2352 case bitc::METADATA_LABEL: {
2353 if (Record.size() < 5 || Record.size() > 7)
2354 return error("Invalid record");
2355
2356 IsDistinct = Record[0] & 1;
2357 uint64_t Line = Record[4];
2358 uint64_t Column = Record.size() > 5 ? Record[5] : 0;
2359 bool IsArtificial = Record[0] & 2;
2360 std::optional<unsigned> CoroSuspendIdx;
2361 if (Record.size() > 6) {
2362 uint64_t RawSuspendIdx = Record[6];
2363 if (RawSuspendIdx != std::numeric_limits<uint64_t>::max()) {
2364 if (RawSuspendIdx > (uint64_t)std::numeric_limits<unsigned>::max())
2365 return error("CoroSuspendIdx value is too large");
2366 CoroSuspendIdx = RawSuspendIdx;
2367 }
2368 }
2369
2370 MetadataList.assignValue(
2371 GET_OR_DISTINCT(DILabel,
2372 (Context, getMDOrNull(Record[1]),
2373 getMDString(Record[2]), getMDOrNull(Record[3]), Line,
2374 Column, IsArtificial, CoroSuspendIdx)),
2375 NextMetadataNo);
2376 NextMetadataNo++;
2377 break;
2378 }
2380 if (Record.size() < 1)
2381 return error("Invalid record");
2382
2383 IsDistinct = Record[0] & 1;
2384 uint64_t Version = Record[0] >> 1;
2385 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2386
2388 if (Error Err = upgradeDIExpression(Version, Elts, Buffer))
2389 return Err;
2390
2391 MetadataList.assignValue(GET_OR_DISTINCT(DIExpression, (Context, Elts)),
2392 NextMetadataNo);
2393 NextMetadataNo++;
2394 break;
2395 }
2397 if (Record.size() != 3)
2398 return error("Invalid record");
2399
2400 IsDistinct = Record[0];
2401 Metadata *Expr = getMDOrNull(Record[2]);
2402 if (!Expr)
2403 Expr = DIExpression::get(Context, {});
2404 MetadataList.assignValue(
2405 GET_OR_DISTINCT(DIGlobalVariableExpression,
2406 (Context, getMDOrNull(Record[1]), Expr)),
2407 NextMetadataNo);
2408 NextMetadataNo++;
2409 break;
2410 }
2412 if (Record.size() != 8)
2413 return error("Invalid record");
2414
2415 IsDistinct = Record[0];
2416 MetadataList.assignValue(
2417 GET_OR_DISTINCT(DIObjCProperty,
2418 (Context, getMDString(Record[1]),
2419 getMDOrNull(Record[2]), Record[3],
2420 /*GetterName=*/getMDString(Record[5]),
2421 /*SetterName=*/getMDString(Record[4]), Record[6],
2422 getDITypeRefOrNull(Record[7]))),
2423 NextMetadataNo);
2424 NextMetadataNo++;
2425 break;
2426 }
2428 if (Record.size() < 6 || Record.size() > 8)
2429 return error("Invalid DIImportedEntity record");
2430
2431 IsDistinct = Record[0];
2432 bool HasFile = (Record.size() >= 7);
2433 bool HasElements = (Record.size() >= 8);
2434 MetadataList.assignValue(
2435 GET_OR_DISTINCT(DIImportedEntity,
2436 (Context, Record[1], getMDOrNull(Record[2]),
2437 getDITypeRefOrNull(Record[3]),
2438 HasFile ? getMDOrNull(Record[6]) : nullptr,
2439 HasFile ? Record[4] : 0, getMDString(Record[5]),
2440 HasElements ? getMDOrNull(Record[7]) : nullptr)),
2441 NextMetadataNo);
2442 NextMetadataNo++;
2443 break;
2444 }
2446 std::string String(Record.begin(), Record.end());
2447
2448 // Test for upgrading !llvm.loop.
2449 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2450 ++NumMDStringLoaded;
2452 MetadataList.assignValue(MD, NextMetadataNo);
2453 NextMetadataNo++;
2454 break;
2455 }
2457 auto CreateNextMDString = [&](StringRef Str) {
2458 ++NumMDStringLoaded;
2459 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2460 NextMetadataNo++;
2461 };
2462 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2463 return Err;
2464 break;
2465 }
2467 if (Record.size() % 2 == 0)
2468 return error("Invalid record");
2469 unsigned ValueID = Record[0];
2470 if (ValueID >= ValueList.size())
2471 return error("Invalid record");
2472 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2473 if (Error Err = parseGlobalObjectAttachment(
2474 *GO, ArrayRef<uint64_t>(Record).slice(1)))
2475 return Err;
2476 break;
2477 }
2478 case bitc::METADATA_KIND: {
2479 // Support older bitcode files that had METADATA_KIND records in a
2480 // block with METADATA_BLOCK_ID.
2481 if (Error Err = parseMetadataKindRecord(Record))
2482 return Err;
2483 break;
2484 }
2487 Elts.reserve(Record.size());
2488 for (uint64_t Elt : Record) {
2489 Metadata *MD = getMD(Elt);
2490 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2491 return error(
2492 "Invalid record: DIArgList should not contain forward refs");
2493 if (!isa<ValueAsMetadata>(MD))
2494 return error("Invalid record");
2496 }
2497
2498 MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2499 NextMetadataNo++;
2500 break;
2501 }
2502 }
2503 return Error::success();
2504#undef GET_OR_DISTINCT
2505}
2506
2507Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2508 ArrayRef<uint64_t> Record, StringRef Blob,
2509 function_ref<void(StringRef)> CallBack) {
2510 // All the MDStrings in the block are emitted together in a single
2511 // record. The strings are concatenated and stored in a blob along with
2512 // their sizes.
2513 if (Record.size() != 2)
2514 return error("Invalid record: metadata strings layout");
2515
2516 unsigned NumStrings = Record[0];
2517 unsigned StringsOffset = Record[1];
2518 if (!NumStrings)
2519 return error("Invalid record: metadata strings with no strings");
2520 if (StringsOffset > Blob.size())
2521 return error("Invalid record: metadata strings corrupt offset");
2522
2523 StringRef Lengths = Blob.slice(0, StringsOffset);
2524 SimpleBitstreamCursor R(Lengths);
2525
2526 StringRef Strings = Blob.drop_front(StringsOffset);
2527 do {
2528 if (R.AtEndOfStream())
2529 return error("Invalid record: metadata strings bad length");
2530
2531 uint32_t Size;
2532 if (Error E = R.ReadVBR(6).moveInto(Size))
2533 return E;
2534 if (Strings.size() < Size)
2535 return error("Invalid record: metadata strings truncated chars");
2536
2537 CallBack(Strings.slice(0, Size));
2538 Strings = Strings.drop_front(Size);
2539 } while (--NumStrings);
2540
2541 return Error::success();
2542}
2543
2544Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2545 GlobalObject &GO, ArrayRef<uint64_t> Record) {
2546 assert(Record.size() % 2 == 0);
2547 for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2548 auto K = MDKindMap.find(Record[I]);
2549 if (K == MDKindMap.end())
2550 return error("Invalid ID");
2551 MDNode *MD =
2552 dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2553 if (!MD)
2554 return error("Invalid metadata attachment: expect fwd ref to MDNode");
2555 GO.addMetadata(K->second, *MD);
2556 }
2557 return Error::success();
2558}
2559
2560/// Parse metadata attachments.
2562 Function &F, ArrayRef<Instruction *> InstructionList) {
2563 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2564 return Err;
2565
2567 PlaceholderQueue Placeholders;
2568
2569 while (true) {
2570 BitstreamEntry Entry;
2571 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2572 return E;
2573
2574 switch (Entry.Kind) {
2575 case BitstreamEntry::SubBlock: // Handled for us already.
2577 return error("Malformed block");
2579 LLVM_DEBUG(llvm::dbgs() << "\nAttachment metadata loading: ");
2580 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2581 return Error::success();
2583 // The interesting case.
2584 break;
2585 }
2586
2587 // Read a metadata attachment record.
2588 Record.clear();
2589 ++NumMDRecordLoaded;
2590 Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2591 if (!MaybeRecord)
2592 return MaybeRecord.takeError();
2593 switch (MaybeRecord.get()) {
2594 default: // Default behavior: ignore.
2595 break;
2597 unsigned RecordLength = Record.size();
2598 if (Record.empty())
2599 return error("Invalid record");
2600 if (RecordLength % 2 == 0) {
2601 // A function attachment.
2602 if (Error Err = parseGlobalObjectAttachment(F, Record))
2603 return Err;
2604 continue;
2605 }
2606
2607 // An instruction attachment.
2608 Instruction *Inst = InstructionList[Record[0]];
2609 for (unsigned i = 1; i != RecordLength; i = i + 2) {
2610 unsigned Kind = Record[i];
2611 auto I = MDKindMap.find(Kind);
2612 if (I == MDKindMap.end())
2613 return error("Invalid ID");
2614 if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2615 continue;
2616
2617 auto Idx = Record[i + 1];
2618 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2619 !MetadataList.lookup(Idx)) {
2620 // Load the attachment if it is in the lazy-loadable range and hasn't
2621 // been loaded yet.
2622 lazyLoadOneMetadata(Idx, Placeholders);
2623 LLVM_DEBUG(llvm::dbgs() << "\nLazy attachment metadata loading: ");
2624 resolveLoadedMetadata(Placeholders, DebugInfoUpgradeMode::None);
2625 }
2626
2627 Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2629 // Drop the attachment. This used to be legal, but there's no
2630 // upgrade path.
2631 break;
2633 if (!MD)
2634 return error("Invalid metadata attachment");
2635
2636 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2638
2639 if (I->second == LLVMContext::MD_tbaa) {
2640 assert(!MD->isTemporary() && "should load MDs before attachments");
2641 MD = UpgradeTBAANode(*MD);
2642 }
2643 Inst->setMetadata(I->second, MD);
2644 }
2645 break;
2646 }
2647 }
2648 }
2649}
2650
2651/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2652Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2654 if (Record.size() < 2)
2655 return error("Invalid record");
2656
2657 unsigned Kind = Record[0];
2658 SmallString<8> Name(Record.begin() + 1, Record.end());
2659
2660 unsigned NewKind = TheModule.getMDKindID(Name.str());
2661 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2662 return error("Conflicting METADATA_KIND records");
2663 return Error::success();
2664}
2665
2666/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2668 if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2669 return Err;
2670
2672
2673 // Read all the records.
2674 while (true) {
2675 BitstreamEntry Entry;
2676 if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2677 return E;
2678
2679 switch (Entry.Kind) {
2680 case BitstreamEntry::SubBlock: // Handled for us already.
2682 return error("Malformed block");
2684 return Error::success();
2686 // The interesting case.
2687 break;
2688 }
2689
2690 // Read a record.
2691 Record.clear();
2692 ++NumMDRecordLoaded;
2693 Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2694 if (!MaybeCode)
2695 return MaybeCode.takeError();
2696 switch (MaybeCode.get()) {
2697 default: // Default behavior: ignore.
2698 break;
2699 case bitc::METADATA_KIND: {
2700 if (Error Err = parseMetadataKindRecord(Record))
2701 return Err;
2702 break;
2703 }
2704 }
2705 }
2706}
2707
2709 Pimpl = std::move(RHS.Pimpl);
2710 return *this;
2711}
2713 : Pimpl(std::move(RHS.Pimpl)) {}
2714
2717 BitcodeReaderValueList &ValueList,
2718 bool IsImporting,
2719 MetadataLoaderCallbacks Callbacks)
2720 : Pimpl(std::make_unique<MetadataLoaderImpl>(
2721 Stream, TheModule, ValueList, std::move(Callbacks), IsImporting)) {}
2722
2723Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2724 return Pimpl->parseMetadata(ModuleLevel);
2725}
2726
2727bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2728
2729/// Return the given metadata, creating a replaceable forward reference if
2730/// necessary.
2732 return Pimpl->getMetadataFwdRefOrLoad(Idx);
2733}
2734
2736 return Pimpl->lookupSubprogramForFunction(F);
2737}
2738
2740 Function &F, ArrayRef<Instruction *> InstructionList) {
2741 return Pimpl->parseMetadataAttachment(F, InstructionList);
2742}
2743
2745 return Pimpl->parseMetadataKinds();
2746}
2747
2748void MetadataLoader::setStripTBAA(bool StripTBAA) {
2749 return Pimpl->setStripTBAA(StripTBAA);
2750}
2751
2752bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2753
2754unsigned MetadataLoader::size() const { return Pimpl->size(); }
2755void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2756
2758 return Pimpl->upgradeDebugIntrinsics(F);
2759}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefInfo InstSet & ToRemove
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:335
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
Module.h This file contains the declarations for the Module class.
static bool lookup(const GsymReader &GR, 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
#define T
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 scope for locals.
DIFlags
Debug info flags.
LLVM_ABI DIScope * getScope() const
Subprogram description. Uses SubclassData1.
void cleanupRetainedNodes()
When IR modules are merged, typically during LTO, the merged module may contain several types having ...
static DILocalScope * getRetainedNodeScope(MDNode *N)
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....
iterator begin()
Definition DenseMap.h:82
iterator end()
Definition DenseMap.h:85
Implements a dense probed hash-table based set.
Definition DenseSet.h:289
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:1080
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1580
bool isTemporary() const
Definition Metadata.h:1264
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1584
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1572
A single uniqued string.
Definition Metadata.h:722
static LLVM_ABI MDString * get(LLVMContext &Context, StringRef Str)
Definition Metadata.cpp:614
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1529
static TempMDTuple getTemporary(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a temporary node.
Definition Metadata.h:1549
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:68
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator end() const
Definition ArrayRef.h:339
iterator begin() const
Definition ArrayRef.h:338
A tuple of MDNodes.
Definition Metadata.h:1760
iterator_range< op_iterator > operands()
Definition Metadata.h:1856
LLVM_ABI void addOperand(MDNode *M)
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A vector that has set insertion semantics.
Definition SetVector.h:57
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:151
Implements a dense probed hash-table based set with some number of buckets stored inline.
Definition DenseSet.h:301
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:629
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:714
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:212
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:558
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1668
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
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
FunctionAddr VTableAddr uintptr_t uintptr_t Version
Definition InstrProf.h:334
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:1916
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:874
#define N
When advancing through a bitstream cursor, each advance can discover a few different kinds of entries...