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