1 //===- MetadataLoader.cpp - Internal BitcodeReader implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
12 
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Bitcode/BitcodeReader.h"
27 #include "llvm/Bitcode/BitstreamReader.h"
28 #include "llvm/Bitcode/LLVMBitCodes.h"
29 #include "llvm/IR/Argument.h"
30 #include "llvm/IR/Attributes.h"
31 #include "llvm/IR/AutoUpgrade.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constant.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DebugInfo.h"
39 #include "llvm/IR/DebugInfoMetadata.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/DiagnosticPrinter.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/GVMaterializer.h"
46 #include "llvm/IR/GlobalAlias.h"
47 #include "llvm/IR/GlobalIFunc.h"
48 #include "llvm/IR/GlobalIndirectSymbol.h"
49 #include "llvm/IR/GlobalObject.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/IR/GlobalVariable.h"
52 #include "llvm/IR/InlineAsm.h"
53 #include "llvm/IR/InstrTypes.h"
54 #include "llvm/IR/Instruction.h"
55 #include "llvm/IR/Instructions.h"
56 #include "llvm/IR/Intrinsics.h"
57 #include "llvm/IR/LLVMContext.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/ModuleSummaryIndex.h"
60 #include "llvm/IR/OperandTraits.h"
61 #include "llvm/IR/Operator.h"
62 #include "llvm/IR/TrackingMDRef.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/ValueHandle.h"
65 #include "llvm/Support/AtomicOrdering.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/Support/Error.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/ManagedStatic.h"
73 #include "llvm/Support/MemoryBuffer.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <deque>
80 #include <limits>
81 #include <map>
82 #include <memory>
83 #include <string>
84 #include <system_error>
85 #include <tuple>
86 #include <utility>
87 #include <vector>
88 
89 using namespace llvm;
90 
91 #define DEBUG_TYPE "bitcode-reader"
92 
93 STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
94 STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
95 STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
96 
97 /// Flag whether we need to import full type definitions for ThinLTO.
98 /// Currently needed for Darwin and LLDB.
99 static cl::opt<bool> ImportFullTypeDefinitions(
100     "import-full-type-definitions", cl::init(false), cl::Hidden,
101     cl::desc("Import full type definitions for ThinLTO."));
102 
103 static cl::opt<bool> DisableLazyLoading(
104     "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
105     cl::desc("Force disable the lazy-loading on-demand of metadata when "
106              "loading bitcode for importing."));
107 
108 namespace {
109 
110 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
111 
112 class BitcodeReaderMetadataList {
113   /// Array of metadata references.
114   ///
115   /// Don't use std::vector here.  Some versions of libc++ copy (instead of
116   /// move) on resize, and TrackingMDRef is very expensive to copy.
117   SmallVector<TrackingMDRef, 1> MetadataPtrs;
118 
119   /// The set of indices in MetadataPtrs above of forward references that were
120   /// generated.
121   SmallDenseSet<unsigned, 1> ForwardReference;
122 
123   /// The set of indices in MetadataPtrs above of Metadata that need to be
124   /// resolved.
125   SmallDenseSet<unsigned, 1> UnresolvedNodes;
126 
127   /// Structures for resolving old type refs.
128   struct {
129     SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
130     SmallDenseMap<MDString *, DICompositeType *, 1> Final;
131     SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
132     SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
133   } OldTypeRefs;
134 
135   LLVMContext &Context;
136 
137 public:
138   BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
139 
140   // vector compatibility methods
141   unsigned size() const { return MetadataPtrs.size(); }
142   void resize(unsigned N) { MetadataPtrs.resize(N); }
143   void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
144   void clear() { MetadataPtrs.clear(); }
145   Metadata *back() const { return MetadataPtrs.back(); }
146   void pop_back() { MetadataPtrs.pop_back(); }
147   bool empty() const { return MetadataPtrs.empty(); }
148 
149   Metadata *operator[](unsigned i) const {
150     assert(i < MetadataPtrs.size());
151     return MetadataPtrs[i];
152   }
153 
154   Metadata *lookup(unsigned I) const {
155     if (I < MetadataPtrs.size())
156       return MetadataPtrs[I];
157     return nullptr;
158   }
159 
160   void shrinkTo(unsigned N) {
161     assert(N <= size() && "Invalid shrinkTo request!");
162     assert(ForwardReference.empty() && "Unexpected forward refs");
163     assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
164     MetadataPtrs.resize(N);
165   }
166 
167   /// Return the given metadata, creating a replaceable forward reference if
168   /// necessary.
169   Metadata *getMetadataFwdRef(unsigned Idx);
170 
171   /// Return the the given metadata only if it is fully resolved.
172   ///
173   /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
174   /// would give \c false.
175   Metadata *getMetadataIfResolved(unsigned Idx);
176 
177   MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
178   void assignValue(Metadata *MD, unsigned Idx);
179   void tryToResolveCycles();
180   bool hasFwdRefs() const { return !ForwardReference.empty(); }
181   int getNextFwdRef() {
182     assert(hasFwdRefs());
183     return *ForwardReference.begin();
184   }
185 
186   /// Upgrade a type that had an MDString reference.
187   void addTypeRef(MDString &UUID, DICompositeType &CT);
188 
189   /// Upgrade a type that had an MDString reference.
190   Metadata *upgradeTypeRef(Metadata *MaybeUUID);
191 
192   /// Upgrade a type ref array that may have MDString references.
193   Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
194 
195 private:
196   Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
197 };
198 
199 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
200   if (auto *MDN = dyn_cast<MDNode>(MD))
201     if (!MDN->isResolved())
202       UnresolvedNodes.insert(Idx);
203 
204   if (Idx == size()) {
205     push_back(MD);
206     return;
207   }
208 
209   if (Idx >= size())
210     resize(Idx + 1);
211 
212   TrackingMDRef &OldMD = MetadataPtrs[Idx];
213   if (!OldMD) {
214     OldMD.reset(MD);
215     return;
216   }
217 
218   // If there was a forward reference to this value, replace it.
219   TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
220   PrevMD->replaceAllUsesWith(MD);
221   ForwardReference.erase(Idx);
222 }
223 
224 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
225   if (Idx >= size())
226     resize(Idx + 1);
227 
228   if (Metadata *MD = MetadataPtrs[Idx])
229     return MD;
230 
231   // Track forward refs to be resolved later.
232   ForwardReference.insert(Idx);
233 
234   // Create and return a placeholder, which will later be RAUW'd.
235   ++NumMDNodeTemporary;
236   Metadata *MD = MDNode::getTemporary(Context, None).release();
237   MetadataPtrs[Idx].reset(MD);
238   return MD;
239 }
240 
241 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
242   Metadata *MD = lookup(Idx);
243   if (auto *N = dyn_cast_or_null<MDNode>(MD))
244     if (!N->isResolved())
245       return nullptr;
246   return MD;
247 }
248 
249 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
250   return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
251 }
252 
253 void BitcodeReaderMetadataList::tryToResolveCycles() {
254   if (!ForwardReference.empty())
255     // Still forward references... can't resolve cycles.
256     return;
257 
258   // Give up on finding a full definition for any forward decls that remain.
259   for (const auto &Ref : OldTypeRefs.FwdDecls)
260     OldTypeRefs.Final.insert(Ref);
261   OldTypeRefs.FwdDecls.clear();
262 
263   // Upgrade from old type ref arrays.  In strange cases, this could add to
264   // OldTypeRefs.Unknown.
265   for (const auto &Array : OldTypeRefs.Arrays)
266     Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
267   OldTypeRefs.Arrays.clear();
268 
269   // Replace old string-based type refs with the resolved node, if possible.
270   // If we haven't seen the node, leave it to the verifier to complain about
271   // the invalid string reference.
272   for (const auto &Ref : OldTypeRefs.Unknown) {
273     if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
274       Ref.second->replaceAllUsesWith(CT);
275     else
276       Ref.second->replaceAllUsesWith(Ref.first);
277   }
278   OldTypeRefs.Unknown.clear();
279 
280   if (UnresolvedNodes.empty())
281     // Nothing to do.
282     return;
283 
284   // Resolve any cycles.
285   for (unsigned I : UnresolvedNodes) {
286     auto &MD = MetadataPtrs[I];
287     auto *N = dyn_cast_or_null<MDNode>(MD);
288     if (!N)
289       continue;
290 
291     assert(!N->isTemporary() && "Unexpected forward reference");
292     N->resolveCycles();
293   }
294 
295   // Make sure we return early again until there's another unresolved ref.
296   UnresolvedNodes.clear();
297 }
298 
299 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
300                                            DICompositeType &CT) {
301   assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
302   if (CT.isForwardDecl())
303     OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
304   else
305     OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
306 }
307 
308 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
309   auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
310   if (LLVM_LIKELY(!UUID))
311     return MaybeUUID;
312 
313   if (auto *CT = OldTypeRefs.Final.lookup(UUID))
314     return CT;
315 
316   auto &Ref = OldTypeRefs.Unknown[UUID];
317   if (!Ref)
318     Ref = MDNode::getTemporary(Context, None);
319   return Ref.get();
320 }
321 
322 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
323   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
324   if (!Tuple || Tuple->isDistinct())
325     return MaybeTuple;
326 
327   // Look through the array immediately if possible.
328   if (!Tuple->isTemporary())
329     return resolveTypeRefArray(Tuple);
330 
331   // Create and return a placeholder to use for now.  Eventually
332   // resolveTypeRefArrays() will be resolve this forward reference.
333   OldTypeRefs.Arrays.emplace_back(
334       std::piecewise_construct, std::forward_as_tuple(Tuple),
335       std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
336   return OldTypeRefs.Arrays.back().second.get();
337 }
338 
339 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
340   auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
341   if (!Tuple || Tuple->isDistinct())
342     return MaybeTuple;
343 
344   // Look through the DITypeRefArray, upgrading each DITypeRef.
345   SmallVector<Metadata *, 32> Ops;
346   Ops.reserve(Tuple->getNumOperands());
347   for (Metadata *MD : Tuple->operands())
348     Ops.push_back(upgradeTypeRef(MD));
349 
350   return MDTuple::get(Context, Ops);
351 }
352 
353 namespace {
354 
355 class PlaceholderQueue {
356   // Placeholders would thrash around when moved, so store in a std::deque
357   // instead of some sort of vector.
358   std::deque<DistinctMDOperandPlaceholder> PHs;
359 
360 public:
361   ~PlaceholderQueue() {
362     assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
363   }
364   bool empty() { return PHs.empty(); }
365   DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
366   void flush(BitcodeReaderMetadataList &MetadataList);
367 
368   /// Return the list of temporaries nodes in the queue, these need to be
369   /// loaded before we can flush the queue.
370   void getTemporaries(BitcodeReaderMetadataList &MetadataList,
371                       DenseSet<unsigned> &Temporaries) {
372     for (auto &PH : PHs) {
373       auto ID = PH.getID();
374       auto *MD = MetadataList.lookup(ID);
375       if (!MD) {
376         Temporaries.insert(ID);
377         continue;
378       }
379       auto *N = dyn_cast_or_null<MDNode>(MD);
380       if (N && N->isTemporary())
381         Temporaries.insert(ID);
382     }
383   }
384 };
385 
386 } // end anonymous namespace
387 
388 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
389   PHs.emplace_back(ID);
390   return PHs.back();
391 }
392 
393 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
394   while (!PHs.empty()) {
395     auto *MD = MetadataList.lookup(PHs.front().getID());
396     assert(MD && "Flushing placeholder on unassigned MD");
397 #ifndef NDEBUG
398     if (auto *MDN = dyn_cast<MDNode>(MD))
399       assert(MDN->isResolved() &&
400              "Flushing Placeholder while cycles aren't resolved");
401 #endif
402     PHs.front().replaceUseWith(MD);
403     PHs.pop_front();
404   }
405 }
406 
407 } // anonynous namespace
408 
409 class MetadataLoader::MetadataLoaderImpl {
410   BitcodeReaderMetadataList MetadataList;
411   BitcodeReaderValueList &ValueList;
412   BitstreamCursor &Stream;
413   LLVMContext &Context;
414   Module &TheModule;
415   std::function<Type *(unsigned)> getTypeByID;
416 
417   /// Cursor associated with the lazy-loading of Metadata. This is the easy way
418   /// to keep around the right "context" (Abbrev list) to be able to jump in
419   /// the middle of the metadata block and load any record.
420   BitstreamCursor IndexCursor;
421 
422   /// Index that keeps track of MDString values.
423   std::vector<StringRef> MDStringRef;
424 
425   /// On-demand loading of a single MDString. Requires the index above to be
426   /// populated.
427   MDString *lazyLoadOneMDString(unsigned Idx);
428 
429   /// Index that keeps track of where to find a metadata record in the stream.
430   std::vector<uint64_t> GlobalMetadataBitPosIndex;
431 
432   /// Populate the index above to enable lazily loading of metadata, and load
433   /// the named metadata as well as the transitively referenced global
434   /// Metadata.
435   Expected<bool> lazyLoadModuleMetadataBlock();
436 
437   /// On-demand loading of a single metadata. Requires the index above to be
438   /// populated.
439   void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
440 
441   // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
442   // point from SP to CU after a block is completly parsed.
443   std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
444 
445   /// Functions that need to be matched with subprograms when upgrading old
446   /// metadata.
447   SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
448 
449   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
450   DenseMap<unsigned, unsigned> MDKindMap;
451 
452   bool StripTBAA = false;
453   bool HasSeenOldLoopTags = false;
454   bool NeedUpgradeToDIGlobalVariableExpression = false;
455 
456   /// True if metadata is being parsed for a module being ThinLTO imported.
457   bool IsImporting = false;
458 
459   Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
460                          PlaceholderQueue &Placeholders, StringRef Blob,
461                          unsigned &NextMetadataNo);
462   Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
463                              function_ref<void(StringRef)> CallBack);
464   Error parseGlobalObjectAttachment(GlobalObject &GO,
465                                     ArrayRef<uint64_t> Record);
466   Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
467 
468   void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
469 
470   /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
471   void upgradeCUSubprograms() {
472     for (auto CU_SP : CUSubprograms)
473       if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
474         for (auto &Op : SPs->operands())
475           if (auto *SP = dyn_cast_or_null<MDNode>(Op))
476             SP->replaceOperandWith(7, CU_SP.first);
477     CUSubprograms.clear();
478   }
479 
480   /// Upgrade old-style bare DIGlobalVariables to DIGlobalVariableExpressions.
481   void upgradeCUVariables() {
482     if (!NeedUpgradeToDIGlobalVariableExpression)
483       return;
484 
485     // Upgrade list of variables attached to the CUs.
486     if (NamedMDNode *CUNodes = TheModule.getNamedMetadata("llvm.dbg.cu"))
487       for (unsigned I = 0, E = CUNodes->getNumOperands(); I != E; ++I) {
488         auto *CU = cast<DICompileUnit>(CUNodes->getOperand(I));
489         if (auto *GVs = dyn_cast_or_null<MDTuple>(CU->getRawGlobalVariables()))
490           for (unsigned I = 0; I < GVs->getNumOperands(); I++)
491             if (auto *GV =
492                     dyn_cast_or_null<DIGlobalVariable>(GVs->getOperand(I))) {
493               auto *DGVE =
494                   DIGlobalVariableExpression::getDistinct(Context, GV, nullptr);
495               GVs->replaceOperandWith(I, DGVE);
496             }
497       }
498 
499     // Upgrade variables attached to globals.
500     for (auto &GV : TheModule.globals()) {
501       SmallVector<MDNode *, 1> MDs, NewMDs;
502       GV.getMetadata(LLVMContext::MD_dbg, MDs);
503       GV.eraseMetadata(LLVMContext::MD_dbg);
504       for (auto *MD : MDs)
505         if (auto *DGV = dyn_cast_or_null<DIGlobalVariable>(MD)) {
506           auto *DGVE =
507               DIGlobalVariableExpression::getDistinct(Context, DGV, nullptr);
508           GV.addMetadata(LLVMContext::MD_dbg, *DGVE);
509         } else
510           GV.addMetadata(LLVMContext::MD_dbg, *MD);
511     }
512   }
513 
514   void upgradeDebugInfo() {
515     upgradeCUSubprograms();
516     upgradeCUVariables();
517   }
518 
519 public:
520   MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
521                      BitcodeReaderValueList &ValueList,
522                      std::function<Type *(unsigned)> getTypeByID,
523                      bool IsImporting)
524       : MetadataList(TheModule.getContext()), ValueList(ValueList),
525         Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
526         getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
527 
528   Error parseMetadata(bool ModuleLevel);
529 
530   bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
531 
532   Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
533     if (ID < MDStringRef.size())
534       return lazyLoadOneMDString(ID);
535     if (auto *MD = MetadataList.lookup(ID))
536       return MD;
537     // If lazy-loading is enabled, we try recursively to load the operand
538     // instead of creating a temporary.
539     if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
540       PlaceholderQueue Placeholders;
541       lazyLoadOneMetadata(ID, Placeholders);
542       resolveForwardRefsAndPlaceholders(Placeholders);
543       return MetadataList.lookup(ID);
544     }
545     return MetadataList.getMetadataFwdRef(ID);
546   }
547 
548   MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
549     return MetadataList.getMDNodeFwdRefOrNull(Idx);
550   }
551 
552   DISubprogram *lookupSubprogramForFunction(Function *F) {
553     return FunctionsWithSPs.lookup(F);
554   }
555 
556   bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
557 
558   Error parseMetadataAttachment(
559       Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
560 
561   Error parseMetadataKinds();
562 
563   void setStripTBAA(bool Value) { StripTBAA = Value; }
564   bool isStrippingTBAA() { return StripTBAA; }
565 
566   unsigned size() const { return MetadataList.size(); }
567   void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
568 };
569 
570 static Error error(const Twine &Message) {
571   return make_error<StringError>(
572       Message, make_error_code(BitcodeError::CorruptedBitcode));
573 }
574 
575 Expected<bool>
576 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
577   IndexCursor = Stream;
578   SmallVector<uint64_t, 64> Record;
579   // Get the abbrevs, and preload record positions to make them lazy-loadable.
580   while (true) {
581     BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
582         BitstreamCursor::AF_DontPopBlockAtEnd);
583     switch (Entry.Kind) {
584     case BitstreamEntry::SubBlock: // Handled for us already.
585     case BitstreamEntry::Error:
586       return error("Malformed block");
587     case BitstreamEntry::EndBlock: {
588       return true;
589     }
590     case BitstreamEntry::Record: {
591       // The interesting case.
592       ++NumMDRecordLoaded;
593       uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
594       auto Code = IndexCursor.skipRecord(Entry.ID);
595       switch (Code) {
596       case bitc::METADATA_STRINGS: {
597         // Rewind and parse the strings.
598         IndexCursor.JumpToBit(CurrentPos);
599         StringRef Blob;
600         Record.clear();
601         IndexCursor.readRecord(Entry.ID, Record, &Blob);
602         unsigned NumStrings = Record[0];
603         MDStringRef.reserve(NumStrings);
604         auto IndexNextMDString = [&](StringRef Str) {
605           MDStringRef.push_back(Str);
606         };
607         if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
608           return std::move(Err);
609         break;
610       }
611       case bitc::METADATA_INDEX_OFFSET: {
612         // This is the offset to the index, when we see this we skip all the
613         // records and load only an index to these.
614         IndexCursor.JumpToBit(CurrentPos);
615         Record.clear();
616         IndexCursor.readRecord(Entry.ID, Record);
617         if (Record.size() != 2)
618           return error("Invalid record");
619         auto Offset = Record[0] + (Record[1] << 32);
620         auto BeginPos = IndexCursor.GetCurrentBitNo();
621         IndexCursor.JumpToBit(BeginPos + Offset);
622         Entry = IndexCursor.advanceSkippingSubblocks(
623             BitstreamCursor::AF_DontPopBlockAtEnd);
624         assert(Entry.Kind == BitstreamEntry::Record &&
625                "Corrupted bitcode: Expected `Record` when trying to find the "
626                "Metadata index");
627         Record.clear();
628         auto Code = IndexCursor.readRecord(Entry.ID, Record);
629         (void)Code;
630         assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
631                                                "`METADATA_INDEX` when trying "
632                                                "to find the Metadata index");
633 
634         // Delta unpack
635         auto CurrentValue = BeginPos;
636         GlobalMetadataBitPosIndex.reserve(Record.size());
637         for (auto &Elt : Record) {
638           CurrentValue += Elt;
639           GlobalMetadataBitPosIndex.push_back(CurrentValue);
640         }
641         break;
642       }
643       case bitc::METADATA_INDEX:
644         // We don't expect to get there, the Index is loaded when we encounter
645         // the offset.
646         return error("Corrupted Metadata block");
647       case bitc::METADATA_NAME: {
648         // Named metadata need to be materialized now and aren't deferred.
649         IndexCursor.JumpToBit(CurrentPos);
650         Record.clear();
651         unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
652         assert(Code == bitc::METADATA_NAME);
653 
654         // Read name of the named metadata.
655         SmallString<8> Name(Record.begin(), Record.end());
656         Code = IndexCursor.ReadCode();
657 
658         // Named Metadata comes in two parts, we expect the name to be followed
659         // by the node
660         Record.clear();
661         unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
662         assert(NextBitCode == bitc::METADATA_NAMED_NODE);
663         (void)NextBitCode;
664 
665         // Read named metadata elements.
666         unsigned Size = Record.size();
667         NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
668         for (unsigned i = 0; i != Size; ++i) {
669           // FIXME: We could use a placeholder here, however NamedMDNode are
670           // taking MDNode as operand and not using the Metadata infrastructure.
671           // It is acknowledged by 'TODO: Inherit from Metadata' in the
672           // NamedMDNode class definition.
673           MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
674           assert(MD && "Invalid record");
675           NMD->addOperand(MD);
676         }
677         break;
678       }
679       case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
680         // FIXME: we need to do this early because we don't materialize global
681         // value explicitly.
682         IndexCursor.JumpToBit(CurrentPos);
683         Record.clear();
684         IndexCursor.readRecord(Entry.ID, Record);
685         if (Record.size() % 2 == 0)
686           return error("Invalid record");
687         unsigned ValueID = Record[0];
688         if (ValueID >= ValueList.size())
689           return error("Invalid record");
690         if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
691           if (Error Err = parseGlobalObjectAttachment(
692                   *GO, ArrayRef<uint64_t>(Record).slice(1)))
693             return std::move(Err);
694         break;
695       }
696       case bitc::METADATA_KIND:
697       case bitc::METADATA_STRING_OLD:
698       case bitc::METADATA_OLD_FN_NODE:
699       case bitc::METADATA_OLD_NODE:
700       case bitc::METADATA_VALUE:
701       case bitc::METADATA_DISTINCT_NODE:
702       case bitc::METADATA_NODE:
703       case bitc::METADATA_LOCATION:
704       case bitc::METADATA_GENERIC_DEBUG:
705       case bitc::METADATA_SUBRANGE:
706       case bitc::METADATA_ENUMERATOR:
707       case bitc::METADATA_BASIC_TYPE:
708       case bitc::METADATA_DERIVED_TYPE:
709       case bitc::METADATA_COMPOSITE_TYPE:
710       case bitc::METADATA_SUBROUTINE_TYPE:
711       case bitc::METADATA_MODULE:
712       case bitc::METADATA_FILE:
713       case bitc::METADATA_COMPILE_UNIT:
714       case bitc::METADATA_SUBPROGRAM:
715       case bitc::METADATA_LEXICAL_BLOCK:
716       case bitc::METADATA_LEXICAL_BLOCK_FILE:
717       case bitc::METADATA_NAMESPACE:
718       case bitc::METADATA_MACRO:
719       case bitc::METADATA_MACRO_FILE:
720       case bitc::METADATA_TEMPLATE_TYPE:
721       case bitc::METADATA_TEMPLATE_VALUE:
722       case bitc::METADATA_GLOBAL_VAR:
723       case bitc::METADATA_LOCAL_VAR:
724       case bitc::METADATA_EXPRESSION:
725       case bitc::METADATA_OBJC_PROPERTY:
726       case bitc::METADATA_IMPORTED_ENTITY:
727       case bitc::METADATA_GLOBAL_VAR_EXPR:
728         // We don't expect to see any of these, if we see one, give up on
729         // lazy-loading and fallback.
730         MDStringRef.clear();
731         GlobalMetadataBitPosIndex.clear();
732         return false;
733       }
734       break;
735     }
736     }
737   }
738 }
739 
740 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
741 /// module level metadata.
742 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
743   if (!ModuleLevel && MetadataList.hasFwdRefs())
744     return error("Invalid metadata: fwd refs into function blocks");
745 
746   // Record the entry position so that we can jump back here and efficiently
747   // skip the whole block in case we lazy-load.
748   auto EntryPos = Stream.GetCurrentBitNo();
749 
750   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
751     return error("Invalid record");
752 
753   SmallVector<uint64_t, 64> Record;
754   PlaceholderQueue Placeholders;
755 
756   // We lazy-load module-level metadata: we build an index for each record, and
757   // then load individual record as needed, starting with the named metadata.
758   if (ModuleLevel && IsImporting && MetadataList.empty() &&
759       !DisableLazyLoading) {
760     auto SuccessOrErr = lazyLoadModuleMetadataBlock();
761     if (!SuccessOrErr)
762       return SuccessOrErr.takeError();
763     if (SuccessOrErr.get()) {
764       // An index was successfully created and we will be able to load metadata
765       // on-demand.
766       MetadataList.resize(MDStringRef.size() +
767                           GlobalMetadataBitPosIndex.size());
768 
769       // Reading the named metadata created forward references and/or
770       // placeholders, that we flush here.
771       resolveForwardRefsAndPlaceholders(Placeholders);
772       upgradeDebugInfo();
773       // Return at the beginning of the block, since it is easy to skip it
774       // entirely from there.
775       Stream.ReadBlockEnd(); // Pop the abbrev block context.
776       Stream.JumpToBit(EntryPos);
777       if (Stream.SkipBlock())
778         return error("Invalid record");
779       return Error::success();
780     }
781     // Couldn't load an index, fallback to loading all the block "old-style".
782   }
783 
784   unsigned NextMetadataNo = MetadataList.size();
785 
786   // Read all the records.
787   while (true) {
788     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
789 
790     switch (Entry.Kind) {
791     case BitstreamEntry::SubBlock: // Handled for us already.
792     case BitstreamEntry::Error:
793       return error("Malformed block");
794     case BitstreamEntry::EndBlock:
795       resolveForwardRefsAndPlaceholders(Placeholders);
796       upgradeDebugInfo();
797       return Error::success();
798     case BitstreamEntry::Record:
799       // The interesting case.
800       break;
801     }
802 
803     // Read a record.
804     Record.clear();
805     StringRef Blob;
806     ++NumMDRecordLoaded;
807     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
808     if (Error Err =
809             parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
810       return Err;
811   }
812 }
813 
814 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
815   ++NumMDStringLoaded;
816   if (Metadata *MD = MetadataList.lookup(ID))
817     return cast<MDString>(MD);
818   auto MDS = MDString::get(Context, MDStringRef[ID]);
819   MetadataList.assignValue(MDS, ID);
820   return MDS;
821 }
822 
823 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
824     unsigned ID, PlaceholderQueue &Placeholders) {
825   assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
826   assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
827   // Lookup first if the metadata hasn't already been loaded.
828   if (auto *MD = MetadataList.lookup(ID)) {
829     auto *N = dyn_cast_or_null<MDNode>(MD);
830     if (!N->isTemporary())
831       return;
832   }
833   SmallVector<uint64_t, 64> Record;
834   StringRef Blob;
835   IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
836   auto Entry = IndexCursor.advanceSkippingSubblocks();
837   ++NumMDRecordLoaded;
838   unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
839   if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
840     report_fatal_error("Can't lazyload MD");
841 }
842 
843 /// Ensure that all forward-references and placeholders are resolved.
844 /// Iteratively lazy-loading metadata on-demand if needed.
845 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
846     PlaceholderQueue &Placeholders) {
847   DenseSet<unsigned> Temporaries;
848   while (1) {
849     // Populate Temporaries with the placeholders that haven't been loaded yet.
850     Placeholders.getTemporaries(MetadataList, Temporaries);
851 
852     // If we don't have any temporary, or FwdReference, we're done!
853     if (Temporaries.empty() && !MetadataList.hasFwdRefs())
854       break;
855 
856     // First, load all the temporaries. This can add new placeholders or
857     // forward references.
858     for (auto ID : Temporaries)
859       lazyLoadOneMetadata(ID, Placeholders);
860     Temporaries.clear();
861 
862     // Second, load the forward-references. This can also add new placeholders
863     // or forward references.
864     while (MetadataList.hasFwdRefs())
865       lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
866   }
867   // At this point we don't have any forward reference remaining, or temporary
868   // that haven't been loaded. We can safely drop RAUW support and mark cycles
869   // as resolved.
870   MetadataList.tryToResolveCycles();
871 
872   // Finally, everything is in place, we can replace the placeholders operands
873   // with the final node they refer to.
874   Placeholders.flush(MetadataList);
875 }
876 
877 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
878     SmallVectorImpl<uint64_t> &Record, unsigned Code,
879     PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
880 
881   bool IsDistinct = false;
882   auto getMD = [&](unsigned ID) -> Metadata * {
883     if (ID < MDStringRef.size())
884       return lazyLoadOneMDString(ID);
885     if (!IsDistinct) {
886       if (auto *MD = MetadataList.lookup(ID))
887         return MD;
888       // If lazy-loading is enabled, we try recursively to load the operand
889       // instead of creating a temporary.
890       if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
891         // Create a temporary for the node that is referencing the operand we
892         // will lazy-load. It is needed before recursing in case there are
893         // uniquing cycles.
894         MetadataList.getMetadataFwdRef(NextMetadataNo);
895         lazyLoadOneMetadata(ID, Placeholders);
896         return MetadataList.lookup(ID);
897       }
898       // Return a temporary.
899       return MetadataList.getMetadataFwdRef(ID);
900     }
901     if (auto *MD = MetadataList.getMetadataIfResolved(ID))
902       return MD;
903     return &Placeholders.getPlaceholderOp(ID);
904   };
905   auto getMDOrNull = [&](unsigned ID) -> Metadata * {
906     if (ID)
907       return getMD(ID - 1);
908     return nullptr;
909   };
910   auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
911     if (ID)
912       return MetadataList.getMetadataFwdRef(ID - 1);
913     return nullptr;
914   };
915   auto getMDString = [&](unsigned ID) -> MDString * {
916     // This requires that the ID is not really a forward reference.  In
917     // particular, the MDString must already have been resolved.
918     auto MDS = getMDOrNull(ID);
919     return cast_or_null<MDString>(MDS);
920   };
921 
922   // Support for old type refs.
923   auto getDITypeRefOrNull = [&](unsigned ID) {
924     return MetadataList.upgradeTypeRef(getMDOrNull(ID));
925   };
926 
927 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
928   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
929 
930   switch (Code) {
931   default: // Default behavior: ignore.
932     break;
933   case bitc::METADATA_NAME: {
934     // Read name of the named metadata.
935     SmallString<8> Name(Record.begin(), Record.end());
936     Record.clear();
937     Code = Stream.ReadCode();
938 
939     ++NumMDRecordLoaded;
940     unsigned NextBitCode = Stream.readRecord(Code, Record);
941     if (NextBitCode != bitc::METADATA_NAMED_NODE)
942       return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
943 
944     // Read named metadata elements.
945     unsigned Size = Record.size();
946     NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
947     for (unsigned i = 0; i != Size; ++i) {
948       MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
949       if (!MD)
950         return error("Invalid record");
951       NMD->addOperand(MD);
952     }
953     break;
954   }
955   case bitc::METADATA_OLD_FN_NODE: {
956     // FIXME: Remove in 4.0.
957     // This is a LocalAsMetadata record, the only type of function-local
958     // metadata.
959     if (Record.size() % 2 == 1)
960       return error("Invalid record");
961 
962     // If this isn't a LocalAsMetadata record, we're dropping it.  This used
963     // to be legal, but there's no upgrade path.
964     auto dropRecord = [&] {
965       MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
966       NextMetadataNo++;
967     };
968     if (Record.size() != 2) {
969       dropRecord();
970       break;
971     }
972 
973     Type *Ty = getTypeByID(Record[0]);
974     if (Ty->isMetadataTy() || Ty->isVoidTy()) {
975       dropRecord();
976       break;
977     }
978 
979     MetadataList.assignValue(
980         LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
981         NextMetadataNo);
982     NextMetadataNo++;
983     break;
984   }
985   case bitc::METADATA_OLD_NODE: {
986     // FIXME: Remove in 4.0.
987     if (Record.size() % 2 == 1)
988       return error("Invalid record");
989 
990     unsigned Size = Record.size();
991     SmallVector<Metadata *, 8> Elts;
992     for (unsigned i = 0; i != Size; i += 2) {
993       Type *Ty = getTypeByID(Record[i]);
994       if (!Ty)
995         return error("Invalid record");
996       if (Ty->isMetadataTy())
997         Elts.push_back(getMD(Record[i + 1]));
998       else if (!Ty->isVoidTy()) {
999         auto *MD =
1000             ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1001         assert(isa<ConstantAsMetadata>(MD) &&
1002                "Expected non-function-local metadata");
1003         Elts.push_back(MD);
1004       } else
1005         Elts.push_back(nullptr);
1006     }
1007     MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
1008     NextMetadataNo++;
1009     break;
1010   }
1011   case bitc::METADATA_VALUE: {
1012     if (Record.size() != 2)
1013       return error("Invalid record");
1014 
1015     Type *Ty = getTypeByID(Record[0]);
1016     if (Ty->isMetadataTy() || Ty->isVoidTy())
1017       return error("Invalid record");
1018 
1019     MetadataList.assignValue(
1020         ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1021         NextMetadataNo);
1022     NextMetadataNo++;
1023     break;
1024   }
1025   case bitc::METADATA_DISTINCT_NODE:
1026     IsDistinct = true;
1027     LLVM_FALLTHROUGH;
1028   case bitc::METADATA_NODE: {
1029     SmallVector<Metadata *, 8> Elts;
1030     Elts.reserve(Record.size());
1031     for (unsigned ID : Record)
1032       Elts.push_back(getMDOrNull(ID));
1033     MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
1034                                         : MDNode::get(Context, Elts),
1035                              NextMetadataNo);
1036     NextMetadataNo++;
1037     break;
1038   }
1039   case bitc::METADATA_LOCATION: {
1040     if (Record.size() != 5)
1041       return error("Invalid record");
1042 
1043     IsDistinct = Record[0];
1044     unsigned Line = Record[1];
1045     unsigned Column = Record[2];
1046     Metadata *Scope = getMD(Record[3]);
1047     Metadata *InlinedAt = getMDOrNull(Record[4]);
1048     MetadataList.assignValue(
1049         GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
1050         NextMetadataNo);
1051     NextMetadataNo++;
1052     break;
1053   }
1054   case bitc::METADATA_GENERIC_DEBUG: {
1055     if (Record.size() < 4)
1056       return error("Invalid record");
1057 
1058     IsDistinct = Record[0];
1059     unsigned Tag = Record[1];
1060     unsigned Version = Record[2];
1061 
1062     if (Tag >= 1u << 16 || Version != 0)
1063       return error("Invalid record");
1064 
1065     auto *Header = getMDString(Record[3]);
1066     SmallVector<Metadata *, 8> DwarfOps;
1067     for (unsigned I = 4, E = Record.size(); I != E; ++I)
1068       DwarfOps.push_back(getMDOrNull(Record[I]));
1069     MetadataList.assignValue(
1070         GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1071         NextMetadataNo);
1072     NextMetadataNo++;
1073     break;
1074   }
1075   case bitc::METADATA_SUBRANGE: {
1076     if (Record.size() != 3)
1077       return error("Invalid record");
1078 
1079     IsDistinct = Record[0];
1080     MetadataList.assignValue(
1081         GET_OR_DISTINCT(DISubrange,
1082                         (Context, Record[1], unrotateSign(Record[2]))),
1083         NextMetadataNo);
1084     NextMetadataNo++;
1085     break;
1086   }
1087   case bitc::METADATA_ENUMERATOR: {
1088     if (Record.size() != 3)
1089       return error("Invalid record");
1090 
1091     IsDistinct = Record[0];
1092     MetadataList.assignValue(
1093         GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1094                                        getMDString(Record[2]))),
1095         NextMetadataNo);
1096     NextMetadataNo++;
1097     break;
1098   }
1099   case bitc::METADATA_BASIC_TYPE: {
1100     if (Record.size() != 6)
1101       return error("Invalid record");
1102 
1103     IsDistinct = Record[0];
1104     MetadataList.assignValue(
1105         GET_OR_DISTINCT(DIBasicType,
1106                         (Context, Record[1], getMDString(Record[2]), Record[3],
1107                          Record[4], Record[5])),
1108         NextMetadataNo);
1109     NextMetadataNo++;
1110     break;
1111   }
1112   case bitc::METADATA_DERIVED_TYPE: {
1113     if (Record.size() != 12)
1114       return error("Invalid record");
1115 
1116     IsDistinct = Record[0];
1117     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1118     MetadataList.assignValue(
1119         GET_OR_DISTINCT(DIDerivedType,
1120                         (Context, Record[1], getMDString(Record[2]),
1121                          getMDOrNull(Record[3]), Record[4],
1122                          getDITypeRefOrNull(Record[5]),
1123                          getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1124                          Record[9], Flags, getDITypeRefOrNull(Record[11]))),
1125         NextMetadataNo);
1126     NextMetadataNo++;
1127     break;
1128   }
1129   case bitc::METADATA_COMPOSITE_TYPE: {
1130     if (Record.size() != 16)
1131       return error("Invalid record");
1132 
1133     // If we have a UUID and this is not a forward declaration, lookup the
1134     // mapping.
1135     IsDistinct = Record[0] & 0x1;
1136     bool IsNotUsedInTypeRef = Record[0] >= 2;
1137     unsigned Tag = Record[1];
1138     MDString *Name = getMDString(Record[2]);
1139     Metadata *File = getMDOrNull(Record[3]);
1140     unsigned Line = Record[4];
1141     Metadata *Scope = getDITypeRefOrNull(Record[5]);
1142     Metadata *BaseType = nullptr;
1143     uint64_t SizeInBits = Record[7];
1144     if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1145       return error("Alignment value is too large");
1146     uint32_t AlignInBits = Record[8];
1147     uint64_t OffsetInBits = 0;
1148     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1149     Metadata *Elements = nullptr;
1150     unsigned RuntimeLang = Record[12];
1151     Metadata *VTableHolder = nullptr;
1152     Metadata *TemplateParams = nullptr;
1153     auto *Identifier = getMDString(Record[15]);
1154     // If this module is being parsed so that it can be ThinLTO imported
1155     // into another module, composite types only need to be imported
1156     // as type declarations (unless full type definitions requested).
1157     // Create type declarations up front to save memory. Also, buildODRType
1158     // handles the case where this is type ODRed with a definition needed
1159     // by the importing module, in which case the existing definition is
1160     // used.
1161     if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1162         (Tag == dwarf::DW_TAG_enumeration_type ||
1163          Tag == dwarf::DW_TAG_class_type ||
1164          Tag == dwarf::DW_TAG_structure_type ||
1165          Tag == dwarf::DW_TAG_union_type)) {
1166       Flags = Flags | DINode::FlagFwdDecl;
1167     } else {
1168       BaseType = getDITypeRefOrNull(Record[6]);
1169       OffsetInBits = Record[9];
1170       Elements = getMDOrNull(Record[11]);
1171       VTableHolder = getDITypeRefOrNull(Record[13]);
1172       TemplateParams = getMDOrNull(Record[14]);
1173     }
1174     DICompositeType *CT = nullptr;
1175     if (Identifier)
1176       CT = DICompositeType::buildODRType(
1177           Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1178           SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1179           VTableHolder, TemplateParams);
1180 
1181     // Create a node if we didn't get a lazy ODR type.
1182     if (!CT)
1183       CT = GET_OR_DISTINCT(DICompositeType,
1184                            (Context, Tag, Name, File, Line, Scope, BaseType,
1185                             SizeInBits, AlignInBits, OffsetInBits, Flags,
1186                             Elements, RuntimeLang, VTableHolder, TemplateParams,
1187                             Identifier));
1188     if (!IsNotUsedInTypeRef && Identifier)
1189       MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1190 
1191     MetadataList.assignValue(CT, NextMetadataNo);
1192     NextMetadataNo++;
1193     break;
1194   }
1195   case bitc::METADATA_SUBROUTINE_TYPE: {
1196     if (Record.size() < 3 || Record.size() > 4)
1197       return error("Invalid record");
1198     bool IsOldTypeRefArray = Record[0] < 2;
1199     unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1200 
1201     IsDistinct = Record[0] & 0x1;
1202     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1203     Metadata *Types = getMDOrNull(Record[2]);
1204     if (LLVM_UNLIKELY(IsOldTypeRefArray))
1205       Types = MetadataList.upgradeTypeRefArray(Types);
1206 
1207     MetadataList.assignValue(
1208         GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1209         NextMetadataNo);
1210     NextMetadataNo++;
1211     break;
1212   }
1213 
1214   case bitc::METADATA_MODULE: {
1215     if (Record.size() != 6)
1216       return error("Invalid record");
1217 
1218     IsDistinct = Record[0];
1219     MetadataList.assignValue(
1220         GET_OR_DISTINCT(DIModule,
1221                         (Context, getMDOrNull(Record[1]),
1222                          getMDString(Record[2]), getMDString(Record[3]),
1223                          getMDString(Record[4]), getMDString(Record[5]))),
1224         NextMetadataNo);
1225     NextMetadataNo++;
1226     break;
1227   }
1228 
1229   case bitc::METADATA_FILE: {
1230     if (Record.size() != 3 && Record.size() != 5)
1231       return error("Invalid record");
1232 
1233     IsDistinct = Record[0];
1234     MetadataList.assignValue(
1235         GET_OR_DISTINCT(
1236             DIFile,
1237             (Context, getMDString(Record[1]), getMDString(Record[2]),
1238              Record.size() == 3 ? DIFile::CSK_None
1239                                 : static_cast<DIFile::ChecksumKind>(Record[3]),
1240              Record.size() == 3 ? nullptr : getMDString(Record[4]))),
1241         NextMetadataNo);
1242     NextMetadataNo++;
1243     break;
1244   }
1245   case bitc::METADATA_COMPILE_UNIT: {
1246     if (Record.size() < 14 || Record.size() > 18)
1247       return error("Invalid record");
1248 
1249     // Ignore Record[0], which indicates whether this compile unit is
1250     // distinct.  It's always distinct.
1251     IsDistinct = true;
1252     auto *CU = DICompileUnit::getDistinct(
1253         Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1254         Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1255         Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1256         getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1257         Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1258         Record.size() <= 14 ? 0 : Record[14],
1259         Record.size() <= 16 ? true : Record[16],
1260         Record.size() <= 17 ? false : Record[17]);
1261 
1262     MetadataList.assignValue(CU, NextMetadataNo);
1263     NextMetadataNo++;
1264 
1265     // Move the Upgrade the list of subprograms.
1266     if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1267       CUSubprograms.push_back({CU, SPs});
1268     break;
1269   }
1270   case bitc::METADATA_SUBPROGRAM: {
1271     if (Record.size() < 18 || Record.size() > 20)
1272       return error("Invalid record");
1273 
1274     IsDistinct =
1275         (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1276     // Version 1 has a Function as Record[15].
1277     // Version 2 has removed Record[15].
1278     // Version 3 has the Unit as Record[15].
1279     // Version 4 added thisAdjustment.
1280     bool HasUnit = Record[0] >= 2;
1281     if (HasUnit && Record.size() < 19)
1282       return error("Invalid record");
1283     Metadata *CUorFn = getMDOrNull(Record[15]);
1284     unsigned Offset = Record.size() >= 19 ? 1 : 0;
1285     bool HasFn = Offset && !HasUnit;
1286     bool HasThisAdj = Record.size() >= 20;
1287     DISubprogram *SP = GET_OR_DISTINCT(
1288         DISubprogram, (Context,
1289                        getDITypeRefOrNull(Record[1]),          // scope
1290                        getMDString(Record[2]),                 // name
1291                        getMDString(Record[3]),                 // linkageName
1292                        getMDOrNull(Record[4]),                 // file
1293                        Record[5],                              // line
1294                        getMDOrNull(Record[6]),                 // type
1295                        Record[7],                              // isLocal
1296                        Record[8],                              // isDefinition
1297                        Record[9],                              // scopeLine
1298                        getDITypeRefOrNull(Record[10]),         // containingType
1299                        Record[11],                             // virtuality
1300                        Record[12],                             // virtualIndex
1301                        HasThisAdj ? Record[19] : 0,            // thisAdjustment
1302                        static_cast<DINode::DIFlags>(Record[13] // flags
1303                                                     ),
1304                        Record[14],                       // isOptimized
1305                        HasUnit ? CUorFn : nullptr,       // unit
1306                        getMDOrNull(Record[15 + Offset]), // templateParams
1307                        getMDOrNull(Record[16 + Offset]), // declaration
1308                        getMDOrNull(Record[17 + Offset])  // variables
1309                        ));
1310     MetadataList.assignValue(SP, NextMetadataNo);
1311     NextMetadataNo++;
1312 
1313     // Upgrade sp->function mapping to function->sp mapping.
1314     if (HasFn) {
1315       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1316         if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1317           if (F->isMaterializable())
1318             // Defer until materialized; unmaterialized functions may not have
1319             // metadata.
1320             FunctionsWithSPs[F] = SP;
1321           else if (!F->empty())
1322             F->setSubprogram(SP);
1323         }
1324     }
1325     break;
1326   }
1327   case bitc::METADATA_LEXICAL_BLOCK: {
1328     if (Record.size() != 5)
1329       return error("Invalid record");
1330 
1331     IsDistinct = Record[0];
1332     MetadataList.assignValue(
1333         GET_OR_DISTINCT(DILexicalBlock,
1334                         (Context, getMDOrNull(Record[1]),
1335                          getMDOrNull(Record[2]), Record[3], Record[4])),
1336         NextMetadataNo);
1337     NextMetadataNo++;
1338     break;
1339   }
1340   case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1341     if (Record.size() != 4)
1342       return error("Invalid record");
1343 
1344     IsDistinct = Record[0];
1345     MetadataList.assignValue(
1346         GET_OR_DISTINCT(DILexicalBlockFile,
1347                         (Context, getMDOrNull(Record[1]),
1348                          getMDOrNull(Record[2]), Record[3])),
1349         NextMetadataNo);
1350     NextMetadataNo++;
1351     break;
1352   }
1353   case bitc::METADATA_NAMESPACE: {
1354     if (Record.size() != 5)
1355       return error("Invalid record");
1356 
1357     IsDistinct = Record[0] & 1;
1358     bool ExportSymbols = Record[0] & 2;
1359     MetadataList.assignValue(
1360         GET_OR_DISTINCT(DINamespace,
1361                         (Context, getMDOrNull(Record[1]),
1362                          getMDOrNull(Record[2]), getMDString(Record[3]),
1363                          Record[4], ExportSymbols)),
1364         NextMetadataNo);
1365     NextMetadataNo++;
1366     break;
1367   }
1368   case bitc::METADATA_MACRO: {
1369     if (Record.size() != 5)
1370       return error("Invalid record");
1371 
1372     IsDistinct = Record[0];
1373     MetadataList.assignValue(
1374         GET_OR_DISTINCT(DIMacro,
1375                         (Context, Record[1], Record[2], getMDString(Record[3]),
1376                          getMDString(Record[4]))),
1377         NextMetadataNo);
1378     NextMetadataNo++;
1379     break;
1380   }
1381   case bitc::METADATA_MACRO_FILE: {
1382     if (Record.size() != 5)
1383       return error("Invalid record");
1384 
1385     IsDistinct = Record[0];
1386     MetadataList.assignValue(
1387         GET_OR_DISTINCT(DIMacroFile,
1388                         (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1389                          getMDOrNull(Record[4]))),
1390         NextMetadataNo);
1391     NextMetadataNo++;
1392     break;
1393   }
1394   case bitc::METADATA_TEMPLATE_TYPE: {
1395     if (Record.size() != 3)
1396       return error("Invalid record");
1397 
1398     IsDistinct = Record[0];
1399     MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1400                                              (Context, getMDString(Record[1]),
1401                                               getDITypeRefOrNull(Record[2]))),
1402                              NextMetadataNo);
1403     NextMetadataNo++;
1404     break;
1405   }
1406   case bitc::METADATA_TEMPLATE_VALUE: {
1407     if (Record.size() != 5)
1408       return error("Invalid record");
1409 
1410     IsDistinct = Record[0];
1411     MetadataList.assignValue(
1412         GET_OR_DISTINCT(DITemplateValueParameter,
1413                         (Context, Record[1], getMDString(Record[2]),
1414                          getDITypeRefOrNull(Record[3]),
1415                          getMDOrNull(Record[4]))),
1416         NextMetadataNo);
1417     NextMetadataNo++;
1418     break;
1419   }
1420   case bitc::METADATA_GLOBAL_VAR: {
1421     if (Record.size() < 11 || Record.size() > 12)
1422       return error("Invalid record");
1423 
1424     IsDistinct = Record[0] & 1;
1425     unsigned Version = Record[0] >> 1;
1426 
1427     if (Version == 1) {
1428       MetadataList.assignValue(
1429           GET_OR_DISTINCT(DIGlobalVariable,
1430                           (Context, getMDOrNull(Record[1]),
1431                            getMDString(Record[2]), getMDString(Record[3]),
1432                            getMDOrNull(Record[4]), Record[5],
1433                            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1434                            getMDOrNull(Record[10]), Record[11])),
1435           NextMetadataNo);
1436       NextMetadataNo++;
1437     } else if (Version == 0) {
1438       // Upgrade old metadata, which stored a global variable reference or a
1439       // ConstantInt here.
1440       NeedUpgradeToDIGlobalVariableExpression = true;
1441       Metadata *Expr = getMDOrNull(Record[9]);
1442       uint32_t AlignInBits = 0;
1443       if (Record.size() > 11) {
1444         if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1445           return error("Alignment value is too large");
1446         AlignInBits = Record[11];
1447       }
1448       GlobalVariable *Attach = nullptr;
1449       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1450         if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1451           Attach = GV;
1452           Expr = nullptr;
1453         } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1454           Expr = DIExpression::get(Context,
1455                                    {dwarf::DW_OP_constu, CI->getZExtValue(),
1456                                     dwarf::DW_OP_stack_value});
1457         } else {
1458           Expr = nullptr;
1459         }
1460       }
1461       DIGlobalVariable *DGV = GET_OR_DISTINCT(
1462           DIGlobalVariable,
1463           (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1464            getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1465            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1466            getMDOrNull(Record[10]), AlignInBits));
1467 
1468       DIGlobalVariableExpression *DGVE = nullptr;
1469       if (Attach || Expr)
1470         DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1471       if (Attach)
1472         Attach->addDebugInfo(DGVE);
1473 
1474       auto *MDNode = Expr ? cast<Metadata>(DGVE) : cast<Metadata>(DGV);
1475       MetadataList.assignValue(MDNode, NextMetadataNo);
1476       NextMetadataNo++;
1477     } else
1478       return error("Invalid record");
1479 
1480     break;
1481   }
1482   case bitc::METADATA_LOCAL_VAR: {
1483     // 10th field is for the obseleted 'inlinedAt:' field.
1484     if (Record.size() < 8 || Record.size() > 10)
1485       return error("Invalid record");
1486 
1487     IsDistinct = Record[0] & 1;
1488     bool HasAlignment = Record[0] & 2;
1489     // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1490     // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1491     // this is newer version of record which doesn't have artifical tag.
1492     bool HasTag = !HasAlignment && Record.size() > 8;
1493     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1494     uint32_t AlignInBits = 0;
1495     if (HasAlignment) {
1496       if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1497         return error("Alignment value is too large");
1498       AlignInBits = Record[8 + HasTag];
1499     }
1500     MetadataList.assignValue(
1501         GET_OR_DISTINCT(DILocalVariable,
1502                         (Context, getMDOrNull(Record[1 + HasTag]),
1503                          getMDString(Record[2 + HasTag]),
1504                          getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1505                          getDITypeRefOrNull(Record[5 + HasTag]),
1506                          Record[6 + HasTag], Flags, AlignInBits)),
1507         NextMetadataNo);
1508     NextMetadataNo++;
1509     break;
1510   }
1511   case bitc::METADATA_EXPRESSION: {
1512     if (Record.size() < 1)
1513       return error("Invalid record");
1514 
1515     IsDistinct = Record[0] & 1;
1516     bool HasOpFragment = Record[0] & 2;
1517     auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1518     if (!HasOpFragment)
1519       if (unsigned N = Elts.size())
1520         if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
1521           Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
1522 
1523     MetadataList.assignValue(
1524         GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
1525         NextMetadataNo);
1526     NextMetadataNo++;
1527     break;
1528   }
1529   case bitc::METADATA_GLOBAL_VAR_EXPR: {
1530     if (Record.size() != 3)
1531       return error("Invalid record");
1532 
1533     IsDistinct = Record[0];
1534     MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1535                                              (Context, getMDOrNull(Record[1]),
1536                                               getMDOrNull(Record[2]))),
1537                              NextMetadataNo);
1538     NextMetadataNo++;
1539     break;
1540   }
1541   case bitc::METADATA_OBJC_PROPERTY: {
1542     if (Record.size() != 8)
1543       return error("Invalid record");
1544 
1545     IsDistinct = Record[0];
1546     MetadataList.assignValue(
1547         GET_OR_DISTINCT(DIObjCProperty,
1548                         (Context, getMDString(Record[1]),
1549                          getMDOrNull(Record[2]), Record[3],
1550                          getMDString(Record[4]), getMDString(Record[5]),
1551                          Record[6], getDITypeRefOrNull(Record[7]))),
1552         NextMetadataNo);
1553     NextMetadataNo++;
1554     break;
1555   }
1556   case bitc::METADATA_IMPORTED_ENTITY: {
1557     if (Record.size() != 6)
1558       return error("Invalid record");
1559 
1560     IsDistinct = Record[0];
1561     MetadataList.assignValue(
1562         GET_OR_DISTINCT(DIImportedEntity,
1563                         (Context, Record[1], getMDOrNull(Record[2]),
1564                          getDITypeRefOrNull(Record[3]), Record[4],
1565                          getMDString(Record[5]))),
1566         NextMetadataNo);
1567     NextMetadataNo++;
1568     break;
1569   }
1570   case bitc::METADATA_STRING_OLD: {
1571     std::string String(Record.begin(), Record.end());
1572 
1573     // Test for upgrading !llvm.loop.
1574     HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
1575     ++NumMDStringLoaded;
1576     Metadata *MD = MDString::get(Context, String);
1577     MetadataList.assignValue(MD, NextMetadataNo);
1578     NextMetadataNo++;
1579     break;
1580   }
1581   case bitc::METADATA_STRINGS: {
1582     auto CreateNextMDString = [&](StringRef Str) {
1583       ++NumMDStringLoaded;
1584       MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
1585       NextMetadataNo++;
1586     };
1587     if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
1588       return Err;
1589     break;
1590   }
1591   case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1592     if (Record.size() % 2 == 0)
1593       return error("Invalid record");
1594     unsigned ValueID = Record[0];
1595     if (ValueID >= ValueList.size())
1596       return error("Invalid record");
1597     if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1598       if (Error Err = parseGlobalObjectAttachment(
1599               *GO, ArrayRef<uint64_t>(Record).slice(1)))
1600         return Err;
1601     break;
1602   }
1603   case bitc::METADATA_KIND: {
1604     // Support older bitcode files that had METADATA_KIND records in a
1605     // block with METADATA_BLOCK_ID.
1606     if (Error Err = parseMetadataKindRecord(Record))
1607       return Err;
1608     break;
1609   }
1610   }
1611   return Error::success();
1612 #undef GET_OR_DISTINCT
1613 }
1614 
1615 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1616     ArrayRef<uint64_t> Record, StringRef Blob,
1617     function_ref<void(StringRef)> CallBack) {
1618   // All the MDStrings in the block are emitted together in a single
1619   // record.  The strings are concatenated and stored in a blob along with
1620   // their sizes.
1621   if (Record.size() != 2)
1622     return error("Invalid record: metadata strings layout");
1623 
1624   unsigned NumStrings = Record[0];
1625   unsigned StringsOffset = Record[1];
1626   if (!NumStrings)
1627     return error("Invalid record: metadata strings with no strings");
1628   if (StringsOffset > Blob.size())
1629     return error("Invalid record: metadata strings corrupt offset");
1630 
1631   StringRef Lengths = Blob.slice(0, StringsOffset);
1632   SimpleBitstreamCursor R(Lengths);
1633 
1634   StringRef Strings = Blob.drop_front(StringsOffset);
1635   do {
1636     if (R.AtEndOfStream())
1637       return error("Invalid record: metadata strings bad length");
1638 
1639     unsigned Size = R.ReadVBR(6);
1640     if (Strings.size() < Size)
1641       return error("Invalid record: metadata strings truncated chars");
1642 
1643     CallBack(Strings.slice(0, Size));
1644     Strings = Strings.drop_front(Size);
1645   } while (--NumStrings);
1646 
1647   return Error::success();
1648 }
1649 
1650 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1651     GlobalObject &GO, ArrayRef<uint64_t> Record) {
1652   assert(Record.size() % 2 == 0);
1653   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1654     auto K = MDKindMap.find(Record[I]);
1655     if (K == MDKindMap.end())
1656       return error("Invalid ID");
1657     MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1658     if (!MD)
1659       return error("Invalid metadata attachment");
1660     GO.addMetadata(K->second, *MD);
1661   }
1662   return Error::success();
1663 }
1664 
1665 /// Parse metadata attachments.
1666 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1667     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1668   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1669     return error("Invalid record");
1670 
1671   SmallVector<uint64_t, 64> Record;
1672   PlaceholderQueue Placeholders;
1673 
1674   while (true) {
1675     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1676 
1677     switch (Entry.Kind) {
1678     case BitstreamEntry::SubBlock: // Handled for us already.
1679     case BitstreamEntry::Error:
1680       return error("Malformed block");
1681     case BitstreamEntry::EndBlock:
1682       resolveForwardRefsAndPlaceholders(Placeholders);
1683       return Error::success();
1684     case BitstreamEntry::Record:
1685       // The interesting case.
1686       break;
1687     }
1688 
1689     // Read a metadata attachment record.
1690     Record.clear();
1691     ++NumMDRecordLoaded;
1692     switch (Stream.readRecord(Entry.ID, Record)) {
1693     default: // Default behavior: ignore.
1694       break;
1695     case bitc::METADATA_ATTACHMENT: {
1696       unsigned RecordLength = Record.size();
1697       if (Record.empty())
1698         return error("Invalid record");
1699       if (RecordLength % 2 == 0) {
1700         // A function attachment.
1701         if (Error Err = parseGlobalObjectAttachment(F, Record))
1702           return Err;
1703         continue;
1704       }
1705 
1706       // An instruction attachment.
1707       Instruction *Inst = InstructionList[Record[0]];
1708       for (unsigned i = 1; i != RecordLength; i = i + 2) {
1709         unsigned Kind = Record[i];
1710         DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1711         if (I == MDKindMap.end())
1712           return error("Invalid ID");
1713         if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1714           continue;
1715 
1716         auto Idx = Record[i + 1];
1717         if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
1718             !MetadataList.lookup(Idx)) {
1719           // Load the attachment if it is in the lazy-loadable range and hasn't
1720           // been loaded yet.
1721           lazyLoadOneMetadata(Idx, Placeholders);
1722           resolveForwardRefsAndPlaceholders(Placeholders);
1723         }
1724 
1725         Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
1726         if (isa<LocalAsMetadata>(Node))
1727           // Drop the attachment.  This used to be legal, but there's no
1728           // upgrade path.
1729           break;
1730         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1731         if (!MD)
1732           return error("Invalid metadata attachment");
1733 
1734         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1735           MD = upgradeInstructionLoopAttachment(*MD);
1736 
1737         if (I->second == LLVMContext::MD_tbaa) {
1738           assert(!MD->isTemporary() && "should load MDs before attachments");
1739           MD = UpgradeTBAANode(*MD);
1740         }
1741         Inst->setMetadata(I->second, MD);
1742       }
1743       break;
1744     }
1745     }
1746   }
1747 }
1748 
1749 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1750 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1751     SmallVectorImpl<uint64_t> &Record) {
1752   if (Record.size() < 2)
1753     return error("Invalid record");
1754 
1755   unsigned Kind = Record[0];
1756   SmallString<8> Name(Record.begin() + 1, Record.end());
1757 
1758   unsigned NewKind = TheModule.getMDKindID(Name.str());
1759   if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1760     return error("Conflicting METADATA_KIND records");
1761   return Error::success();
1762 }
1763 
1764 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1765 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1766   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1767     return error("Invalid record");
1768 
1769   SmallVector<uint64_t, 64> Record;
1770 
1771   // Read all the records.
1772   while (true) {
1773     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1774 
1775     switch (Entry.Kind) {
1776     case BitstreamEntry::SubBlock: // Handled for us already.
1777     case BitstreamEntry::Error:
1778       return error("Malformed block");
1779     case BitstreamEntry::EndBlock:
1780       return Error::success();
1781     case BitstreamEntry::Record:
1782       // The interesting case.
1783       break;
1784     }
1785 
1786     // Read a record.
1787     Record.clear();
1788     ++NumMDRecordLoaded;
1789     unsigned Code = Stream.readRecord(Entry.ID, Record);
1790     switch (Code) {
1791     default: // Default behavior: ignore.
1792       break;
1793     case bitc::METADATA_KIND: {
1794       if (Error Err = parseMetadataKindRecord(Record))
1795         return Err;
1796       break;
1797     }
1798     }
1799   }
1800 }
1801 
1802 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1803   Pimpl = std::move(RHS.Pimpl);
1804   return *this;
1805 }
1806 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
1807     : Pimpl(std::move(RHS.Pimpl)) {}
1808 
1809 MetadataLoader::~MetadataLoader() = default;
1810 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1811                                BitcodeReaderValueList &ValueList,
1812                                bool IsImporting,
1813                                std::function<Type *(unsigned)> getTypeByID)
1814     : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
1815           Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
1816 
1817 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
1818   return Pimpl->parseMetadata(ModuleLevel);
1819 }
1820 
1821 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1822 
1823 /// Return the given metadata, creating a replaceable forward reference if
1824 /// necessary.
1825 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
1826   return Pimpl->getMetadataFwdRefOrLoad(Idx);
1827 }
1828 
1829 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1830   return Pimpl->getMDNodeFwdRefOrNull(Idx);
1831 }
1832 
1833 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1834   return Pimpl->lookupSubprogramForFunction(F);
1835 }
1836 
1837 Error MetadataLoader::parseMetadataAttachment(
1838     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1839   return Pimpl->parseMetadataAttachment(F, InstructionList);
1840 }
1841 
1842 Error MetadataLoader::parseMetadataKinds() {
1843   return Pimpl->parseMetadataKinds();
1844 }
1845 
1846 void MetadataLoader::setStripTBAA(bool StripTBAA) {
1847   return Pimpl->setStripTBAA(StripTBAA);
1848 }
1849 
1850 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1851 
1852 unsigned MetadataLoader::size() const { return Pimpl->size(); }
1853 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
1854