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