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