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