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