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