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