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