xref: /llvm-project/llvm/lib/Bitcode/Reader/MetadataLoader.cpp (revision ee7652569854af567ba83e5255d70e80cc8619a1)
1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MetadataLoader.h"
10 #include "ValueList.h"
11 
12 #include "llvm/ADT/APFloat.h"
13 #include "llvm/ADT/APInt.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/LLVMBitCodes.h"
25 #include "llvm/Bitstream/BitstreamReader.h"
26 #include "llvm/IR/Argument.h"
27 #include "llvm/IR/Attributes.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Comdat.h"
32 #include "llvm/IR/Constant.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DebugInfo.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/DebugLoc.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/DiagnosticPrinter.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GVMaterializer.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalIFunc.h"
43 #include "llvm/IR/GlobalObject.h"
44 #include "llvm/IR/GlobalValue.h"
45 #include "llvm/IR/GlobalVariable.h"
46 #include "llvm/IR/InlineAsm.h"
47 #include "llvm/IR/InstrTypes.h"
48 #include "llvm/IR/Instruction.h"
49 #include "llvm/IR/Instructions.h"
50 #include "llvm/IR/IntrinsicInst.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/IR/ModuleSummaryIndex.h"
55 #include "llvm/IR/OperandTraits.h"
56 #include "llvm/IR/TrackingMDRef.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/ValueHandle.h"
59 #include "llvm/Support/AtomicOrdering.h"
60 #include "llvm/Support/Casting.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/Support/Compiler.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include "llvm/Support/raw_ostream.h"
68 #include <algorithm>
69 #include <cassert>
70 #include <cstddef>
71 #include <cstdint>
72 #include <deque>
73 #include <limits>
74 #include <map>
75 #include <string>
76 #include <system_error>
77 #include <tuple>
78 #include <utility>
79 #include <vector>
80 
81 using namespace llvm;
82 
83 #define DEBUG_TYPE "bitcode-reader"
84 
85 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
86 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
87 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
88 
89 /// Flag whether we need to import full type definitions for ThinLTO.
90 /// Currently needed for Darwin and LLDB.
91 static cl::opt<bool> ImportFullTypeDefinitions(
92     "import-full-type-definitions", cl::init(false), cl::Hidden,
93     cl::desc("Import full type definitions for ThinLTO."));
94 
95 static cl::opt<bool> DisableLazyLoading(
96     "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
97     cl::desc("Force disable the lazy-loading on-demand of metadata when "
98              "loading bitcode for importing."));
99 
100 namespace {
101 
102 static int64_t unrotateSign(uint64_t U) { return (U & 1) ? ~(U >> 1) : U >> 1; }
103 
104 class BitcodeReaderMetadataList {
105   /// Array of metadata references.
106   ///
107   /// Don't use std::vector here.  Some versions of libc++ copy (instead of
108   /// move) on resize, and TrackingMDRef is very expensive to copy.
109   SmallVector<TrackingMDRef, 1> MetadataPtrs;
110 
111   /// The set of indices in MetadataPtrs above of forward references that were
112   /// generated.
113   SmallDenseSet<unsigned, 1> ForwardReference;
114 
115   /// The set of indices in MetadataPtrs above of Metadata that need to be
116   /// resolved.
117   SmallDenseSet<unsigned, 1> UnresolvedNodes;
118 
119   /// Structures for resolving old type refs.
120   struct {
121     SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
122     SmallDenseMap<MDString *, DICompositeType *, 1> Final;
123     SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
124     SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
125   } OldTypeRefs;
126 
127   LLVMContext &Context;
128 
129   /// Maximum number of valid references. Forward references exceeding the
130   /// maximum must be invalid.
131   unsigned RefsUpperBound;
132 
133 public:
134   BitcodeReaderMetadataList(LLVMContext &C, size_t RefsUpperBound)
135       : Context(C),
136         RefsUpperBound(std::min((size_t)std::numeric_limits<unsigned>::max(),
137                                 RefsUpperBound)) {}
138 
139   // vector compatibility methods
140   unsigned size() const { return MetadataPtrs.size(); }
141   void resize(unsigned N) { MetadataPtrs.resize(N); }
142   void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
143   void clear() { MetadataPtrs.clear(); }
144   Metadata *back() const { return MetadataPtrs.back(); }
145   void pop_back() { MetadataPtrs.pop_back(); }
146   bool empty() const { return MetadataPtrs.empty(); }
147 
148   Metadata *operator[](unsigned i) const {
149     assert(i < MetadataPtrs.size());
150     return MetadataPtrs[i];
151   }
152 
153   Metadata *lookup(unsigned I) const {
154     if (I < MetadataPtrs.size())
155       return MetadataPtrs[I];
156     return nullptr;
157   }
158 
159   void shrinkTo(unsigned N) {
160     assert(N <= size() && "Invalid shrinkTo request!");
161     assert(ForwardReference.empty() && "Unexpected forward refs");
162     assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
163     MetadataPtrs.resize(N);
164   }
165 
166   /// Return the given metadata, creating a replaceable forward reference if
167   /// necessary.
168   Metadata *getMetadataFwdRef(unsigned Idx);
169 
170   /// Return the given metadata only if it is fully resolved.
171   ///
172   /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
173   /// would give \c false.
174   Metadata *getMetadataIfResolved(unsigned Idx);
175 
176   MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
177   void assignValue(Metadata *MD, unsigned Idx);
178   void tryToResolveCycles();
179   bool hasFwdRefs() const { return !ForwardReference.empty(); }
180   int getNextFwdRef() {
181     assert(hasFwdRefs());
182     return *ForwardReference.begin();
183   }
184 
185   /// Upgrade a type that had an MDString reference.
186   void addTypeRef(MDString &UUID, DICompositeType &CT);
187 
188   /// Upgrade a type that had an MDString reference.
189   Metadata *upgradeTypeRef(Metadata *MaybeUUID);
190 
191   /// Upgrade a type ref array that may have MDString references.
192   Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
193 
194 private:
195   Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
196 };
197 
198 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
199   if (auto *MDN = dyn_cast<MDNode>(MD))
200     if (!MDN->isResolved())
201       UnresolvedNodes.insert(Idx);
202 
203   if (Idx == size()) {
204     push_back(MD);
205     return;
206   }
207 
208   if (Idx >= size())
209     resize(Idx + 1);
210 
211   TrackingMDRef &OldMD = MetadataPtrs[Idx];
212   if (!OldMD) {
213     OldMD.reset(MD);
214     return;
215   }
216 
217   // If there was a forward reference to this value, replace it.
218   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
219   PrevMD->replaceAllUsesWith(MD);
220   ForwardReference.erase(Idx);
221 }
222 
223 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
224   // Bail out for a clearly invalid value.
225   if (Idx >= RefsUpperBound)
226     return nullptr;
227 
228   if (Idx >= size())
229     resize(Idx + 1);
230 
231   if (Metadata *MD = MetadataPtrs[Idx])
232     return MD;
233 
234   // Track forward refs to be resolved later.
235   ForwardReference.insert(Idx);
236 
237   // Create and return a placeholder, which will later be RAUW'd.
238   ++NumMDNodeTemporary;
239   Metadata *MD = MDNode::getTemporary(Context, None).release();
240   MetadataPtrs[Idx].reset(MD);
241   return MD;
242 }
243 
244 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
245   Metadata *MD = lookup(Idx);
246   if (auto *N = dyn_cast_or_null<MDNode>(MD))
247     if (!N->isResolved())
248       return nullptr;
249   return MD;
250 }
251 
252 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
253   return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
254 }
255 
256 void BitcodeReaderMetadataList::tryToResolveCycles() {
257   if (!ForwardReference.empty())
258     // Still forward references... can't resolve cycles.
259     return;
260 
261   // Give up on finding a full definition for any forward decls that remain.
262   for (const auto &Ref : OldTypeRefs.FwdDecls)
263     OldTypeRefs.Final.insert(Ref);
264   OldTypeRefs.FwdDecls.clear();
265 
266   // Upgrade from old type ref arrays.  In strange cases, this could add to
267   // OldTypeRefs.Unknown.
268   for (const auto &Array : OldTypeRefs.Arrays)
269     Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
270   OldTypeRefs.Arrays.clear();
271 
272   // Replace old string-based type refs with the resolved node, if possible.
273   // If we haven't seen the node, leave it to the verifier to complain about
274   // the invalid string reference.
275   for (const auto &Ref : OldTypeRefs.Unknown) {
276     if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
277       Ref.second->replaceAllUsesWith(CT);
278     else
279       Ref.second->replaceAllUsesWith(Ref.first);
280   }
281   OldTypeRefs.Unknown.clear();
282 
283   if (UnresolvedNodes.empty())
284     // Nothing to do.
285     return;
286 
287   // Resolve any cycles.
288   for (unsigned I : UnresolvedNodes) {
289     auto &MD = MetadataPtrs[I];
290     auto *N = dyn_cast_or_null<MDNode>(MD);
291     if (!N)
292       continue;
293 
294     assert(!N->isTemporary() && "Unexpected forward reference");
295     N->resolveCycles();
296   }
297 
298   // Make sure we return early again until there's another unresolved ref.
299   UnresolvedNodes.clear();
300 }
301 
302 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
303                                            DICompositeType &CT) {
304   assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
305   if (CT.isForwardDecl())
306     OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
307   else
308     OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
309 }
310 
311 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
312   auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
313   if (LLVM_LIKELY(!UUID))
314     return MaybeUUID;
315 
316   if (auto *CT = OldTypeRefs.Final.lookup(UUID))
317     return CT;
318 
319   auto &Ref = OldTypeRefs.Unknown[UUID];
320   if (!Ref)
321     Ref = MDNode::getTemporary(Context, None);
322   return Ref.get();
323 }
324 
325 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
326   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
327   if (!Tuple || Tuple->isDistinct())
328     return MaybeTuple;
329 
330   // Look through the array immediately if possible.
331   if (!Tuple->isTemporary())
332     return resolveTypeRefArray(Tuple);
333 
334   // Create and return a placeholder to use for now.  Eventually
335   // resolveTypeRefArrays() will be resolve this forward reference.
336   OldTypeRefs.Arrays.emplace_back(
337       std::piecewise_construct, std::forward_as_tuple(Tuple),
338       std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
339   return OldTypeRefs.Arrays.back().second.get();
340 }
341 
342 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
343   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
344   if (!Tuple || Tuple->isDistinct())
345     return MaybeTuple;
346 
347   // Look through the DITypeRefArray, upgrading each DIType *.
348   SmallVector<Metadata *, 32> Ops;
349   Ops.reserve(Tuple->getNumOperands());
350   for (Metadata *MD : Tuple->operands())
351     Ops.push_back(upgradeTypeRef(MD));
352 
353   return MDTuple::get(Context, Ops);
354 }
355 
356 namespace {
357 
358 class PlaceholderQueue {
359   // Placeholders would thrash around when moved, so store in a std::deque
360   // instead of some sort of vector.
361   std::deque<DistinctMDOperandPlaceholder> PHs;
362 
363 public:
364   ~PlaceholderQueue() {
365     assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
366   }
367   bool empty() const { return PHs.empty(); }
368   DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
369   void flush(BitcodeReaderMetadataList &MetadataList);
370 
371   /// Return the list of temporaries nodes in the queue, these need to be
372   /// loaded before we can flush the queue.
373   void getTemporaries(BitcodeReaderMetadataList &MetadataList,
374                       DenseSet<unsigned> &Temporaries) {
375     for (auto &PH : PHs) {
376       auto ID = PH.getID();
377       auto *MD = MetadataList.lookup(ID);
378       if (!MD) {
379         Temporaries.insert(ID);
380         continue;
381       }
382       auto *N = dyn_cast_or_null<MDNode>(MD);
383       if (N && N->isTemporary())
384         Temporaries.insert(ID);
385     }
386   }
387 };
388 
389 } // end anonymous namespace
390 
391 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
392   PHs.emplace_back(ID);
393   return PHs.back();
394 }
395 
396 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
397   while (!PHs.empty()) {
398     auto *MD = MetadataList.lookup(PHs.front().getID());
399     assert(MD && "Flushing placeholder on unassigned MD");
400 #ifndef NDEBUG
401     if (auto *MDN = dyn_cast<MDNode>(MD))
402       assert(MDN->isResolved() &&
403              "Flushing Placeholder while cycles aren't resolved");
404 #endif
405     PHs.front().replaceUseWith(MD);
406     PHs.pop_front();
407   }
408 }
409 
410 } // anonymous namespace
411 
412 static Error error(const Twine &Message) {
413   return make_error<StringError>(
414       Message, make_error_code(BitcodeError::CorruptedBitcode));
415 }
416 
417 class MetadataLoader::MetadataLoaderImpl {
418   BitcodeReaderMetadataList MetadataList;
419   BitcodeReaderValueList &ValueList;
420   BitstreamCursor &Stream;
421   LLVMContext &Context;
422   Module &TheModule;
423   std::function<Type *(unsigned)> getTypeByID;
424 
425   /// Cursor associated with the lazy-loading of Metadata. This is the easy way
426   /// to keep around the right "context" (Abbrev list) to be able to jump in
427   /// the middle of the metadata block and load any record.
428   BitstreamCursor IndexCursor;
429 
430   /// Index that keeps track of MDString values.
431   std::vector<StringRef> MDStringRef;
432 
433   /// On-demand loading of a single MDString. Requires the index above to be
434   /// populated.
435   MDString *lazyLoadOneMDString(unsigned Idx);
436 
437   /// Index that keeps track of where to find a metadata record in the stream.
438   std::vector<uint64_t> GlobalMetadataBitPosIndex;
439 
440   /// Cursor position of the start of the global decl attachments, to enable
441   /// loading using the index built for lazy loading, instead of forward
442   /// references.
443   uint64_t GlobalDeclAttachmentPos = 0;
444 
445 #ifndef NDEBUG
446   /// Sanity check that we end up parsing all of the global decl attachments.
447   unsigned NumGlobalDeclAttachSkipped = 0;
448   unsigned NumGlobalDeclAttachParsed = 0;
449 #endif
450 
451   /// Load the global decl attachments, using the index built for lazy loading.
452   Expected<bool> loadGlobalDeclAttachments();
453 
454   /// Populate the index above to enable lazily loading of metadata, and load
455   /// the named metadata as well as the transitively referenced global
456   /// Metadata.
457   Expected<bool> lazyLoadModuleMetadataBlock();
458 
459   /// On-demand loading of a single metadata. Requires the index above to be
460   /// populated.
461   void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
462 
463   // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
464   // point from SP to CU after a block is completly parsed.
465   std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
466 
467   /// Functions that need to be matched with subprograms when upgrading old
468   /// metadata.
469   SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
470 
471   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
472   DenseMap<unsigned, unsigned> MDKindMap;
473 
474   bool StripTBAA = false;
475   bool HasSeenOldLoopTags = false;
476   bool NeedUpgradeToDIGlobalVariableExpression = false;
477   bool NeedDeclareExpressionUpgrade = false;
478 
479   /// True if metadata is being parsed for a module being ThinLTO imported.
480   bool IsImporting = false;
481 
482   Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
483                          PlaceholderQueue &Placeholders, StringRef Blob,
484                          unsigned &NextMetadataNo);
485   Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
486                              function_ref<void(StringRef)> CallBack);
487   Error parseGlobalObjectAttachment(GlobalObject &GO,
488                                     ArrayRef<uint64_t> Record);
489   Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
490 
491   void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
492 
493   /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
494   void upgradeCUSubprograms() {
495     for (auto CU_SP : CUSubprograms)
496       if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
497         for (auto &Op : SPs->operands())
498           if (auto *SP = dyn_cast_or_null<DISubprogram>(Op))
499             SP->replaceUnit(CU_SP.first);
500     CUSubprograms.clear();
501   }
502 
503   /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
504   void upgradeCUVariables() {
505     if (!NeedUpgradeToDIGlobalVariableExpression)
506       return;
507 
508     // Upgrade list of variables attached to the CUs.
509     if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
510       for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
511         auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
512         if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
513           for (unsigned I = 0; I < GVs->getNumOperands(); I++)
514             if (auto *GV =
515                     dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
516               auto *DGVE = DIGlobalVariableExpression::getDistinct(
517                   Context, GV, DIExpression::get(Context, {}));
518               GVs->replaceOperandWith(I, DGVE);
519             }
520       }
521 
522     // Upgrade variables attached to globals.
523     for (auto &GV : TheModule.globals()) {
524       SmallVector<MDNode *, 1> MDs;
525       GV.getMetadata(LLVMContext::MD_dbg, MDs);
526       GV.eraseMetadata(LLVMContext::MD_dbg);
527       for (auto *MD : MDs)
528         if (auto *DGV = dyn_cast<DIGlobalVariable>(MD)) {
529           auto *DGVE = DIGlobalVariableExpression::getDistinct(
530               Context, DGV, DIExpression::get(Context, {}));
531           GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
532         } else
533           GV.addMetadata(LLVMContext::MD_dbg, *MD);
534     }
535   }
536 
537   /// Remove a leading DW_OP_deref from DIExpressions in a dbg.declare that
538   /// describes a function argument.
539   void upgradeDeclareExpressions(Function &F) {
540     if (!NeedDeclareExpressionUpgrade)
541       return;
542 
543     for (auto &BB : F)
544       for (auto &I : BB)
545         if (auto *DDI = dyn_cast<DbgDeclareInst>(&I))
546           if (auto *DIExpr = DDI->getExpression())
547             if (DIExpr->startsWithDeref() &&
548                 dyn_cast_or_null<Argument>(DDI->getAddress())) {
549               SmallVector<uint64_t, 8> Ops;
550               Ops.append(std::next(DIExpr->elements_begin()),
551                          DIExpr->elements_end());
552               DDI->setExpression(DIExpression::get(Context, Ops));
553             }
554   }
555 
556   /// Upgrade the expression from previous versions.
557   Error upgradeDIExpression(uint64_t FromVersion, bool &IsDistinct,
558                             MutableArrayRef<uint64_t> &Expr,
559                             SmallVectorImpl<uint64_t> &Buffer) {
560     auto N = Expr.size();
561     switch (FromVersion) {
562     default:
563       return error("Invalid record");
564     case 0:
565       if (N >= 3 && Expr[N - 3] == dwarf::DW_OP_bit_piece)
566         Expr[N - 3] = dwarf::DW_OP_LLVM_fragment;
567       LLVM_FALLTHROUGH;
568     case 1:
569       // Move DW_OP_deref to the end.
570       if (N && Expr[0] == dwarf::DW_OP_deref) {
571         auto End = Expr.end();
572         if (Expr.size() >= 3 &&
573             *std::prev(End, 3) == dwarf::DW_OP_LLVM_fragment)
574           End = std::prev(End, 3);
575         std::move(std::next(Expr.begin()), End, Expr.begin());
576         *std::prev(End) = dwarf::DW_OP_deref;
577       }
578       NeedDeclareExpressionUpgrade = true;
579       LLVM_FALLTHROUGH;
580     case 2: {
581       // Change DW_OP_plus to DW_OP_plus_uconst.
582       // Change DW_OP_minus to DW_OP_uconst, DW_OP_minus
583       auto SubExpr = ArrayRef<uint64_t>(Expr);
584       while (!SubExpr.empty()) {
585         // Skip past other operators with their operands
586         // for this version of the IR, obtained from
587         // from historic DIExpression::ExprOperand::getSize().
588         size_t HistoricSize;
589         switch (SubExpr.front()) {
590         default:
591           HistoricSize = 1;
592           break;
593         case dwarf::DW_OP_constu:
594         case dwarf::DW_OP_minus:
595         case dwarf::DW_OP_plus:
596           HistoricSize = 2;
597           break;
598         case dwarf::DW_OP_LLVM_fragment:
599           HistoricSize = 3;
600           break;
601         }
602 
603         // If the expression is malformed, make sure we don't
604         // copy more elements than we should.
605         HistoricSize = std::min(SubExpr.size(), HistoricSize);
606         ArrayRef<uint64_t> Args = SubExpr.slice(1, HistoricSize-1);
607 
608         switch (SubExpr.front()) {
609         case dwarf::DW_OP_plus:
610           Buffer.push_back(dwarf::DW_OP_plus_uconst);
611           Buffer.append(Args.begin(), Args.end());
612           break;
613         case dwarf::DW_OP_minus:
614           Buffer.push_back(dwarf::DW_OP_constu);
615           Buffer.append(Args.begin(), Args.end());
616           Buffer.push_back(dwarf::DW_OP_minus);
617           break;
618         default:
619           Buffer.push_back(*SubExpr.begin());
620           Buffer.append(Args.begin(), Args.end());
621           break;
622         }
623 
624         // Continue with remaining elements.
625         SubExpr = SubExpr.slice(HistoricSize);
626       }
627       Expr = MutableArrayRef<uint64_t>(Buffer);
628       LLVM_FALLTHROUGH;
629     }
630     case 3:
631       IsDistinct = false;
632       LLVM_FALLTHROUGH;
633     case 4:
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       // Sanity check that we parsed them all.
923       assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
924       return true;
925     case BitstreamEntry::Record:
926       break;
927     }
928     uint64_t CurrentPos = TempCursor.GetCurrentBitNo();
929     Expected<unsigned> MaybeCode = TempCursor.skipRecord(Entry.ID);
930     if (!MaybeCode)
931       return MaybeCode.takeError();
932     if (MaybeCode.get() != bitc::METADATA_GLOBAL_DECL_ATTACHMENT) {
933       // Anything other than a global decl attachment signals the end of
934       // these records. sanity check that we parsed them all.
935       assert(NumGlobalDeclAttachSkipped == NumGlobalDeclAttachParsed);
936       return true;
937     }
938 #ifndef NDEBUG
939     NumGlobalDeclAttachParsed++;
940 #endif
941     // FIXME: we need to do this early because we don't materialize global
942     // value explicitly.
943     if (Error Err = TempCursor.JumpToBit(CurrentPos))
944       return std::move(Err);
945     Record.clear();
946     if (Expected<unsigned> MaybeRecord =
947             TempCursor.readRecord(Entry.ID, Record))
948       ;
949     else
950       return MaybeRecord.takeError();
951     if (Record.size() % 2 == 0)
952       return error("Invalid record");
953     unsigned ValueID = Record[0];
954     if (ValueID >= ValueList.size())
955       return error("Invalid record");
956     if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) {
957       // Need to save and restore the current position since
958       // parseGlobalObjectAttachment will resolve all forward references which
959       // would require parsing from locations stored in the index.
960       CurrentPos = TempCursor.GetCurrentBitNo();
961       if (Error Err = parseGlobalObjectAttachment(
962               *GO, ArrayRef<uint64_t>(Record).slice(1)))
963         return std::move(Err);
964       if (Error Err = TempCursor.JumpToBit(CurrentPos))
965         return std::move(Err);
966     }
967   }
968 }
969 
970 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
971 /// module level metadata.
972 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
973   if (!ModuleLevel && MetadataList.hasFwdRefs())
974     return error("Invalid metadata: fwd refs into function blocks");
975 
976   // Record the entry position so that we can jump back here and efficiently
977   // skip the whole block in case we lazy-load.
978   auto EntryPos = Stream.GetCurrentBitNo();
979 
980   if (Error Err = Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
981     return Err;
982 
983   SmallVector<uint64_t, 64> Record;
984   PlaceholderQueue Placeholders;
985 
986   // We lazy-load module-level metadata: we build an index for each record, and
987   // then load individual record as needed, starting with the named metadata.
988   if (ModuleLevel && IsImporting && MetadataList.empty() &&
989       !DisableLazyLoading) {
990     auto SuccessOrErr = lazyLoadModuleMetadataBlock();
991     if (!SuccessOrErr)
992       return SuccessOrErr.takeError();
993     if (SuccessOrErr.get()) {
994       // An index was successfully created and we will be able to load metadata
995       // on-demand.
996       MetadataList.resize(MDStringRef.size() +
997                           GlobalMetadataBitPosIndex.size());
998 
999       // Now that we have built the index, load the global decl attachments
1000       // that were deferred during that process. This avoids creating
1001       // temporaries.
1002       SuccessOrErr = loadGlobalDeclAttachments();
1003       if (!SuccessOrErr)
1004         return SuccessOrErr.takeError();
1005       assert(SuccessOrErr.get());
1006 
1007       // Reading the named metadata created forward references and/or
1008       // placeholders, that we flush here.
1009       resolveForwardRefsAndPlaceholders(Placeholders);
1010       upgradeDebugInfo();
1011       // Return at the beginning of the block, since it is easy to skip it
1012       // entirely from there.
1013       Stream.ReadBlockEnd(); // Pop the abbrev block context.
1014       if (Error Err = IndexCursor.JumpToBit(EntryPos))
1015         return Err;
1016       if (Error Err = Stream.SkipBlock()) {
1017         // FIXME this drops the error on the floor, which
1018         // ThinLTO/X86/debuginfo-cu-import.ll relies on.
1019         consumeError(std::move(Err));
1020         return Error::success();
1021       }
1022       return Error::success();
1023     }
1024     // Couldn't load an index, fallback to loading all the block "old-style".
1025   }
1026 
1027   unsigned NextMetadataNo = MetadataList.size();
1028 
1029   // Read all the records.
1030   while (true) {
1031     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 (1) {
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]) : DINode::FlagZero;
1416 
1417     MetadataList.assignValue(
1418         GET_OR_DISTINCT(DIBasicType,
1419                         (Context, Record[1], getMDString(Record[2]), Record[3],
1420                          Record[4], Record[5], Flags)),
1421         NextMetadataNo);
1422     NextMetadataNo++;
1423     break;
1424   }
1425   case bitc::METADATA_STRING_TYPE: {
1426     if (Record.size() != 8)
1427       return error("Invalid record");
1428 
1429     IsDistinct = Record[0];
1430     MetadataList.assignValue(
1431         GET_OR_DISTINCT(DIStringType,
1432                         (Context, Record[1], getMDString(Record[2]),
1433                          getMDOrNull(Record[3]), getMDOrNull(Record[4]),
1434                          Record[5], Record[6], Record[7])),
1435         NextMetadataNo);
1436     NextMetadataNo++;
1437     break;
1438   }
1439   case bitc::METADATA_DERIVED_TYPE: {
1440     if (Record.size() < 12 || Record.size() > 14)
1441       return error("Invalid record");
1442 
1443     // DWARF address space is encoded as N->getDWARFAddressSpace() + 1. 0 means
1444     // that there is no DWARF address space associated with DIDerivedType.
1445     Optional<unsigned> DWARFAddressSpace;
1446     if (Record.size() > 12 && Record[12])
1447       DWARFAddressSpace = Record[12] - 1;
1448 
1449     Metadata *Annotations = nullptr;
1450     if (Record.size() > 13 && Record[13])
1451       Annotations = getMDOrNull(Record[13]);
1452 
1453     IsDistinct = Record[0];
1454     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1455     MetadataList.assignValue(
1456         GET_OR_DISTINCT(DIDerivedType,
1457                         (Context, Record[1], getMDString(Record[2]),
1458                          getMDOrNull(Record[3]), Record[4],
1459                          getDITypeRefOrNull(Record[5]),
1460                          getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1461                          Record[9], DWARFAddressSpace, Flags,
1462                          getDITypeRefOrNull(Record[11]), Annotations)),
1463         NextMetadataNo);
1464     NextMetadataNo++;
1465     break;
1466   }
1467   case bitc::METADATA_COMPOSITE_TYPE: {
1468     if (Record.size() < 16 || Record.size() > 22)
1469       return error("Invalid record");
1470 
1471     // If we have a UUID and this is not a forward declaration, lookup the
1472     // mapping.
1473     IsDistinct = Record[0] & 0x1;
1474     bool IsNotUsedInTypeRef = Record[0] >= 2;
1475     unsigned Tag = Record[1];
1476     MDString *Name = getMDString(Record[2]);
1477     Metadata *File = getMDOrNull(Record[3]);
1478     unsigned Line = Record[4];
1479     Metadata *Scope = getDITypeRefOrNull(Record[5]);
1480     Metadata *BaseType = nullptr;
1481     uint64_t SizeInBits = Record[7];
1482     if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1483       return error("Alignment value is too large");
1484     uint32_t AlignInBits = Record[8];
1485     uint64_t OffsetInBits = 0;
1486     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1487     Metadata *Elements = nullptr;
1488     unsigned RuntimeLang = Record[12];
1489     Metadata *VTableHolder = nullptr;
1490     Metadata *TemplateParams = nullptr;
1491     Metadata *Discriminator = nullptr;
1492     Metadata *DataLocation = nullptr;
1493     Metadata *Associated = nullptr;
1494     Metadata *Allocated = nullptr;
1495     Metadata *Rank = nullptr;
1496     Metadata *Annotations = nullptr;
1497     auto *Identifier = getMDString(Record[15]);
1498     // If this module is being parsed so that it can be ThinLTO imported
1499     // into another module, composite types only need to be imported
1500     // as type declarations (unless full type definitions requested).
1501     // Create type declarations up front to save memory. Also, buildODRType
1502     // handles the case where this is type ODRed with a definition needed
1503     // by the importing module, in which case the existing definition is
1504     // used.
1505     if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1506         (Tag == dwarf::DW_TAG_enumeration_type ||
1507          Tag == dwarf::DW_TAG_class_type ||
1508          Tag == dwarf::DW_TAG_structure_type ||
1509          Tag == dwarf::DW_TAG_union_type)) {
1510       Flags = Flags | DINode::FlagFwdDecl;
1511     } else {
1512       BaseType = getDITypeRefOrNull(Record[6]);
1513       OffsetInBits = Record[9];
1514       Elements = getMDOrNull(Record[11]);
1515       VTableHolder = getDITypeRefOrNull(Record[13]);
1516       TemplateParams = getMDOrNull(Record[14]);
1517       if (Record.size() > 16)
1518         Discriminator = getMDOrNull(Record[16]);
1519       if (Record.size() > 17)
1520         DataLocation = getMDOrNull(Record[17]);
1521       if (Record.size() > 19) {
1522         Associated = getMDOrNull(Record[18]);
1523         Allocated = getMDOrNull(Record[19]);
1524       }
1525       if (Record.size() > 20) {
1526         Rank = getMDOrNull(Record[20]);
1527       }
1528       if (Record.size() > 21) {
1529         Annotations = getMDOrNull(Record[21]);
1530       }
1531     }
1532     DICompositeType *CT = nullptr;
1533     if (Identifier)
1534       CT = DICompositeType::buildODRType(
1535           Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1536           SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1537           VTableHolder, TemplateParams, Discriminator, DataLocation, Associated,
1538           Allocated, Rank, Annotations);
1539 
1540     // Create a node if we didn't get a lazy ODR type.
1541     if (!CT)
1542       CT = GET_OR_DISTINCT(DICompositeType,
1543                            (Context, Tag, Name, File, Line, Scope, BaseType,
1544                             SizeInBits, AlignInBits, OffsetInBits, Flags,
1545                             Elements, RuntimeLang, VTableHolder, TemplateParams,
1546                             Identifier, Discriminator, DataLocation, Associated,
1547                             Allocated, Rank, Annotations));
1548     if (!IsNotUsedInTypeRef && Identifier)
1549       MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1550 
1551     MetadataList.assignValue(CT, NextMetadataNo);
1552     NextMetadataNo++;
1553     break;
1554   }
1555   case bitc::METADATA_SUBROUTINE_TYPE: {
1556     if (Record.size() < 3 || Record.size() > 4)
1557       return error("Invalid record");
1558     bool IsOldTypeRefArray = Record[0] < 2;
1559     unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1560 
1561     IsDistinct = Record[0] & 0x1;
1562     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1563     Metadata *Types = getMDOrNull(Record[2]);
1564     if (LLVM_UNLIKELY(IsOldTypeRefArray))
1565       Types = MetadataList.upgradeTypeRefArray(Types);
1566 
1567     MetadataList.assignValue(
1568         GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1569         NextMetadataNo);
1570     NextMetadataNo++;
1571     break;
1572   }
1573 
1574   case bitc::METADATA_MODULE: {
1575     if (Record.size() < 5 || Record.size() > 9)
1576       return error("Invalid record");
1577 
1578     unsigned Offset = Record.size() >= 8 ? 2 : 1;
1579     IsDistinct = Record[0];
1580     MetadataList.assignValue(
1581         GET_OR_DISTINCT(
1582             DIModule,
1583             (Context, Record.size() >= 8 ? getMDOrNull(Record[1]) : nullptr,
1584              getMDOrNull(Record[0 + Offset]), getMDString(Record[1 + Offset]),
1585              getMDString(Record[2 + Offset]), getMDString(Record[3 + Offset]),
1586              getMDString(Record[4 + Offset]),
1587              Record.size() <= 7 ? 0 : Record[7],
1588              Record.size() <= 8 ? false : Record[8])),
1589         NextMetadataNo);
1590     NextMetadataNo++;
1591     break;
1592   }
1593 
1594   case bitc::METADATA_FILE: {
1595     if (Record.size() != 3 && Record.size() != 5 && Record.size() != 6)
1596       return error("Invalid record");
1597 
1598     IsDistinct = Record[0];
1599     Optional<DIFile::ChecksumInfo<MDString *>> Checksum;
1600     // The BitcodeWriter writes null bytes into Record[3:4] when the Checksum
1601     // is not present. This matches up with the old internal representation,
1602     // and the old encoding for CSK_None in the ChecksumKind. The new
1603     // representation reserves the value 0 in the ChecksumKind to continue to
1604     // encode None in a backwards-compatible way.
1605     if (Record.size() > 4 && Record[3] && Record[4])
1606       Checksum.emplace(static_cast<DIFile::ChecksumKind>(Record[3]),
1607                        getMDString(Record[4]));
1608     MetadataList.assignValue(
1609         GET_OR_DISTINCT(
1610             DIFile,
1611             (Context, getMDString(Record[1]), getMDString(Record[2]), Checksum,
1612              Record.size() > 5 ? Optional<MDString *>(getMDString(Record[5]))
1613                                : None)),
1614         NextMetadataNo);
1615     NextMetadataNo++;
1616     break;
1617   }
1618   case bitc::METADATA_COMPILE_UNIT: {
1619     if (Record.size() < 14 || Record.size() > 22)
1620       return error("Invalid record");
1621 
1622     // Ignore Record[0], which indicates whether this compile unit is
1623     // distinct.  It's always distinct.
1624     IsDistinct = true;
1625     auto *CU = DICompileUnit::getDistinct(
1626         Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1627         Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1628         Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1629         getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1630         Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1631         Record.size() <= 14 ? 0 : Record[14],
1632         Record.size() <= 16 ? true : Record[16],
1633         Record.size() <= 17 ? false : Record[17],
1634         Record.size() <= 18 ? 0 : Record[18],
1635         Record.size() <= 19 ? 0 : Record[19],
1636         Record.size() <= 20 ? nullptr : getMDString(Record[20]),
1637         Record.size() <= 21 ? nullptr : getMDString(Record[21]));
1638 
1639     MetadataList.assignValue(CU, NextMetadataNo);
1640     NextMetadataNo++;
1641 
1642     // Move the Upgrade the list of subprograms.
1643     if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1644       CUSubprograms.push_back({CU, SPs});
1645     break;
1646   }
1647   case bitc::METADATA_SUBPROGRAM: {
1648     if (Record.size() < 18 || Record.size() > 21)
1649       return error("Invalid record");
1650 
1651     bool HasSPFlags = Record[0] & 4;
1652 
1653     DINode::DIFlags Flags;
1654     DISubprogram::DISPFlags SPFlags;
1655     if (!HasSPFlags)
1656       Flags = static_cast<DINode::DIFlags>(Record[11 + 2]);
1657     else {
1658       Flags = static_cast<DINode::DIFlags>(Record[11]);
1659       SPFlags = static_cast<DISubprogram::DISPFlags>(Record[9]);
1660     }
1661 
1662     // Support for old metadata when
1663     // subprogram specific flags are placed in DIFlags.
1664     const unsigned DIFlagMainSubprogram = 1 << 21;
1665     bool HasOldMainSubprogramFlag = Flags & DIFlagMainSubprogram;
1666     if (HasOldMainSubprogramFlag)
1667       // Remove old DIFlagMainSubprogram from DIFlags.
1668       // Note: This assumes that any future use of bit 21 defaults to it
1669       // being 0.
1670       Flags &= ~static_cast<DINode::DIFlags>(DIFlagMainSubprogram);
1671 
1672     if (HasOldMainSubprogramFlag && HasSPFlags)
1673       SPFlags |= DISubprogram::SPFlagMainSubprogram;
1674     else if (!HasSPFlags)
1675       SPFlags = DISubprogram::toSPFlags(
1676                     /*IsLocalToUnit=*/Record[7], /*IsDefinition=*/Record[8],
1677                     /*IsOptimized=*/Record[14], /*Virtuality=*/Record[11],
1678                     /*DIFlagMainSubprogram*/HasOldMainSubprogramFlag);
1679 
1680     // All definitions should be distinct.
1681     IsDistinct = (Record[0] & 1) || (SPFlags & DISubprogram::SPFlagDefinition);
1682     // Version 1 has a Function as Record[15].
1683     // Version 2 has removed Record[15].
1684     // Version 3 has the Unit as Record[15].
1685     // Version 4 added thisAdjustment.
1686     // Version 5 repacked flags into DISPFlags, changing many element numbers.
1687     bool HasUnit = Record[0] & 2;
1688     if (!HasSPFlags && HasUnit && Record.size() < 19)
1689       return error("Invalid record");
1690     if (HasSPFlags && !HasUnit)
1691       return error("Invalid record");
1692     // Accommodate older formats.
1693     bool HasFn = false;
1694     bool HasThisAdj = true;
1695     bool HasThrownTypes = true;
1696     bool HasAnnotations = false;
1697     unsigned OffsetA = 0;
1698     unsigned OffsetB = 0;
1699     if (!HasSPFlags) {
1700       OffsetA = 2;
1701       OffsetB = 2;
1702       if (Record.size() >= 19) {
1703         HasFn = !HasUnit;
1704         OffsetB++;
1705       }
1706       HasThisAdj = Record.size() >= 20;
1707       HasThrownTypes = Record.size() >= 21;
1708     } else {
1709       HasAnnotations = Record.size() >= 19;
1710     }
1711     Metadata *CUorFn = getMDOrNull(Record[12 + OffsetB]);
1712     DISubprogram *SP = GET_OR_DISTINCT(
1713         DISubprogram,
1714         (Context,
1715          getDITypeRefOrNull(Record[1]),                     // scope
1716          getMDString(Record[2]),                            // name
1717          getMDString(Record[3]),                            // linkageName
1718          getMDOrNull(Record[4]),                            // file
1719          Record[5],                                         // line
1720          getMDOrNull(Record[6]),                            // type
1721          Record[7 + OffsetA],                               // scopeLine
1722          getDITypeRefOrNull(Record[8 + OffsetA]),           // containingType
1723          Record[10 + OffsetA],                              // virtualIndex
1724          HasThisAdj ? Record[16 + OffsetB] : 0,             // thisAdjustment
1725          Flags,                                             // flags
1726          SPFlags,                                           // SPFlags
1727          HasUnit ? CUorFn : nullptr,                        // unit
1728          getMDOrNull(Record[13 + OffsetB]),                 // templateParams
1729          getMDOrNull(Record[14 + OffsetB]),                 // declaration
1730          getMDOrNull(Record[15 + OffsetB]),                 // retainedNodes
1731          HasThrownTypes ? getMDOrNull(Record[17 + OffsetB])
1732                         : nullptr,                          // thrownTypes
1733          HasAnnotations ? getMDOrNull(Record[18 + OffsetB])
1734                         : nullptr                           // annotations
1735          ));
1736     MetadataList.assignValue(SP, NextMetadataNo);
1737     NextMetadataNo++;
1738 
1739     // Upgrade sp->function mapping to function->sp mapping.
1740     if (HasFn) {
1741       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1742         if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1743           if (F->isMaterializable())
1744             // Defer until materialized; unmaterialized functions may not have
1745             // metadata.
1746             FunctionsWithSPs[F] = SP;
1747           else if (!F->empty())
1748             F->setSubprogram(SP);
1749         }
1750     }
1751     break;
1752   }
1753   case bitc::METADATA_LEXICAL_BLOCK: {
1754     if (Record.size() != 5)
1755       return error("Invalid record");
1756 
1757     IsDistinct = Record[0];
1758     MetadataList.assignValue(
1759         GET_OR_DISTINCT(DILexicalBlock,
1760                         (Context, getMDOrNull(Record[1]),
1761                          getMDOrNull(Record[2]), Record[3], Record[4])),
1762         NextMetadataNo);
1763     NextMetadataNo++;
1764     break;
1765   }
1766   case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1767     if (Record.size() != 4)
1768       return error("Invalid record");
1769 
1770     IsDistinct = Record[0];
1771     MetadataList.assignValue(
1772         GET_OR_DISTINCT(DILexicalBlockFile,
1773                         (Context, getMDOrNull(Record[1]),
1774                          getMDOrNull(Record[2]), Record[3])),
1775         NextMetadataNo);
1776     NextMetadataNo++;
1777     break;
1778   }
1779   case bitc::METADATA_COMMON_BLOCK: {
1780     IsDistinct = Record[0] & 1;
1781     MetadataList.assignValue(
1782         GET_OR_DISTINCT(DICommonBlock,
1783                         (Context, getMDOrNull(Record[1]),
1784                          getMDOrNull(Record[2]), getMDString(Record[3]),
1785                          getMDOrNull(Record[4]), Record[5])),
1786         NextMetadataNo);
1787     NextMetadataNo++;
1788     break;
1789   }
1790   case bitc::METADATA_NAMESPACE: {
1791     // Newer versions of DINamespace dropped file and line.
1792     MDString *Name;
1793     if (Record.size() == 3)
1794       Name = getMDString(Record[2]);
1795     else if (Record.size() == 5)
1796       Name = getMDString(Record[3]);
1797     else
1798       return error("Invalid record");
1799 
1800     IsDistinct = Record[0] & 1;
1801     bool ExportSymbols = Record[0] & 2;
1802     MetadataList.assignValue(
1803         GET_OR_DISTINCT(DINamespace,
1804                         (Context, getMDOrNull(Record[1]), Name, ExportSymbols)),
1805         NextMetadataNo);
1806     NextMetadataNo++;
1807     break;
1808   }
1809   case bitc::METADATA_MACRO: {
1810     if (Record.size() != 5)
1811       return error("Invalid record");
1812 
1813     IsDistinct = Record[0];
1814     MetadataList.assignValue(
1815         GET_OR_DISTINCT(DIMacro,
1816                         (Context, Record[1], Record[2], getMDString(Record[3]),
1817                          getMDString(Record[4]))),
1818         NextMetadataNo);
1819     NextMetadataNo++;
1820     break;
1821   }
1822   case bitc::METADATA_MACRO_FILE: {
1823     if (Record.size() != 5)
1824       return error("Invalid record");
1825 
1826     IsDistinct = Record[0];
1827     MetadataList.assignValue(
1828         GET_OR_DISTINCT(DIMacroFile,
1829                         (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1830                          getMDOrNull(Record[4]))),
1831         NextMetadataNo);
1832     NextMetadataNo++;
1833     break;
1834   }
1835   case bitc::METADATA_TEMPLATE_TYPE: {
1836     if (Record.size() < 3 || Record.size() > 4)
1837       return error("Invalid record");
1838 
1839     IsDistinct = Record[0];
1840     MetadataList.assignValue(
1841         GET_OR_DISTINCT(DITemplateTypeParameter,
1842                         (Context, getMDString(Record[1]),
1843                          getDITypeRefOrNull(Record[2]),
1844                          (Record.size() == 4) ? getMDOrNull(Record[3])
1845                                               : getMDOrNull(false))),
1846         NextMetadataNo);
1847     NextMetadataNo++;
1848     break;
1849   }
1850   case bitc::METADATA_TEMPLATE_VALUE: {
1851     if (Record.size() < 5 || Record.size() > 6)
1852       return error("Invalid record");
1853 
1854     IsDistinct = Record[0];
1855 
1856     MetadataList.assignValue(
1857         GET_OR_DISTINCT(
1858             DITemplateValueParameter,
1859             (Context, Record[1], getMDString(Record[2]),
1860              getDITypeRefOrNull(Record[3]),
1861              (Record.size() == 6) ? getMDOrNull(Record[4]) : getMDOrNull(false),
1862              (Record.size() == 6) ? getMDOrNull(Record[5])
1863                                   : getMDOrNull(Record[4]))),
1864         NextMetadataNo);
1865     NextMetadataNo++;
1866     break;
1867   }
1868   case bitc::METADATA_GLOBAL_VAR: {
1869     if (Record.size() < 11 || Record.size() > 13)
1870       return error("Invalid record");
1871 
1872     IsDistinct = Record[0] & 1;
1873     unsigned Version = Record[0] >> 1;
1874 
1875     if (Version == 2) {
1876       Metadata *Annotations = nullptr;
1877       if (Record.size() > 12)
1878         Annotations = getMDOrNull(Record[12]);
1879 
1880       MetadataList.assignValue(
1881           GET_OR_DISTINCT(
1882               DIGlobalVariable,
1883               (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1884                getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1885                getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1886                getMDOrNull(Record[9]), getMDOrNull(Record[10]), Record[11],
1887                Annotations)),
1888           NextMetadataNo);
1889 
1890       NextMetadataNo++;
1891     } else if (Version == 1) {
1892       // No upgrade necessary. A null field will be introduced to indicate
1893       // that no parameter information is available.
1894       MetadataList.assignValue(
1895           GET_OR_DISTINCT(DIGlobalVariable,
1896                           (Context, getMDOrNull(Record[1]),
1897                            getMDString(Record[2]), getMDString(Record[3]),
1898                            getMDOrNull(Record[4]), Record[5],
1899                            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1900                            getMDOrNull(Record[10]), nullptr, Record[11],
1901                            nullptr)),
1902           NextMetadataNo);
1903 
1904       NextMetadataNo++;
1905     } else if (Version == 0) {
1906       // Upgrade old metadata, which stored a global variable reference or a
1907       // ConstantInt here.
1908       NeedUpgradeToDIGlobalVariableExpression = true;
1909       Metadata *Expr = getMDOrNull(Record[9]);
1910       uint32_t AlignInBits = 0;
1911       if (Record.size() > 11) {
1912         if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1913           return error("Alignment value is too large");
1914         AlignInBits = Record[11];
1915       }
1916       GlobalVariable *Attach = nullptr;
1917       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1918         if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1919           Attach = GV;
1920           Expr = nullptr;
1921         } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1922           Expr = DIExpression::get(Context,
1923                                    {dwarf::DW_OP_constu, CI->getZExtValue(),
1924                                     dwarf::DW_OP_stack_value});
1925         } else {
1926           Expr = nullptr;
1927         }
1928       }
1929       DIGlobalVariable *DGV = GET_OR_DISTINCT(
1930           DIGlobalVariable,
1931           (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1932            getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1933            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1934            getMDOrNull(Record[10]), nullptr, AlignInBits, nullptr));
1935 
1936       DIGlobalVariableExpression *DGVE = nullptr;
1937       if (Attach || Expr)
1938         DGVE = DIGlobalVariableExpression::getDistinct(
1939             Context, DGV, Expr ? Expr : DIExpression::get(Context, {}));
1940       if (Attach)
1941         Attach->addDebugInfo(DGVE);
1942 
1943       auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1944       MetadataList.assignValue(MDNode, NextMetadataNo);
1945       NextMetadataNo++;
1946     } else
1947       return error("Invalid record");
1948 
1949     break;
1950   }
1951   case bitc::METADATA_LOCAL_VAR: {
1952     // 10th field is for the obseleted 'inlinedAt:' field.
1953     if (Record.size() < 8 || Record.size() > 10)
1954       return error("Invalid record");
1955 
1956     IsDistinct = Record[0] & 1;
1957     bool HasAlignment = Record[0] & 2;
1958     // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1959     // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1960     // this is newer version of record which doesn't have artificial tag.
1961     bool HasTag = !HasAlignment && Record.size() > 8;
1962     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1963     uint32_t AlignInBits = 0;
1964     Metadata *Annotations = nullptr;
1965     if (HasAlignment) {
1966       if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1967         return error("Alignment value is too large");
1968       AlignInBits = Record[8];
1969       if (Record.size() > 9)
1970         Annotations = getMDOrNull(Record[9]);
1971     }
1972 
1973     MetadataList.assignValue(
1974         GET_OR_DISTINCT(DILocalVariable,
1975                         (Context, getMDOrNull(Record[1 + HasTag]),
1976                          getMDString(Record[2 + HasTag]),
1977                          getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1978                          getDITypeRefOrNull(Record[5 + HasTag]),
1979                          Record[6 + HasTag], Flags, AlignInBits,
1980                          Annotations)),
1981         NextMetadataNo);
1982     NextMetadataNo++;
1983     break;
1984   }
1985   case bitc::METADATA_LABEL: {
1986     if (Record.size() != 5)
1987       return error("Invalid record");
1988 
1989     IsDistinct = Record[0] & 1;
1990     MetadataList.assignValue(
1991         GET_OR_DISTINCT(DILabel,
1992                         (Context, getMDOrNull(Record[1]),
1993                          getMDString(Record[2]),
1994                          getMDOrNull(Record[3]), Record[4])),
1995         NextMetadataNo);
1996     NextMetadataNo++;
1997     break;
1998   }
1999   case bitc::METADATA_EXPRESSION: {
2000     if (Record.size() < 1)
2001       return error("Invalid record");
2002 
2003     IsDistinct = Record[0] & 1;
2004     uint64_t Version = Record[0] >> 1;
2005     auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
2006 
2007     SmallVector<uint64_t, 6> Buffer;
2008     if (Error Err = upgradeDIExpression(Version, IsDistinct, Elts, Buffer))
2009       return Err;
2010 
2011     if (IsDistinct)
2012       return error("Invalid record");
2013 
2014     MetadataList.assignValue(DIExpression::get(Context, Elts), NextMetadataNo);
2015     NextMetadataNo++;
2016     break;
2017   }
2018   case bitc::METADATA_GLOBAL_VAR_EXPR: {
2019     if (Record.size() != 3)
2020       return error("Invalid record");
2021 
2022     IsDistinct = Record[0];
2023     Metadata *Expr = getMDOrNull(Record[2]);
2024     if (!Expr)
2025       Expr = DIExpression::get(Context, {});
2026     MetadataList.assignValue(
2027         GET_OR_DISTINCT(DIGlobalVariableExpression,
2028                         (Context, getMDOrNull(Record[1]), Expr)),
2029         NextMetadataNo);
2030     NextMetadataNo++;
2031     break;
2032   }
2033   case bitc::METADATA_OBJC_PROPERTY: {
2034     if (Record.size() != 8)
2035       return error("Invalid record");
2036 
2037     IsDistinct = Record[0];
2038     MetadataList.assignValue(
2039         GET_OR_DISTINCT(DIObjCProperty,
2040                         (Context, getMDString(Record[1]),
2041                          getMDOrNull(Record[2]), Record[3],
2042                          getMDString(Record[4]), getMDString(Record[5]),
2043                          Record[6], getDITypeRefOrNull(Record[7]))),
2044         NextMetadataNo);
2045     NextMetadataNo++;
2046     break;
2047   }
2048   case bitc::METADATA_IMPORTED_ENTITY: {
2049     if (Record.size() < 6 && Record.size() > 8)
2050       return error("Invalid record");
2051 
2052     IsDistinct = Record[0];
2053     bool HasFile = (Record.size() >= 7);
2054     bool HasElements = (Record.size() >= 8);
2055     MetadataList.assignValue(
2056         GET_OR_DISTINCT(DIImportedEntity,
2057                         (Context, Record[1], getMDOrNull(Record[2]),
2058                          getDITypeRefOrNull(Record[3]),
2059                          HasFile ? getMDOrNull(Record[6]) : nullptr,
2060                          HasFile ? Record[4] : 0, getMDString(Record[5]),
2061                          HasElements ? getMDOrNull(Record[7]) : nullptr)),
2062         NextMetadataNo);
2063     NextMetadataNo++;
2064     break;
2065   }
2066   case bitc::METADATA_STRING_OLD: {
2067     std::string String(Record.begin(), Record.end());
2068 
2069     // Test for upgrading !llvm.loop.
2070     HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2071     ++NumMDStringLoaded;
2072     Metadata *MD = MDString::get(Context, String);
2073     MetadataList.assignValue(MD, NextMetadataNo);
2074     NextMetadataNo++;
2075     break;
2076   }
2077   case bitc::METADATA_STRINGS: {
2078     auto CreateNextMDString = [&](StringRef Str) {
2079       ++NumMDStringLoaded;
2080       MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
2081       NextMetadataNo++;
2082     };
2083     if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
2084       return Err;
2085     break;
2086   }
2087   case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
2088     if (Record.size() % 2 == 0)
2089       return error("Invalid record");
2090     unsigned ValueID = Record[0];
2091     if (ValueID >= ValueList.size())
2092       return error("Invalid record");
2093     if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
2094       if (Error Err = parseGlobalObjectAttachment(
2095               *GO, ArrayRef<uint64_t>(Record).slice(1)))
2096         return Err;
2097     break;
2098   }
2099   case bitc::METADATA_KIND: {
2100     // Support older bitcode files that had METADATA_KIND records in a
2101     // block with METADATA_BLOCK_ID.
2102     if (Error Err = parseMetadataKindRecord(Record))
2103       return Err;
2104     break;
2105   }
2106   case bitc::METADATA_ARG_LIST: {
2107     SmallVector<ValueAsMetadata *, 4> Elts;
2108     Elts.reserve(Record.size());
2109     for (uint64_t Elt : Record) {
2110       Metadata *MD = getMD(Elt);
2111       if (isa<MDNode>(MD) && cast<MDNode>(MD)->isTemporary())
2112         return error(
2113             "Invalid record: DIArgList should not contain forward refs");
2114       if (!isa<ValueAsMetadata>(MD))
2115         return error("Invalid record");
2116       Elts.push_back(cast<ValueAsMetadata>(MD));
2117     }
2118 
2119     MetadataList.assignValue(DIArgList::get(Context, Elts), NextMetadataNo);
2120     NextMetadataNo++;
2121     break;
2122   }
2123   }
2124   return Error::success();
2125 #undef GET_OR_DISTINCT
2126 }
2127 
2128 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
2129     ArrayRef<uint64_t> Record, StringRef Blob,
2130     function_ref<void(StringRef)> CallBack) {
2131   // All the MDStrings in the block are emitted together in a single
2132   // record.  The strings are concatenated and stored in a blob along with
2133   // their sizes.
2134   if (Record.size() != 2)
2135     return error("Invalid record: metadata strings layout");
2136 
2137   unsigned NumStrings = Record[0];
2138   unsigned StringsOffset = Record[1];
2139   if (!NumStrings)
2140     return error("Invalid record: metadata strings with no strings");
2141   if (StringsOffset > Blob.size())
2142     return error("Invalid record: metadata strings corrupt offset");
2143 
2144   StringRef Lengths = Blob.slice(0, StringsOffset);
2145   SimpleBitstreamCursor R(Lengths);
2146 
2147   StringRef Strings = Blob.drop_front(StringsOffset);
2148   do {
2149     if (R.AtEndOfStream())
2150       return error("Invalid record: metadata strings bad length");
2151 
2152     uint32_t Size;
2153     if (Error E = R.ReadVBR(6).moveInto(Size))
2154       return E;
2155     if (Strings.size() < Size)
2156       return error("Invalid record: metadata strings truncated chars");
2157 
2158     CallBack(Strings.slice(0, Size));
2159     Strings = Strings.drop_front(Size);
2160   } while (--NumStrings);
2161 
2162   return Error::success();
2163 }
2164 
2165 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
2166     GlobalObject &GO, ArrayRef<uint64_t> Record) {
2167   assert(Record.size() % 2 == 0);
2168   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
2169     auto K = MDKindMap.find(Record[I]);
2170     if (K == MDKindMap.end())
2171       return error("Invalid ID");
2172     MDNode *MD =
2173         dyn_cast_or_null<MDNode>(getMetadataFwdRefOrLoad(Record[I + 1]));
2174     if (!MD)
2175       return error("Invalid metadata attachment: expect fwd ref to MDNode");
2176     GO.addMetadata(K->second, *MD);
2177   }
2178   return Error::success();
2179 }
2180 
2181 /// Parse metadata attachments.
2182 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
2183     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
2184   if (Error Err = Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2185     return Err;
2186 
2187   SmallVector<uint64_t, 64> Record;
2188   PlaceholderQueue Placeholders;
2189 
2190   while (true) {
2191     BitstreamEntry Entry;
2192     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2193       return E;
2194 
2195     switch (Entry.Kind) {
2196     case BitstreamEntry::SubBlock: // Handled for us already.
2197     case BitstreamEntry::Error:
2198       return error("Malformed block");
2199     case BitstreamEntry::EndBlock:
2200       resolveForwardRefsAndPlaceholders(Placeholders);
2201       return Error::success();
2202     case BitstreamEntry::Record:
2203       // The interesting case.
2204       break;
2205     }
2206 
2207     // Read a metadata attachment record.
2208     Record.clear();
2209     ++NumMDRecordLoaded;
2210     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2211     if (!MaybeRecord)
2212       return MaybeRecord.takeError();
2213     switch (MaybeRecord.get()) {
2214     default: // Default behavior: ignore.
2215       break;
2216     case bitc::METADATA_ATTACHMENT: {
2217       unsigned RecordLength = Record.size();
2218       if (Record.empty())
2219         return error("Invalid record");
2220       if (RecordLength % 2 == 0) {
2221         // A function attachment.
2222         if (Error Err = parseGlobalObjectAttachment(F, Record))
2223           return Err;
2224         continue;
2225       }
2226 
2227       // An instruction attachment.
2228       Instruction *Inst = InstructionList[Record[0]];
2229       for (unsigned i = 1; i != RecordLength; i = i + 2) {
2230         unsigned Kind = Record[i];
2231         DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
2232         if (I == MDKindMap.end())
2233           return error("Invalid ID");
2234         if (I->second == LLVMContext::MD_tbaa && StripTBAA)
2235           continue;
2236 
2237         auto Idx = Record[i + 1];
2238         if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
2239             !MetadataList.lookup(Idx)) {
2240           // Load the attachment if it is in the lazy-loadable range and hasn't
2241           // been loaded yet.
2242           lazyLoadOneMetadata(Idx, Placeholders);
2243           resolveForwardRefsAndPlaceholders(Placeholders);
2244         }
2245 
2246         Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
2247         if (isa<LocalAsMetadata>(Node))
2248           // Drop the attachment.  This used to be legal, but there's no
2249           // upgrade path.
2250           break;
2251         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
2252         if (!MD)
2253           return error("Invalid metadata attachment");
2254 
2255         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
2256           MD = upgradeInstructionLoopAttachment(*MD);
2257 
2258         if (I->second == LLVMContext::MD_tbaa) {
2259           assert(!MD->isTemporary() && "should load MDs before attachments");
2260           MD = UpgradeTBAANode(*MD);
2261         }
2262         Inst->setMetadata(I->second, MD);
2263       }
2264       break;
2265     }
2266     }
2267   }
2268 }
2269 
2270 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
2271 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
2272     SmallVectorImpl<uint64_t> &Record) {
2273   if (Record.size() < 2)
2274     return error("Invalid record");
2275 
2276   unsigned Kind = Record[0];
2277   SmallString<8> Name(Record.begin() + 1, Record.end());
2278 
2279   unsigned NewKind = TheModule.getMDKindID(Name.str());
2280   if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
2281     return error("Conflicting METADATA_KIND records");
2282   return Error::success();
2283 }
2284 
2285 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2286 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
2287   if (Error Err = Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2288     return Err;
2289 
2290   SmallVector<uint64_t, 64> Record;
2291 
2292   // Read all the records.
2293   while (true) {
2294     BitstreamEntry Entry;
2295     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
2296       return E;
2297 
2298     switch (Entry.Kind) {
2299     case BitstreamEntry::SubBlock: // Handled for us already.
2300     case BitstreamEntry::Error:
2301       return error("Malformed block");
2302     case BitstreamEntry::EndBlock:
2303       return Error::success();
2304     case BitstreamEntry::Record:
2305       // The interesting case.
2306       break;
2307     }
2308 
2309     // Read a record.
2310     Record.clear();
2311     ++NumMDRecordLoaded;
2312     Expected<unsigned> MaybeCode = Stream.readRecord(Entry.ID, Record);
2313     if (!MaybeCode)
2314       return MaybeCode.takeError();
2315     switch (MaybeCode.get()) {
2316     default: // Default behavior: ignore.
2317       break;
2318     case bitc::METADATA_KIND: {
2319       if (Error Err = parseMetadataKindRecord(Record))
2320         return Err;
2321       break;
2322     }
2323     }
2324   }
2325 }
2326 
2327 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
2328   Pimpl = std::move(RHS.Pimpl);
2329   return *this;
2330 }
2331 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
2332     : Pimpl(std::move(RHS.Pimpl)) {}
2333 
2334 MetadataLoader::~MetadataLoader() = default;
2335 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
2336                                BitcodeReaderValueList &ValueList,
2337                                bool IsImporting,
2338                                std::function<Type *(unsigned)> getTypeByID)
2339     : Pimpl(std::make_unique<MetadataLoaderImpl>(
2340           Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
2341 
2342 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
2343   return Pimpl->parseMetadata(ModuleLevel);
2344 }
2345 
2346 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
2347 
2348 /// Return the given metadata, creating a replaceable forward reference if
2349 /// necessary.
2350 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
2351   return Pimpl->getMetadataFwdRefOrLoad(Idx);
2352 }
2353 
2354 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
2355   return Pimpl->lookupSubprogramForFunction(F);
2356 }
2357 
2358 Error MetadataLoader::parseMetadataAttachment(
2359     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
2360   return Pimpl->parseMetadataAttachment(F, InstructionList);
2361 }
2362 
2363 Error MetadataLoader::parseMetadataKinds() {
2364   return Pimpl->parseMetadataKinds();
2365 }
2366 
2367 void MetadataLoader::setStripTBAA(bool StripTBAA) {
2368   return Pimpl->setStripTBAA(StripTBAA);
2369 }
2370 
2371 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
2372 
2373 unsigned MetadataLoader::size() const { return Pimpl->size(); }
2374 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
2375 
2376 void MetadataLoader::upgradeDebugIntrinsics(Function &F) {
2377   return Pimpl->upgradeDebugIntrinsics(F);
2378 }
2379