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   bool empty() { return PHs.empty(); }
362   DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
363   void flush(BitcodeReaderMetadataList &MetadataList);
364 
365   /// Return the list of temporaries nodes in the queue, these need to be
366   /// loaded before we can flush the queue.
367   void getTemporaries(BitcodeReaderMetadataList &MetadataList,
368                       DenseSet<unsigned> &Temporaries) {
369     for (auto &PH : PHs) {
370       auto ID = PH.getID();
371       auto *MD = MetadataList.lookup(ID);
372       if (!MD) {
373         Temporaries.insert(ID);
374         continue;
375       }
376       auto *N = dyn_cast_or_null<MDNode>(MD);
377       if (N && N->isTemporary())
378         Temporaries.insert(ID);
379     }
380   }
381 };
382 
383 } // end anonymous namespace
384 
385 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
386   PHs.emplace_back(ID);
387   return PHs.back();
388 }
389 
390 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
391   while (!PHs.empty()) {
392     auto *MD = MetadataList.lookup(PHs.front().getID());
393     assert(MD && "Flushing placeholder on unassigned MD");
394 #ifndef NDEBUG
395     if (auto *MDN = dyn_cast<MDNode>(MD))
396       assert(MDN->isResolved() &&
397              "Flushing Placeholder while cycles aren't resolved");
398 #endif
399     PHs.front().replaceUseWith(MD);
400     PHs.pop_front();
401   }
402 }
403 
404 } // anonynous namespace
405 
406 class MetadataLoader::MetadataLoaderImpl {
407   BitcodeReaderMetadataList MetadataList;
408   BitcodeReaderValueList &ValueList;
409   BitstreamCursor &Stream;
410   LLVMContext &Context;
411   Module &TheModule;
412   std::function<Type *(unsigned)> getTypeByID;
413 
414   /// Cursor associated with the lazy-loading of Metadata. This is the easy way
415   /// to keep around the right "context" (Abbrev list) to be able to jump in
416   /// the middle of the metadata block and load any record.
417   BitstreamCursor IndexCursor;
418 
419   /// Index that keeps track of MDString values.
420   std::vector<StringRef> MDStringRef;
421 
422   /// On-demand loading of a single MDString. Requires the index above to be
423   /// populated.
424   MDString *lazyLoadOneMDString(unsigned Idx);
425 
426   /// Index that keeps track of where to find a metadata record in the stream.
427   std::vector<uint64_t> GlobalMetadataBitPosIndex;
428 
429   /// Populate the index above to enable lazily loading of metadata, and load
430   /// the named metadata as well as the transitively referenced global
431   /// Metadata.
432   Expected<bool> lazyLoadModuleMetadataBlock();
433 
434   /// On-demand loading of a single metadata. Requires the index above to be
435   /// populated.
436   void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
437 
438   // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
439   // point from SP to CU after a block is completly parsed.
440   std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
441 
442   /// Functions that need to be matched with subprograms when upgrading old
443   /// metadata.
444   SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
445 
446   // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
447   DenseMap<unsigned, unsigned> MDKindMap;
448 
449   bool StripTBAA = false;
450   bool HasSeenOldLoopTags = false;
451 
452   /// True if metadata is being parsed for a module being ThinLTO imported.
453   bool IsImporting = false;
454 
455   Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
456                          PlaceholderQueue &Placeholders, StringRef Blob,
457                          unsigned &NextMetadataNo);
458   Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
459                              function_ref<void(StringRef)> CallBack);
460   Error parseGlobalObjectAttachment(GlobalObject &GO,
461                                     ArrayRef<uint64_t> Record);
462   Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
463 
464   void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
465 
466   /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
467   void upgradeCUSubprograms() {
468     for (auto CU_SP : CUSubprograms)
469       if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
470         for (auto &Op : SPs->operands())
471           if (auto *SP = dyn_cast_or_null<MDNode>(Op))
472             SP->replaceOperandWith(7, CU_SP.first);
473     CUSubprograms.clear();
474   }
475 
476 public:
477   MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
478                      BitcodeReaderValueList &ValueList,
479                      std::function<Type *(unsigned)> getTypeByID,
480                      bool IsImporting)
481       : MetadataList(TheModule.getContext()), ValueList(ValueList),
482         Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
483         getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
484 
485   Error parseMetadata(bool ModuleLevel);
486 
487   bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
488   Metadata *getMetadataFwdRef(unsigned Idx) {
489     return MetadataList.getMetadataFwdRef(Idx);
490   }
491 
492   MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
493     return MetadataList.getMDNodeFwdRefOrNull(Idx);
494   }
495 
496   DISubprogram *lookupSubprogramForFunction(Function *F) {
497     return FunctionsWithSPs.lookup(F);
498   }
499 
500   bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
501 
502   Error parseMetadataAttachment(
503       Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
504 
505   Error parseMetadataKinds();
506 
507   void setStripTBAA(bool Value) { StripTBAA = Value; }
508   bool isStrippingTBAA() { return StripTBAA; }
509 
510   unsigned size() const { return MetadataList.size(); }
511   void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
512 };
513 
514 Error error(const Twine &Message) {
515   return make_error<StringError>(
516       Message, make_error_code(BitcodeError::CorruptedBitcode));
517 }
518 
519 Expected<bool>
520 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
521   IndexCursor = Stream;
522   SmallVector<uint64_t, 64> Record;
523   // Get the abbrevs, and preload record positions to make them lazy-loadable.
524   while (true) {
525     BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
526         BitstreamCursor::AF_DontPopBlockAtEnd);
527     switch (Entry.Kind) {
528     case BitstreamEntry::SubBlock: // Handled for us already.
529     case BitstreamEntry::Error:
530       return error("Malformed block");
531     case BitstreamEntry::EndBlock: {
532       return true;
533     }
534     case BitstreamEntry::Record: {
535       // The interesting case.
536       ++NumMDRecordLoaded;
537       uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
538       auto Code = IndexCursor.skipRecord(Entry.ID);
539       switch (Code) {
540       case bitc::METADATA_STRINGS: {
541         // Rewind and parse the strings.
542         IndexCursor.JumpToBit(CurrentPos);
543         StringRef Blob;
544         Record.clear();
545         IndexCursor.readRecord(Entry.ID, Record, &Blob);
546         unsigned NumStrings = Record[0];
547         MDStringRef.reserve(NumStrings);
548         auto IndexNextMDString = [&](StringRef Str) {
549           MDStringRef.push_back(Str);
550         };
551         if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
552           return std::move(Err);
553         break;
554       }
555       case bitc::METADATA_INDEX_OFFSET: {
556         // This is the offset to the index, when we see this we skip all the
557         // records and load only an index to these.
558         IndexCursor.JumpToBit(CurrentPos);
559         Record.clear();
560         IndexCursor.readRecord(Entry.ID, Record);
561         if (Record.size() != 2)
562           return error("Invalid record");
563         auto Offset = Record[0] + (Record[1] << 32);
564         auto BeginPos = IndexCursor.GetCurrentBitNo();
565         IndexCursor.JumpToBit(BeginPos + Offset);
566         Entry = IndexCursor.advanceSkippingSubblocks(
567             BitstreamCursor::AF_DontPopBlockAtEnd);
568         assert(Entry.Kind == BitstreamEntry::Record &&
569                "Corrupted bitcode: Expected `Record` when trying to find the "
570                "Metadata index");
571         Record.clear();
572         auto Code = IndexCursor.readRecord(Entry.ID, Record);
573         (void)Code;
574         assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
575                                                "`METADATA_INDEX` when trying "
576                                                "to find the Metadata index");
577 
578         // Delta unpack
579         auto CurrentValue = BeginPos;
580         GlobalMetadataBitPosIndex.reserve(Record.size());
581         for (auto &Elt : Record) {
582           CurrentValue += Elt;
583           GlobalMetadataBitPosIndex.push_back(CurrentValue);
584         }
585         break;
586       }
587       case bitc::METADATA_INDEX:
588         // We don't expect to get there, the Index is loaded when we encounter
589         // the offset.
590         return error("Corrupted Metadata block");
591       case bitc::METADATA_NAME: {
592         // Named metadata need to be materialized now and aren't deferred.
593         IndexCursor.JumpToBit(CurrentPos);
594         Record.clear();
595         unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
596         assert(Code == bitc::METADATA_NAME);
597 
598         // Read name of the named metadata.
599         SmallString<8> Name(Record.begin(), Record.end());
600         Code = IndexCursor.ReadCode();
601 
602         // Named Metadata comes in two parts, we expect the name to be followed
603         // by the node
604         Record.clear();
605         unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
606         assert(NextBitCode == bitc::METADATA_NAMED_NODE);
607         (void)NextBitCode;
608 
609         // Read named metadata elements.
610         unsigned Size = Record.size();
611         NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
612         for (unsigned i = 0; i != Size; ++i) {
613           // FIXME: We could use a placeholder here, however NamedMDNode are
614           // taking MDNode as operand and not using the Metadata infrastructure.
615           // It is acknowledged by 'TODO: Inherit from Metadata' in the
616           // NamedMDNode class definition.
617           MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
618           assert(MD && "Invalid record");
619           NMD->addOperand(MD);
620         }
621         break;
622       }
623       case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
624         // FIXME: we need to do this early because we don't materialize global
625         // value explicitly.
626         IndexCursor.JumpToBit(CurrentPos);
627         Record.clear();
628         IndexCursor.readRecord(Entry.ID, Record);
629         if (Record.size() % 2 == 0)
630           return error("Invalid record");
631         unsigned ValueID = Record[0];
632         if (ValueID >= ValueList.size())
633           return error("Invalid record");
634         if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
635           if (Error Err = parseGlobalObjectAttachment(
636                   *GO, ArrayRef<uint64_t>(Record).slice(1)))
637             return std::move(Err);
638         break;
639       }
640       case bitc::METADATA_KIND:
641       case bitc::METADATA_STRING_OLD:
642       case bitc::METADATA_OLD_FN_NODE:
643       case bitc::METADATA_OLD_NODE:
644       case bitc::METADATA_VALUE:
645       case bitc::METADATA_DISTINCT_NODE:
646       case bitc::METADATA_NODE:
647       case bitc::METADATA_LOCATION:
648       case bitc::METADATA_GENERIC_DEBUG:
649       case bitc::METADATA_SUBRANGE:
650       case bitc::METADATA_ENUMERATOR:
651       case bitc::METADATA_BASIC_TYPE:
652       case bitc::METADATA_DERIVED_TYPE:
653       case bitc::METADATA_COMPOSITE_TYPE:
654       case bitc::METADATA_SUBROUTINE_TYPE:
655       case bitc::METADATA_MODULE:
656       case bitc::METADATA_FILE:
657       case bitc::METADATA_COMPILE_UNIT:
658       case bitc::METADATA_SUBPROGRAM:
659       case bitc::METADATA_LEXICAL_BLOCK:
660       case bitc::METADATA_LEXICAL_BLOCK_FILE:
661       case bitc::METADATA_NAMESPACE:
662       case bitc::METADATA_MACRO:
663       case bitc::METADATA_MACRO_FILE:
664       case bitc::METADATA_TEMPLATE_TYPE:
665       case bitc::METADATA_TEMPLATE_VALUE:
666       case bitc::METADATA_GLOBAL_VAR:
667       case bitc::METADATA_LOCAL_VAR:
668       case bitc::METADATA_EXPRESSION:
669       case bitc::METADATA_OBJC_PROPERTY:
670       case bitc::METADATA_IMPORTED_ENTITY:
671       case bitc::METADATA_GLOBAL_VAR_EXPR:
672         // We don't expect to see any of these, if we see one, give up on
673         // lazy-loading and fallback.
674         MDStringRef.clear();
675         GlobalMetadataBitPosIndex.clear();
676         return false;
677       }
678       break;
679     }
680     }
681   }
682 }
683 
684 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
685 /// module level metadata.
686 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
687   if (!ModuleLevel && MetadataList.hasFwdRefs())
688     return error("Invalid metadata: fwd refs into function blocks");
689 
690   // Record the entry position so that we can jump back here and efficiently
691   // skip the whole block in case we lazy-load.
692   auto EntryPos = Stream.GetCurrentBitNo();
693 
694   if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
695     return error("Invalid record");
696 
697   SmallVector<uint64_t, 64> Record;
698   PlaceholderQueue Placeholders;
699 
700   // We lazy-load module-level metadata: we build an index for each record, and
701   // then load individual record as needed, starting with the named metadata.
702   if (ModuleLevel && IsImporting && MetadataList.empty() &&
703       !DisableLazyLoading) {
704     auto SuccessOrErr = lazyLoadModuleMetadataBlock();
705     if (!SuccessOrErr)
706       return SuccessOrErr.takeError();
707     if (SuccessOrErr.get()) {
708       // An index was successfully created and we will be able to load metadata
709       // on-demand.
710       MetadataList.resize(MDStringRef.size() +
711                           GlobalMetadataBitPosIndex.size());
712 
713       // Reading the named metadata created forward references and/or
714       // placeholders, that we flush here.
715       resolveForwardRefsAndPlaceholders(Placeholders);
716       upgradeCUSubprograms();
717       // Return at the beginning of the block, since it is easy to skip it
718       // entirely from there.
719       Stream.ReadBlockEnd(); // Pop the abbrev block context.
720       Stream.JumpToBit(EntryPos);
721       if (Stream.SkipBlock())
722         return error("Invalid record");
723       return Error::success();
724     }
725     // Couldn't load an index, fallback to loading all the block "old-style".
726   }
727 
728   unsigned NextMetadataNo = MetadataList.size();
729 
730   // Read all the records.
731   while (true) {
732     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
733 
734     switch (Entry.Kind) {
735     case BitstreamEntry::SubBlock: // Handled for us already.
736     case BitstreamEntry::Error:
737       return error("Malformed block");
738     case BitstreamEntry::EndBlock:
739       resolveForwardRefsAndPlaceholders(Placeholders);
740       upgradeCUSubprograms();
741       return Error::success();
742     case BitstreamEntry::Record:
743       // The interesting case.
744       break;
745     }
746 
747     // Read a record.
748     Record.clear();
749     StringRef Blob;
750     ++NumMDRecordLoaded;
751     unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
752     if (Error Err =
753             parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
754       return Err;
755   }
756 }
757 
758 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
759   ++NumMDStringLoaded;
760   if (Metadata *MD = MetadataList.lookup(ID))
761     return cast<MDString>(MD);
762   auto MDS = MDString::get(Context, MDStringRef[ID]);
763   MetadataList.assignValue(MDS, ID);
764   return MDS;
765 }
766 
767 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
768     unsigned ID, PlaceholderQueue &Placeholders) {
769   assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
770   assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
771   // Lookup first if the metadata hasn't already been loaded.
772   if (auto *MD = MetadataList.lookup(ID)) {
773     auto *N = dyn_cast_or_null<MDNode>(MD);
774     if (!N->isTemporary())
775       return;
776   }
777   SmallVector<uint64_t, 64> Record;
778   StringRef Blob;
779   IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
780   auto Entry = IndexCursor.advanceSkippingSubblocks();
781   ++NumMDRecordLoaded;
782   unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
783   if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
784     report_fatal_error("Can't lazyload MD");
785 }
786 
787 /// Ensure that all forward-references and placeholders are resolved.
788 /// Iteratively lazy-loading metadata on-demand if needed.
789 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
790     PlaceholderQueue &Placeholders) {
791   DenseSet<unsigned> Temporaries;
792   while (1) {
793     // Populate Temporaries with the placeholders that haven't been loaded yet.
794     Placeholders.getTemporaries(MetadataList, Temporaries);
795 
796     // If we don't have any temporary, or FwdReference, we're done!
797     if (Temporaries.empty() && !MetadataList.hasFwdRefs())
798       break;
799 
800     // First, load all the temporaries. This can add new placeholders or
801     // forward references.
802     for (auto ID : Temporaries)
803       lazyLoadOneMetadata(ID, Placeholders);
804     Temporaries.clear();
805 
806     // Second, load the forward-references. This can also add new placeholders
807     // or forward references.
808     while (MetadataList.hasFwdRefs())
809       lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
810   }
811   // At this point we don't have any forward reference remaining, or temporary
812   // that haven't been loaded. We can safely drop RAUW support and mark cycles
813   // as resolved.
814   MetadataList.tryToResolveCycles();
815 
816   // Finally, everything is in place, we can replace the placeholders operands
817   // with the final node they refer to.
818   Placeholders.flush(MetadataList);
819 }
820 
821 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
822     SmallVectorImpl<uint64_t> &Record, unsigned Code,
823     PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
824 
825   bool IsDistinct = false;
826   auto getMD = [&](unsigned ID) -> Metadata * {
827     if (ID < MDStringRef.size())
828       return lazyLoadOneMDString(ID);
829     if (!IsDistinct) {
830       if (auto *MD = MetadataList.lookup(ID))
831         return MD;
832       // If lazy-loading is enabled, we try recursively to load the operand
833       // instead of creating a temporary.
834       if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
835         // Create a temporary for the node that is referencing the operand we
836         // will lazy-load. It is needed before recursing in case there are
837         // uniquing cycles.
838         MetadataList.getMetadataFwdRef(NextMetadataNo);
839         lazyLoadOneMetadata(ID, Placeholders);
840         return MetadataList.lookup(ID);
841       }
842       // Return a temporary.
843       return MetadataList.getMetadataFwdRef(ID);
844     }
845     if (auto *MD = MetadataList.getMetadataIfResolved(ID))
846       return MD;
847     return &Placeholders.getPlaceholderOp(ID);
848   };
849   auto getMDOrNull = [&](unsigned ID) -> Metadata * {
850     if (ID)
851       return getMD(ID - 1);
852     return nullptr;
853   };
854   auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
855     if (ID)
856       return MetadataList.getMetadataFwdRef(ID - 1);
857     return nullptr;
858   };
859   auto getMDString = [&](unsigned ID) -> MDString * {
860     // This requires that the ID is not really a forward reference.  In
861     // particular, the MDString must already have been resolved.
862     auto MDS = getMDOrNull(ID);
863     return cast_or_null<MDString>(MDS);
864   };
865 
866   // Support for old type refs.
867   auto getDITypeRefOrNull = [&](unsigned ID) {
868     return MetadataList.upgradeTypeRef(getMDOrNull(ID));
869   };
870 
871 #define GET_OR_DISTINCT(CLASS, ARGS)                                           \
872   (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
873 
874   switch (Code) {
875   default: // Default behavior: ignore.
876     break;
877   case bitc::METADATA_NAME: {
878     // Read name of the named metadata.
879     SmallString<8> Name(Record.begin(), Record.end());
880     Record.clear();
881     Code = Stream.ReadCode();
882 
883     ++NumMDRecordLoaded;
884     unsigned NextBitCode = Stream.readRecord(Code, Record);
885     if (NextBitCode != bitc::METADATA_NAMED_NODE)
886       return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
887 
888     // Read named metadata elements.
889     unsigned Size = Record.size();
890     NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
891     for (unsigned i = 0; i != Size; ++i) {
892       MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
893       if (!MD)
894         return error("Invalid record");
895       NMD->addOperand(MD);
896     }
897     break;
898   }
899   case bitc::METADATA_OLD_FN_NODE: {
900     // FIXME: Remove in 4.0.
901     // This is a LocalAsMetadata record, the only type of function-local
902     // metadata.
903     if (Record.size() % 2 == 1)
904       return error("Invalid record");
905 
906     // If this isn't a LocalAsMetadata record, we're dropping it.  This used
907     // to be legal, but there's no upgrade path.
908     auto dropRecord = [&] {
909       MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
910     };
911     if (Record.size() != 2) {
912       dropRecord();
913       break;
914     }
915 
916     Type *Ty = getTypeByID(Record[0]);
917     if (Ty->isMetadataTy() || Ty->isVoidTy()) {
918       dropRecord();
919       break;
920     }
921 
922     MetadataList.assignValue(
923         LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
924         NextMetadataNo++);
925     break;
926   }
927   case bitc::METADATA_OLD_NODE: {
928     // FIXME: Remove in 4.0.
929     if (Record.size() % 2 == 1)
930       return error("Invalid record");
931 
932     unsigned Size = Record.size();
933     SmallVector<Metadata *, 8> Elts;
934     for (unsigned i = 0; i != Size; i += 2) {
935       Type *Ty = getTypeByID(Record[i]);
936       if (!Ty)
937         return error("Invalid record");
938       if (Ty->isMetadataTy())
939         Elts.push_back(getMD(Record[i + 1]));
940       else if (!Ty->isVoidTy()) {
941         auto *MD =
942             ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
943         assert(isa<ConstantAsMetadata>(MD) &&
944                "Expected non-function-local metadata");
945         Elts.push_back(MD);
946       } else
947         Elts.push_back(nullptr);
948     }
949     MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
950     break;
951   }
952   case bitc::METADATA_VALUE: {
953     if (Record.size() != 2)
954       return error("Invalid record");
955 
956     Type *Ty = getTypeByID(Record[0]);
957     if (Ty->isMetadataTy() || Ty->isVoidTy())
958       return error("Invalid record");
959 
960     MetadataList.assignValue(
961         ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
962         NextMetadataNo++);
963     break;
964   }
965   case bitc::METADATA_DISTINCT_NODE:
966     IsDistinct = true;
967     LLVM_FALLTHROUGH;
968   case bitc::METADATA_NODE: {
969     SmallVector<Metadata *, 8> Elts;
970     Elts.reserve(Record.size());
971     for (unsigned ID : Record)
972       Elts.push_back(getMDOrNull(ID));
973     MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
974                                         : MDNode::get(Context, Elts),
975                              NextMetadataNo++);
976     break;
977   }
978   case bitc::METADATA_LOCATION: {
979     if (Record.size() != 5)
980       return error("Invalid record");
981 
982     IsDistinct = Record[0];
983     unsigned Line = Record[1];
984     unsigned Column = Record[2];
985     Metadata *Scope = getMD(Record[3]);
986     Metadata *InlinedAt = getMDOrNull(Record[4]);
987     MetadataList.assignValue(
988         GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
989         NextMetadataNo++);
990     break;
991   }
992   case bitc::METADATA_GENERIC_DEBUG: {
993     if (Record.size() < 4)
994       return error("Invalid record");
995 
996     IsDistinct = Record[0];
997     unsigned Tag = Record[1];
998     unsigned Version = Record[2];
999 
1000     if (Tag >= 1u << 16 || Version != 0)
1001       return error("Invalid record");
1002 
1003     auto *Header = getMDString(Record[3]);
1004     SmallVector<Metadata *, 8> DwarfOps;
1005     for (unsigned I = 4, E = Record.size(); I != E; ++I)
1006       DwarfOps.push_back(getMDOrNull(Record[I]));
1007     MetadataList.assignValue(
1008         GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
1009         NextMetadataNo++);
1010     break;
1011   }
1012   case bitc::METADATA_SUBRANGE: {
1013     if (Record.size() != 3)
1014       return error("Invalid record");
1015 
1016     IsDistinct = Record[0];
1017     MetadataList.assignValue(
1018         GET_OR_DISTINCT(DISubrange,
1019                         (Context, Record[1], unrotateSign(Record[2]))),
1020         NextMetadataNo++);
1021     break;
1022   }
1023   case bitc::METADATA_ENUMERATOR: {
1024     if (Record.size() != 3)
1025       return error("Invalid record");
1026 
1027     IsDistinct = Record[0];
1028     MetadataList.assignValue(
1029         GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
1030                                        getMDString(Record[2]))),
1031         NextMetadataNo++);
1032     break;
1033   }
1034   case bitc::METADATA_BASIC_TYPE: {
1035     if (Record.size() != 6)
1036       return error("Invalid record");
1037 
1038     IsDistinct = Record[0];
1039     MetadataList.assignValue(
1040         GET_OR_DISTINCT(DIBasicType,
1041                         (Context, Record[1], getMDString(Record[2]), Record[3],
1042                          Record[4], Record[5])),
1043         NextMetadataNo++);
1044     break;
1045   }
1046   case bitc::METADATA_DERIVED_TYPE: {
1047     if (Record.size() != 12)
1048       return error("Invalid record");
1049 
1050     IsDistinct = Record[0];
1051     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1052     MetadataList.assignValue(
1053         GET_OR_DISTINCT(DIDerivedType,
1054                         (Context, Record[1], getMDString(Record[2]),
1055                          getMDOrNull(Record[3]), Record[4],
1056                          getDITypeRefOrNull(Record[5]),
1057                          getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1058                          Record[9], Flags, getDITypeRefOrNull(Record[11]))),
1059         NextMetadataNo++);
1060     break;
1061   }
1062   case bitc::METADATA_COMPOSITE_TYPE: {
1063     if (Record.size() != 16)
1064       return error("Invalid record");
1065 
1066     // If we have a UUID and this is not a forward declaration, lookup the
1067     // mapping.
1068     IsDistinct = Record[0] & 0x1;
1069     bool IsNotUsedInTypeRef = Record[0] >= 2;
1070     unsigned Tag = Record[1];
1071     MDString *Name = getMDString(Record[2]);
1072     Metadata *File = getMDOrNull(Record[3]);
1073     unsigned Line = Record[4];
1074     Metadata *Scope = getDITypeRefOrNull(Record[5]);
1075     Metadata *BaseType = nullptr;
1076     uint64_t SizeInBits = Record[7];
1077     if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
1078       return error("Alignment value is too large");
1079     uint32_t AlignInBits = Record[8];
1080     uint64_t OffsetInBits = 0;
1081     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
1082     Metadata *Elements = nullptr;
1083     unsigned RuntimeLang = Record[12];
1084     Metadata *VTableHolder = nullptr;
1085     Metadata *TemplateParams = nullptr;
1086     auto *Identifier = getMDString(Record[15]);
1087     // If this module is being parsed so that it can be ThinLTO imported
1088     // into another module, composite types only need to be imported
1089     // as type declarations (unless full type definitions requested).
1090     // Create type declarations up front to save memory. Also, buildODRType
1091     // handles the case where this is type ODRed with a definition needed
1092     // by the importing module, in which case the existing definition is
1093     // used.
1094     if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
1095         (Tag == dwarf::DW_TAG_enumeration_type ||
1096          Tag == dwarf::DW_TAG_class_type ||
1097          Tag == dwarf::DW_TAG_structure_type ||
1098          Tag == dwarf::DW_TAG_union_type)) {
1099       Flags = Flags | DINode::FlagFwdDecl;
1100     } else {
1101       BaseType = getDITypeRefOrNull(Record[6]);
1102       OffsetInBits = Record[9];
1103       Elements = getMDOrNull(Record[11]);
1104       VTableHolder = getDITypeRefOrNull(Record[13]);
1105       TemplateParams = getMDOrNull(Record[14]);
1106     }
1107     DICompositeType *CT = nullptr;
1108     if (Identifier)
1109       CT = DICompositeType::buildODRType(
1110           Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
1111           SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1112           VTableHolder, TemplateParams);
1113 
1114     // Create a node if we didn't get a lazy ODR type.
1115     if (!CT)
1116       CT = GET_OR_DISTINCT(DICompositeType,
1117                            (Context, Tag, Name, File, Line, Scope, BaseType,
1118                             SizeInBits, AlignInBits, OffsetInBits, Flags,
1119                             Elements, RuntimeLang, VTableHolder, TemplateParams,
1120                             Identifier));
1121     if (!IsNotUsedInTypeRef && Identifier)
1122       MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
1123 
1124     MetadataList.assignValue(CT, NextMetadataNo++);
1125     break;
1126   }
1127   case bitc::METADATA_SUBROUTINE_TYPE: {
1128     if (Record.size() < 3 || Record.size() > 4)
1129       return error("Invalid record");
1130     bool IsOldTypeRefArray = Record[0] < 2;
1131     unsigned CC = (Record.size() > 3) ? Record[3] : 0;
1132 
1133     IsDistinct = Record[0] & 0x1;
1134     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
1135     Metadata *Types = getMDOrNull(Record[2]);
1136     if (LLVM_UNLIKELY(IsOldTypeRefArray))
1137       Types = MetadataList.upgradeTypeRefArray(Types);
1138 
1139     MetadataList.assignValue(
1140         GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
1141         NextMetadataNo++);
1142     break;
1143   }
1144 
1145   case bitc::METADATA_MODULE: {
1146     if (Record.size() != 6)
1147       return error("Invalid record");
1148 
1149     IsDistinct = Record[0];
1150     MetadataList.assignValue(
1151         GET_OR_DISTINCT(DIModule,
1152                         (Context, getMDOrNull(Record[1]),
1153                          getMDString(Record[2]), getMDString(Record[3]),
1154                          getMDString(Record[4]), getMDString(Record[5]))),
1155         NextMetadataNo++);
1156     break;
1157   }
1158 
1159   case bitc::METADATA_FILE: {
1160     if (Record.size() != 3 && Record.size() != 5)
1161       return error("Invalid record");
1162 
1163     IsDistinct = Record[0];
1164     MetadataList.assignValue(
1165         GET_OR_DISTINCT(
1166             DIFile,
1167             (Context, getMDString(Record[1]), getMDString(Record[2]),
1168              Record.size() == 3 ? DIFile::CSK_None
1169                                 : static_cast<DIFile::ChecksumKind>(Record[3]),
1170              Record.size() == 3 ? nullptr : getMDString(Record[4]))),
1171         NextMetadataNo++);
1172     break;
1173   }
1174   case bitc::METADATA_COMPILE_UNIT: {
1175     if (Record.size() < 14 || Record.size() > 17)
1176       return error("Invalid record");
1177 
1178     // Ignore Record[0], which indicates whether this compile unit is
1179     // distinct.  It's always distinct.
1180     IsDistinct = true;
1181     auto *CU = DICompileUnit::getDistinct(
1182         Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
1183         Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
1184         Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1185         getMDOrNull(Record[12]), getMDOrNull(Record[13]),
1186         Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
1187         Record.size() <= 14 ? 0 : Record[14],
1188         Record.size() <= 16 ? true : Record[16]);
1189 
1190     MetadataList.assignValue(CU, NextMetadataNo++);
1191 
1192     // Move the Upgrade the list of subprograms.
1193     if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
1194       CUSubprograms.push_back({CU, SPs});
1195     break;
1196   }
1197   case bitc::METADATA_SUBPROGRAM: {
1198     if (Record.size() < 18 || Record.size() > 20)
1199       return error("Invalid record");
1200 
1201     IsDistinct =
1202         (Record[0] & 1) || Record[8]; // All definitions should be distinct.
1203     // Version 1 has a Function as Record[15].
1204     // Version 2 has removed Record[15].
1205     // Version 3 has the Unit as Record[15].
1206     // Version 4 added thisAdjustment.
1207     bool HasUnit = Record[0] >= 2;
1208     if (HasUnit && Record.size() < 19)
1209       return error("Invalid record");
1210     Metadata *CUorFn = getMDOrNull(Record[15]);
1211     unsigned Offset = Record.size() >= 19 ? 1 : 0;
1212     bool HasFn = Offset && !HasUnit;
1213     bool HasThisAdj = Record.size() >= 20;
1214     DISubprogram *SP = GET_OR_DISTINCT(
1215         DISubprogram, (Context,
1216                        getDITypeRefOrNull(Record[1]),          // scope
1217                        getMDString(Record[2]),                 // name
1218                        getMDString(Record[3]),                 // linkageName
1219                        getMDOrNull(Record[4]),                 // file
1220                        Record[5],                              // line
1221                        getMDOrNull(Record[6]),                 // type
1222                        Record[7],                              // isLocal
1223                        Record[8],                              // isDefinition
1224                        Record[9],                              // scopeLine
1225                        getDITypeRefOrNull(Record[10]),         // containingType
1226                        Record[11],                             // virtuality
1227                        Record[12],                             // virtualIndex
1228                        HasThisAdj ? Record[19] : 0,            // thisAdjustment
1229                        static_cast<DINode::DIFlags>(Record[13] // flags
1230                                                     ),
1231                        Record[14],                       // isOptimized
1232                        HasUnit ? CUorFn : nullptr,       // unit
1233                        getMDOrNull(Record[15 + Offset]), // templateParams
1234                        getMDOrNull(Record[16 + Offset]), // declaration
1235                        getMDOrNull(Record[17 + Offset])  // variables
1236                        ));
1237     MetadataList.assignValue(SP, NextMetadataNo++);
1238 
1239     // Upgrade sp->function mapping to function->sp mapping.
1240     if (HasFn) {
1241       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
1242         if (auto *F = dyn_cast<Function>(CMD->getValue())) {
1243           if (F->isMaterializable())
1244             // Defer until materialized; unmaterialized functions may not have
1245             // metadata.
1246             FunctionsWithSPs[F] = SP;
1247           else if (!F->empty())
1248             F->setSubprogram(SP);
1249         }
1250     }
1251     break;
1252   }
1253   case bitc::METADATA_LEXICAL_BLOCK: {
1254     if (Record.size() != 5)
1255       return error("Invalid record");
1256 
1257     IsDistinct = Record[0];
1258     MetadataList.assignValue(
1259         GET_OR_DISTINCT(DILexicalBlock,
1260                         (Context, getMDOrNull(Record[1]),
1261                          getMDOrNull(Record[2]), Record[3], Record[4])),
1262         NextMetadataNo++);
1263     break;
1264   }
1265   case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1266     if (Record.size() != 4)
1267       return error("Invalid record");
1268 
1269     IsDistinct = Record[0];
1270     MetadataList.assignValue(
1271         GET_OR_DISTINCT(DILexicalBlockFile,
1272                         (Context, getMDOrNull(Record[1]),
1273                          getMDOrNull(Record[2]), Record[3])),
1274         NextMetadataNo++);
1275     break;
1276   }
1277   case bitc::METADATA_NAMESPACE: {
1278     if (Record.size() != 5)
1279       return error("Invalid record");
1280 
1281     IsDistinct = Record[0] & 1;
1282     bool ExportSymbols = Record[0] & 2;
1283     MetadataList.assignValue(
1284         GET_OR_DISTINCT(DINamespace,
1285                         (Context, getMDOrNull(Record[1]),
1286                          getMDOrNull(Record[2]), getMDString(Record[3]),
1287                          Record[4], ExportSymbols)),
1288         NextMetadataNo++);
1289     break;
1290   }
1291   case bitc::METADATA_MACRO: {
1292     if (Record.size() != 5)
1293       return error("Invalid record");
1294 
1295     IsDistinct = Record[0];
1296     MetadataList.assignValue(
1297         GET_OR_DISTINCT(DIMacro,
1298                         (Context, Record[1], Record[2], getMDString(Record[3]),
1299                          getMDString(Record[4]))),
1300         NextMetadataNo++);
1301     break;
1302   }
1303   case bitc::METADATA_MACRO_FILE: {
1304     if (Record.size() != 5)
1305       return error("Invalid record");
1306 
1307     IsDistinct = Record[0];
1308     MetadataList.assignValue(
1309         GET_OR_DISTINCT(DIMacroFile,
1310                         (Context, Record[1], Record[2], getMDOrNull(Record[3]),
1311                          getMDOrNull(Record[4]))),
1312         NextMetadataNo++);
1313     break;
1314   }
1315   case bitc::METADATA_TEMPLATE_TYPE: {
1316     if (Record.size() != 3)
1317       return error("Invalid record");
1318 
1319     IsDistinct = Record[0];
1320     MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
1321                                              (Context, getMDString(Record[1]),
1322                                               getDITypeRefOrNull(Record[2]))),
1323                              NextMetadataNo++);
1324     break;
1325   }
1326   case bitc::METADATA_TEMPLATE_VALUE: {
1327     if (Record.size() != 5)
1328       return error("Invalid record");
1329 
1330     IsDistinct = Record[0];
1331     MetadataList.assignValue(
1332         GET_OR_DISTINCT(DITemplateValueParameter,
1333                         (Context, Record[1], getMDString(Record[2]),
1334                          getDITypeRefOrNull(Record[3]),
1335                          getMDOrNull(Record[4]))),
1336         NextMetadataNo++);
1337     break;
1338   }
1339   case bitc::METADATA_GLOBAL_VAR: {
1340     if (Record.size() < 11 || Record.size() > 12)
1341       return error("Invalid record");
1342 
1343     IsDistinct = Record[0] & 1;
1344     unsigned Version = Record[0] >> 1;
1345 
1346     if (Version == 1) {
1347       MetadataList.assignValue(
1348           GET_OR_DISTINCT(DIGlobalVariable,
1349                           (Context, getMDOrNull(Record[1]),
1350                            getMDString(Record[2]), getMDString(Record[3]),
1351                            getMDOrNull(Record[4]), Record[5],
1352                            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1353                            getMDOrNull(Record[10]), Record[11])),
1354           NextMetadataNo++);
1355     } else if (Version == 0) {
1356       // Upgrade old metadata, which stored a global variable reference or a
1357       // ConstantInt here.
1358       Metadata *Expr = getMDOrNull(Record[9]);
1359       uint32_t AlignInBits = 0;
1360       if (Record.size() > 11) {
1361         if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
1362           return error("Alignment value is too large");
1363         AlignInBits = Record[11];
1364       }
1365       GlobalVariable *Attach = nullptr;
1366       if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
1367         if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
1368           Attach = GV;
1369           Expr = nullptr;
1370         } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
1371           Expr = DIExpression::get(Context,
1372                                    {dwarf::DW_OP_constu, CI->getZExtValue(),
1373                                     dwarf::DW_OP_stack_value});
1374         } else {
1375           Expr = nullptr;
1376         }
1377       }
1378       DIGlobalVariable *DGV = GET_OR_DISTINCT(
1379           DIGlobalVariable,
1380           (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1381            getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1382            getDITypeRefOrNull(Record[6]), Record[7], Record[8],
1383            getMDOrNull(Record[10]), AlignInBits));
1384 
1385       auto *DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
1386       MetadataList.assignValue(DGVE, NextMetadataNo++);
1387       if (Attach)
1388         Attach->addDebugInfo(DGVE);
1389     } else
1390       return error("Invalid record");
1391 
1392     break;
1393   }
1394   case bitc::METADATA_LOCAL_VAR: {
1395     // 10th field is for the obseleted 'inlinedAt:' field.
1396     if (Record.size() < 8 || Record.size() > 10)
1397       return error("Invalid record");
1398 
1399     IsDistinct = Record[0] & 1;
1400     bool HasAlignment = Record[0] & 2;
1401     // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
1402     // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
1403     // this is newer version of record which doesn't have artifical tag.
1404     bool HasTag = !HasAlignment && Record.size() > 8;
1405     DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
1406     uint32_t AlignInBits = 0;
1407     if (HasAlignment) {
1408       if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
1409         return error("Alignment value is too large");
1410       AlignInBits = Record[8 + HasTag];
1411     }
1412     MetadataList.assignValue(
1413         GET_OR_DISTINCT(DILocalVariable,
1414                         (Context, getMDOrNull(Record[1 + HasTag]),
1415                          getMDString(Record[2 + HasTag]),
1416                          getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
1417                          getDITypeRefOrNull(Record[5 + HasTag]),
1418                          Record[6 + HasTag], Flags, AlignInBits)),
1419         NextMetadataNo++);
1420     break;
1421   }
1422   case bitc::METADATA_EXPRESSION: {
1423     if (Record.size() < 1)
1424       return error("Invalid record");
1425 
1426     IsDistinct = Record[0] & 1;
1427     bool HasOpFragment = Record[0] & 2;
1428     auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
1429     if (!HasOpFragment)
1430       if (unsigned N = Elts.size())
1431         if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
1432           Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
1433 
1434     MetadataList.assignValue(
1435         GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
1436         NextMetadataNo++);
1437     break;
1438   }
1439   case bitc::METADATA_GLOBAL_VAR_EXPR: {
1440     if (Record.size() != 3)
1441       return error("Invalid record");
1442 
1443     IsDistinct = Record[0];
1444     MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
1445                                              (Context, getMDOrNull(Record[1]),
1446                                               getMDOrNull(Record[2]))),
1447                              NextMetadataNo++);
1448     break;
1449   }
1450   case bitc::METADATA_OBJC_PROPERTY: {
1451     if (Record.size() != 8)
1452       return error("Invalid record");
1453 
1454     IsDistinct = Record[0];
1455     MetadataList.assignValue(
1456         GET_OR_DISTINCT(DIObjCProperty,
1457                         (Context, getMDString(Record[1]),
1458                          getMDOrNull(Record[2]), Record[3],
1459                          getMDString(Record[4]), getMDString(Record[5]),
1460                          Record[6], getDITypeRefOrNull(Record[7]))),
1461         NextMetadataNo++);
1462     break;
1463   }
1464   case bitc::METADATA_IMPORTED_ENTITY: {
1465     if (Record.size() != 6)
1466       return error("Invalid record");
1467 
1468     IsDistinct = Record[0];
1469     MetadataList.assignValue(
1470         GET_OR_DISTINCT(DIImportedEntity,
1471                         (Context, Record[1], getMDOrNull(Record[2]),
1472                          getDITypeRefOrNull(Record[3]), Record[4],
1473                          getMDString(Record[5]))),
1474         NextMetadataNo++);
1475     break;
1476   }
1477   case bitc::METADATA_STRING_OLD: {
1478     std::string String(Record.begin(), Record.end());
1479 
1480     // Test for upgrading !llvm.loop.
1481     HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
1482     ++NumMDStringLoaded;
1483     Metadata *MD = MDString::get(Context, String);
1484     MetadataList.assignValue(MD, NextMetadataNo++);
1485     break;
1486   }
1487   case bitc::METADATA_STRINGS: {
1488     auto CreateNextMDString = [&](StringRef Str) {
1489       ++NumMDStringLoaded;
1490       MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo++);
1491     };
1492     if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
1493       return Err;
1494     break;
1495   }
1496   case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
1497     if (Record.size() % 2 == 0)
1498       return error("Invalid record");
1499     unsigned ValueID = Record[0];
1500     if (ValueID >= ValueList.size())
1501       return error("Invalid record");
1502     if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
1503       if (Error Err = parseGlobalObjectAttachment(
1504               *GO, ArrayRef<uint64_t>(Record).slice(1)))
1505         return Err;
1506     break;
1507   }
1508   case bitc::METADATA_KIND: {
1509     // Support older bitcode files that had METADATA_KIND records in a
1510     // block with METADATA_BLOCK_ID.
1511     if (Error Err = parseMetadataKindRecord(Record))
1512       return Err;
1513     break;
1514   }
1515   }
1516   return Error::success();
1517 #undef GET_OR_DISTINCT
1518 }
1519 
1520 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
1521     ArrayRef<uint64_t> Record, StringRef Blob,
1522     function_ref<void(StringRef)> CallBack) {
1523   // All the MDStrings in the block are emitted together in a single
1524   // record.  The strings are concatenated and stored in a blob along with
1525   // their sizes.
1526   if (Record.size() != 2)
1527     return error("Invalid record: metadata strings layout");
1528 
1529   unsigned NumStrings = Record[0];
1530   unsigned StringsOffset = Record[1];
1531   if (!NumStrings)
1532     return error("Invalid record: metadata strings with no strings");
1533   if (StringsOffset > Blob.size())
1534     return error("Invalid record: metadata strings corrupt offset");
1535 
1536   StringRef Lengths = Blob.slice(0, StringsOffset);
1537   SimpleBitstreamCursor R(Lengths);
1538 
1539   StringRef Strings = Blob.drop_front(StringsOffset);
1540   do {
1541     if (R.AtEndOfStream())
1542       return error("Invalid record: metadata strings bad length");
1543 
1544     unsigned Size = R.ReadVBR(6);
1545     if (Strings.size() < Size)
1546       return error("Invalid record: metadata strings truncated chars");
1547 
1548     CallBack(Strings.slice(0, Size));
1549     Strings = Strings.drop_front(Size);
1550   } while (--NumStrings);
1551 
1552   return Error::success();
1553 }
1554 
1555 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
1556     GlobalObject &GO, ArrayRef<uint64_t> Record) {
1557   assert(Record.size() % 2 == 0);
1558   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
1559     auto K = MDKindMap.find(Record[I]);
1560     if (K == MDKindMap.end())
1561       return error("Invalid ID");
1562     MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
1563     if (!MD)
1564       return error("Invalid metadata attachment");
1565     GO.addMetadata(K->second, *MD);
1566   }
1567   return Error::success();
1568 }
1569 
1570 /// Parse metadata attachments.
1571 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
1572     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1573   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1574     return error("Invalid record");
1575 
1576   SmallVector<uint64_t, 64> Record;
1577   PlaceholderQueue Placeholders;
1578 
1579   while (true) {
1580     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1581 
1582     switch (Entry.Kind) {
1583     case BitstreamEntry::SubBlock: // Handled for us already.
1584     case BitstreamEntry::Error:
1585       return error("Malformed block");
1586     case BitstreamEntry::EndBlock:
1587       resolveForwardRefsAndPlaceholders(Placeholders);
1588       return Error::success();
1589     case BitstreamEntry::Record:
1590       // The interesting case.
1591       break;
1592     }
1593 
1594     // Read a metadata attachment record.
1595     Record.clear();
1596     ++NumMDRecordLoaded;
1597     switch (Stream.readRecord(Entry.ID, Record)) {
1598     default: // Default behavior: ignore.
1599       break;
1600     case bitc::METADATA_ATTACHMENT: {
1601       unsigned RecordLength = Record.size();
1602       if (Record.empty())
1603         return error("Invalid record");
1604       if (RecordLength % 2 == 0) {
1605         // A function attachment.
1606         if (Error Err = parseGlobalObjectAttachment(F, Record))
1607           return Err;
1608         continue;
1609       }
1610 
1611       // An instruction attachment.
1612       Instruction *Inst = InstructionList[Record[0]];
1613       for (unsigned i = 1; i != RecordLength; i = i + 2) {
1614         unsigned Kind = Record[i];
1615         DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
1616         if (I == MDKindMap.end())
1617           return error("Invalid ID");
1618         if (I->second == LLVMContext::MD_tbaa && StripTBAA)
1619           continue;
1620 
1621         auto Idx = Record[i + 1];
1622         if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
1623             !MetadataList.lookup(Idx)) {
1624           // Load the attachment if it is in the lazy-loadable range and hasn't
1625           // been loaded yet.
1626           lazyLoadOneMetadata(Idx, Placeholders);
1627           resolveForwardRefsAndPlaceholders(Placeholders);
1628         }
1629 
1630         Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
1631         if (isa<LocalAsMetadata>(Node))
1632           // Drop the attachment.  This used to be legal, but there's no
1633           // upgrade path.
1634           break;
1635         MDNode *MD = dyn_cast_or_null<MDNode>(Node);
1636         if (!MD)
1637           return error("Invalid metadata attachment");
1638 
1639         if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
1640           MD = upgradeInstructionLoopAttachment(*MD);
1641 
1642         if (I->second == LLVMContext::MD_tbaa) {
1643           assert(!MD->isTemporary() && "should load MDs before attachments");
1644           MD = UpgradeTBAANode(*MD);
1645         }
1646         Inst->setMetadata(I->second, MD);
1647       }
1648       break;
1649     }
1650     }
1651   }
1652 }
1653 
1654 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1655 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
1656     SmallVectorImpl<uint64_t> &Record) {
1657   if (Record.size() < 2)
1658     return error("Invalid record");
1659 
1660   unsigned Kind = Record[0];
1661   SmallString<8> Name(Record.begin() + 1, Record.end());
1662 
1663   unsigned NewKind = TheModule.getMDKindID(Name.str());
1664   if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1665     return error("Conflicting METADATA_KIND records");
1666   return Error::success();
1667 }
1668 
1669 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
1670 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
1671   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
1672     return error("Invalid record");
1673 
1674   SmallVector<uint64_t, 64> Record;
1675 
1676   // Read all the records.
1677   while (true) {
1678     BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1679 
1680     switch (Entry.Kind) {
1681     case BitstreamEntry::SubBlock: // Handled for us already.
1682     case BitstreamEntry::Error:
1683       return error("Malformed block");
1684     case BitstreamEntry::EndBlock:
1685       return Error::success();
1686     case BitstreamEntry::Record:
1687       // The interesting case.
1688       break;
1689     }
1690 
1691     // Read a record.
1692     Record.clear();
1693     ++NumMDRecordLoaded;
1694     unsigned Code = Stream.readRecord(Entry.ID, Record);
1695     switch (Code) {
1696     default: // Default behavior: ignore.
1697       break;
1698     case bitc::METADATA_KIND: {
1699       if (Error Err = parseMetadataKindRecord(Record))
1700         return Err;
1701       break;
1702     }
1703     }
1704   }
1705 }
1706 
1707 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
1708   Pimpl = std::move(RHS.Pimpl);
1709   return *this;
1710 }
1711 MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
1712     : Pimpl(std::move(RHS.Pimpl)) {}
1713 
1714 MetadataLoader::~MetadataLoader() = default;
1715 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
1716                                BitcodeReaderValueList &ValueList,
1717                                bool IsImporting,
1718                                std::function<Type *(unsigned)> getTypeByID)
1719     : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
1720           Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
1721 
1722 Error MetadataLoader::parseMetadata(bool ModuleLevel) {
1723   return Pimpl->parseMetadata(ModuleLevel);
1724 }
1725 
1726 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
1727 
1728 /// Return the given metadata, creating a replaceable forward reference if
1729 /// necessary.
1730 Metadata *MetadataLoader::getMetadataFwdRef(unsigned Idx) {
1731   return Pimpl->getMetadataFwdRef(Idx);
1732 }
1733 
1734 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
1735   return Pimpl->getMDNodeFwdRefOrNull(Idx);
1736 }
1737 
1738 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
1739   return Pimpl->lookupSubprogramForFunction(F);
1740 }
1741 
1742 Error MetadataLoader::parseMetadataAttachment(
1743     Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
1744   return Pimpl->parseMetadataAttachment(F, InstructionList);
1745 }
1746 
1747 Error MetadataLoader::parseMetadataKinds() {
1748   return Pimpl->parseMetadataKinds();
1749 }
1750 
1751 void MetadataLoader::setStripTBAA(bool StripTBAA) {
1752   return Pimpl->setStripTBAA(StripTBAA);
1753 }
1754 
1755 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
1756 
1757 unsigned MetadataLoader::size() const { return Pimpl->size(); }
1758 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }
1759