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