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