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