xref: /freebsd/contrib/llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===- BitcodeReader.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 "llvm/Bitcode/BitcodeReader.h"
10 #include "MetadataLoader.h"
11 #include "ValueList.h"
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/STLExtras.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Bitcode/BitcodeCommon.h"
22 #include "llvm/Bitcode/LLVMBitCodes.h"
23 #include "llvm/Bitstream/BitstreamReader.h"
24 #include "llvm/Config/llvm-config.h"
25 #include "llvm/IR/Argument.h"
26 #include "llvm/IR/AttributeMask.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/DataLayout.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/Function.h"
40 #include "llvm/IR/GVMaterializer.h"
41 #include "llvm/IR/GetElementPtrTypeIterator.h"
42 #include "llvm/IR/GlobalAlias.h"
43 #include "llvm/IR/GlobalIFunc.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/InstIterator.h"
49 #include "llvm/IR/InstrTypes.h"
50 #include "llvm/IR/Instruction.h"
51 #include "llvm/IR/Instructions.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/IntrinsicsAArch64.h"
54 #include "llvm/IR/IntrinsicsARM.h"
55 #include "llvm/IR/LLVMContext.h"
56 #include "llvm/IR/Metadata.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/ModuleSummaryIndex.h"
59 #include "llvm/IR/Operator.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Value.h"
62 #include "llvm/IR/Verifier.h"
63 #include "llvm/Support/AtomicOrdering.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Compiler.h"
67 #include "llvm/Support/Debug.h"
68 #include "llvm/Support/Error.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/ErrorOr.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/MemoryBuffer.h"
73 #include "llvm/Support/ModRef.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include "llvm/TargetParser/Triple.h"
76 #include <algorithm>
77 #include <cassert>
78 #include <cstddef>
79 #include <cstdint>
80 #include <deque>
81 #include <map>
82 #include <memory>
83 #include <optional>
84 #include <set>
85 #include <string>
86 #include <system_error>
87 #include <tuple>
88 #include <utility>
89 #include <vector>
90 
91 using namespace llvm;
92 
93 static cl::opt<bool> PrintSummaryGUIDs(
94     "print-summary-global-ids", cl::init(false), cl::Hidden,
95     cl::desc(
96         "Print the global id for each value when reading the module summary"));
97 
98 static cl::opt<bool> ExpandConstantExprs(
99     "expand-constant-exprs", cl::Hidden,
100     cl::desc(
101         "Expand constant expressions to instructions for testing purposes"));
102 
103 namespace {
104 
105 enum {
106   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
107 };
108 
109 } // end anonymous namespace
110 
111 static Error error(const Twine &Message) {
112   return make_error<StringError>(
113       Message, make_error_code(BitcodeError::CorruptedBitcode));
114 }
115 
116 static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
117   if (!Stream.canSkipToPos(4))
118     return createStringError(std::errc::illegal_byte_sequence,
119                              "file too small to contain bitcode header");
120   for (unsigned C : {'B', 'C'})
121     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
122       if (Res.get() != C)
123         return createStringError(std::errc::illegal_byte_sequence,
124                                  "file doesn't start with bitcode header");
125     } else
126       return Res.takeError();
127   for (unsigned C : {0x0, 0xC, 0xE, 0xD})
128     if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
129       if (Res.get() != C)
130         return createStringError(std::errc::illegal_byte_sequence,
131                                  "file doesn't start with bitcode header");
132     } else
133       return Res.takeError();
134   return Error::success();
135 }
136 
137 static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
138   const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
139   const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
140 
141   if (Buffer.getBufferSize() & 3)
142     return error("Invalid bitcode signature");
143 
144   // If we have a wrapper header, parse it and ignore the non-bc file contents.
145   // The magic number is 0x0B17C0DE stored in little endian.
146   if (isBitcodeWrapper(BufPtr, BufEnd))
147     if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
148       return error("Invalid bitcode wrapper header");
149 
150   BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
151   if (Error Err = hasInvalidBitcodeHeader(Stream))
152     return std::move(Err);
153 
154   return std::move(Stream);
155 }
156 
157 /// Convert a string from a record into an std::string, return true on failure.
158 template <typename StrTy>
159 static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
160                             StrTy &Result) {
161   if (Idx > Record.size())
162     return true;
163 
164   Result.append(Record.begin() + Idx, Record.end());
165   return false;
166 }
167 
168 // Strip all the TBAA attachment for the module.
169 static void stripTBAA(Module *M) {
170   for (auto &F : *M) {
171     if (F.isMaterializable())
172       continue;
173     for (auto &I : instructions(F))
174       I.setMetadata(LLVMContext::MD_tbaa, nullptr);
175   }
176 }
177 
178 /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
179 /// "epoch" encoded in the bitcode, and return the producer name if any.
180 static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
181   if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
182     return std::move(Err);
183 
184   // Read all the records.
185   SmallVector<uint64_t, 64> Record;
186 
187   std::string ProducerIdentification;
188 
189   while (true) {
190     BitstreamEntry Entry;
191     if (Error E = Stream.advance().moveInto(Entry))
192       return std::move(E);
193 
194     switch (Entry.Kind) {
195     default:
196     case BitstreamEntry::Error:
197       return error("Malformed block");
198     case BitstreamEntry::EndBlock:
199       return ProducerIdentification;
200     case BitstreamEntry::Record:
201       // The interesting case.
202       break;
203     }
204 
205     // Read a record.
206     Record.clear();
207     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
208     if (!MaybeBitCode)
209       return MaybeBitCode.takeError();
210     switch (MaybeBitCode.get()) {
211     default: // Default behavior: reject
212       return error("Invalid value");
213     case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
214       convertToString(Record, 0, ProducerIdentification);
215       break;
216     case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
217       unsigned epoch = (unsigned)Record[0];
218       if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
219         return error(
220           Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
221           "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
222       }
223     }
224     }
225   }
226 }
227 
228 static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
229   // We expect a number of well-defined blocks, though we don't necessarily
230   // need to understand them all.
231   while (true) {
232     if (Stream.AtEndOfStream())
233       return "";
234 
235     BitstreamEntry Entry;
236     if (Error E = Stream.advance().moveInto(Entry))
237       return std::move(E);
238 
239     switch (Entry.Kind) {
240     case BitstreamEntry::EndBlock:
241     case BitstreamEntry::Error:
242       return error("Malformed block");
243 
244     case BitstreamEntry::SubBlock:
245       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
246         return readIdentificationBlock(Stream);
247 
248       // Ignore other sub-blocks.
249       if (Error Err = Stream.SkipBlock())
250         return std::move(Err);
251       continue;
252     case BitstreamEntry::Record:
253       if (Error E = Stream.skipRecord(Entry.ID).takeError())
254         return std::move(E);
255       continue;
256     }
257   }
258 }
259 
260 static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
261   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
262     return std::move(Err);
263 
264   SmallVector<uint64_t, 64> Record;
265   // Read all the records for this module.
266 
267   while (true) {
268     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
269     if (!MaybeEntry)
270       return MaybeEntry.takeError();
271     BitstreamEntry Entry = MaybeEntry.get();
272 
273     switch (Entry.Kind) {
274     case BitstreamEntry::SubBlock: // Handled for us already.
275     case BitstreamEntry::Error:
276       return error("Malformed block");
277     case BitstreamEntry::EndBlock:
278       return false;
279     case BitstreamEntry::Record:
280       // The interesting case.
281       break;
282     }
283 
284     // Read a record.
285     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
286     if (!MaybeRecord)
287       return MaybeRecord.takeError();
288     switch (MaybeRecord.get()) {
289     default:
290       break; // Default behavior, ignore unknown content.
291     case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
292       std::string S;
293       if (convertToString(Record, 0, S))
294         return error("Invalid section name record");
295       // Check for the i386 and other (x86_64, ARM) conventions
296       if (S.find("__DATA,__objc_catlist") != std::string::npos ||
297           S.find("__OBJC,__category") != std::string::npos)
298         return true;
299       break;
300     }
301     }
302     Record.clear();
303   }
304   llvm_unreachable("Exit infinite loop");
305 }
306 
307 static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
308   // We expect a number of well-defined blocks, though we don't necessarily
309   // need to understand them all.
310   while (true) {
311     BitstreamEntry Entry;
312     if (Error E = Stream.advance().moveInto(Entry))
313       return std::move(E);
314 
315     switch (Entry.Kind) {
316     case BitstreamEntry::Error:
317       return error("Malformed block");
318     case BitstreamEntry::EndBlock:
319       return false;
320 
321     case BitstreamEntry::SubBlock:
322       if (Entry.ID == bitc::MODULE_BLOCK_ID)
323         return hasObjCCategoryInModule(Stream);
324 
325       // Ignore other sub-blocks.
326       if (Error Err = Stream.SkipBlock())
327         return std::move(Err);
328       continue;
329 
330     case BitstreamEntry::Record:
331       if (Error E = Stream.skipRecord(Entry.ID).takeError())
332         return std::move(E);
333       continue;
334     }
335   }
336 }
337 
338 static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
339   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
340     return std::move(Err);
341 
342   SmallVector<uint64_t, 64> Record;
343 
344   std::string Triple;
345 
346   // Read all the records for this module.
347   while (true) {
348     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
349     if (!MaybeEntry)
350       return MaybeEntry.takeError();
351     BitstreamEntry Entry = MaybeEntry.get();
352 
353     switch (Entry.Kind) {
354     case BitstreamEntry::SubBlock: // Handled for us already.
355     case BitstreamEntry::Error:
356       return error("Malformed block");
357     case BitstreamEntry::EndBlock:
358       return Triple;
359     case BitstreamEntry::Record:
360       // The interesting case.
361       break;
362     }
363 
364     // Read a record.
365     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
366     if (!MaybeRecord)
367       return MaybeRecord.takeError();
368     switch (MaybeRecord.get()) {
369     default: break;  // Default behavior, ignore unknown content.
370     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
371       std::string S;
372       if (convertToString(Record, 0, S))
373         return error("Invalid triple record");
374       Triple = S;
375       break;
376     }
377     }
378     Record.clear();
379   }
380   llvm_unreachable("Exit infinite loop");
381 }
382 
383 static Expected<std::string> readTriple(BitstreamCursor &Stream) {
384   // We expect a number of well-defined blocks, though we don't necessarily
385   // need to understand them all.
386   while (true) {
387     Expected<BitstreamEntry> MaybeEntry = Stream.advance();
388     if (!MaybeEntry)
389       return MaybeEntry.takeError();
390     BitstreamEntry Entry = MaybeEntry.get();
391 
392     switch (Entry.Kind) {
393     case BitstreamEntry::Error:
394       return error("Malformed block");
395     case BitstreamEntry::EndBlock:
396       return "";
397 
398     case BitstreamEntry::SubBlock:
399       if (Entry.ID == bitc::MODULE_BLOCK_ID)
400         return readModuleTriple(Stream);
401 
402       // Ignore other sub-blocks.
403       if (Error Err = Stream.SkipBlock())
404         return std::move(Err);
405       continue;
406 
407     case BitstreamEntry::Record:
408       if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
409         continue;
410       else
411         return Skipped.takeError();
412     }
413   }
414 }
415 
416 namespace {
417 
418 class BitcodeReaderBase {
419 protected:
420   BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
421       : Stream(std::move(Stream)), Strtab(Strtab) {
422     this->Stream.setBlockInfo(&BlockInfo);
423   }
424 
425   BitstreamBlockInfo BlockInfo;
426   BitstreamCursor Stream;
427   StringRef Strtab;
428 
429   /// In version 2 of the bitcode we store names of global values and comdats in
430   /// a string table rather than in the VST.
431   bool UseStrtab = false;
432 
433   Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
434 
435   /// If this module uses a string table, pop the reference to the string table
436   /// and return the referenced string and the rest of the record. Otherwise
437   /// just return the record itself.
438   std::pair<StringRef, ArrayRef<uint64_t>>
439   readNameFromStrtab(ArrayRef<uint64_t> Record);
440 
441   Error readBlockInfo();
442 
443   // Contains an arbitrary and optional string identifying the bitcode producer
444   std::string ProducerIdentification;
445 
446   Error error(const Twine &Message);
447 };
448 
449 } // end anonymous namespace
450 
451 Error BitcodeReaderBase::error(const Twine &Message) {
452   std::string FullMsg = Message.str();
453   if (!ProducerIdentification.empty())
454     FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
455                LLVM_VERSION_STRING "')";
456   return ::error(FullMsg);
457 }
458 
459 Expected<unsigned>
460 BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
461   if (Record.empty())
462     return error("Invalid version record");
463   unsigned ModuleVersion = Record[0];
464   if (ModuleVersion > 2)
465     return error("Invalid value");
466   UseStrtab = ModuleVersion >= 2;
467   return ModuleVersion;
468 }
469 
470 std::pair<StringRef, ArrayRef<uint64_t>>
471 BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
472   if (!UseStrtab)
473     return {"", Record};
474   // Invalid reference. Let the caller complain about the record being empty.
475   if (Record[0] + Record[1] > Strtab.size())
476     return {"", {}};
477   return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
478 }
479 
480 namespace {
481 
482 /// This represents a constant expression or constant aggregate using a custom
483 /// structure internal to the bitcode reader. Later, this structure will be
484 /// expanded by materializeValue() either into a constant expression/aggregate,
485 /// or into an instruction sequence at the point of use. This allows us to
486 /// upgrade bitcode using constant expressions even if this kind of constant
487 /// expression is no longer supported.
488 class BitcodeConstant final : public Value,
489                               TrailingObjects<BitcodeConstant, unsigned> {
490   friend TrailingObjects;
491 
492   // Value subclass ID: Pick largest possible value to avoid any clashes.
493   static constexpr uint8_t SubclassID = 255;
494 
495 public:
496   // Opcodes used for non-expressions. This includes constant aggregates
497   // (struct, array, vector) that might need expansion, as well as non-leaf
498   // constants that don't need expansion (no_cfi, dso_local, blockaddress),
499   // but still go through BitcodeConstant to avoid different uselist orders
500   // between the two cases.
501   static constexpr uint8_t ConstantStructOpcode = 255;
502   static constexpr uint8_t ConstantArrayOpcode = 254;
503   static constexpr uint8_t ConstantVectorOpcode = 253;
504   static constexpr uint8_t NoCFIOpcode = 252;
505   static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
506   static constexpr uint8_t BlockAddressOpcode = 250;
507   static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode;
508 
509   // Separate struct to make passing different number of parameters to
510   // BitcodeConstant::create() more convenient.
511   struct ExtraInfo {
512     uint8_t Opcode;
513     uint8_t Flags;
514     unsigned Extra;
515     Type *SrcElemTy;
516 
517     ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0,
518               Type *SrcElemTy = nullptr)
519         : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {}
520   };
521 
522   uint8_t Opcode;
523   uint8_t Flags;
524   unsigned NumOperands;
525   unsigned Extra;  // GEP inrange index or blockaddress BB id.
526   Type *SrcElemTy; // GEP source element type.
527 
528 private:
529   BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
530       : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
531         NumOperands(OpIDs.size()), Extra(Info.Extra),
532         SrcElemTy(Info.SrcElemTy) {
533     std::uninitialized_copy(OpIDs.begin(), OpIDs.end(),
534                             getTrailingObjects<unsigned>());
535   }
536 
537   BitcodeConstant &operator=(const BitcodeConstant &) = delete;
538 
539 public:
540   static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
541                                  const ExtraInfo &Info,
542                                  ArrayRef<unsigned> OpIDs) {
543     void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
544                            alignof(BitcodeConstant));
545     return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
546   }
547 
548   static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
549 
550   ArrayRef<unsigned> getOperandIDs() const {
551     return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
552   }
553 
554   std::optional<unsigned> getInRangeIndex() const {
555     assert(Opcode == Instruction::GetElementPtr);
556     if (Extra == (unsigned)-1)
557       return std::nullopt;
558     return Extra;
559   }
560 
561   const char *getOpcodeName() const {
562     return Instruction::getOpcodeName(Opcode);
563   }
564 };
565 
566 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
567   LLVMContext &Context;
568   Module *TheModule = nullptr;
569   // Next offset to start scanning for lazy parsing of function bodies.
570   uint64_t NextUnreadBit = 0;
571   // Last function offset found in the VST.
572   uint64_t LastFunctionBlockBit = 0;
573   bool SeenValueSymbolTable = false;
574   uint64_t VSTOffset = 0;
575 
576   std::vector<std::string> SectionTable;
577   std::vector<std::string> GCTable;
578 
579   std::vector<Type *> TypeList;
580   /// Track type IDs of contained types. Order is the same as the contained
581   /// types of a Type*. This is used during upgrades of typed pointer IR in
582   /// opaque pointer mode.
583   DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
584   /// In some cases, we need to create a type ID for a type that was not
585   /// explicitly encoded in the bitcode, or we don't know about at the current
586   /// point. For example, a global may explicitly encode the value type ID, but
587   /// not have a type ID for the pointer to value type, for which we create a
588   /// virtual type ID instead. This map stores the new type ID that was created
589   /// for the given pair of Type and contained type ID.
590   DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
591   DenseMap<Function *, unsigned> FunctionTypeIDs;
592   /// Allocator for BitcodeConstants. This should come before ValueList,
593   /// because the ValueList might hold ValueHandles to these constants, so
594   /// ValueList must be destroyed before Alloc.
595   BumpPtrAllocator Alloc;
596   BitcodeReaderValueList ValueList;
597   std::optional<MetadataLoader> MDLoader;
598   std::vector<Comdat *> ComdatList;
599   DenseSet<GlobalObject *> ImplicitComdatObjects;
600   SmallVector<Instruction *, 64> InstructionList;
601 
602   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
603   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
604 
605   struct FunctionOperandInfo {
606     Function *F;
607     unsigned PersonalityFn;
608     unsigned Prefix;
609     unsigned Prologue;
610   };
611   std::vector<FunctionOperandInfo> FunctionOperands;
612 
613   /// The set of attributes by index.  Index zero in the file is for null, and
614   /// is thus not represented here.  As such all indices are off by one.
615   std::vector<AttributeList> MAttributes;
616 
617   /// The set of attribute groups.
618   std::map<unsigned, AttributeList> MAttributeGroups;
619 
620   /// While parsing a function body, this is a list of the basic blocks for the
621   /// function.
622   std::vector<BasicBlock*> FunctionBBs;
623 
624   // When reading the module header, this list is populated with functions that
625   // have bodies later in the file.
626   std::vector<Function*> FunctionsWithBodies;
627 
628   // When intrinsic functions are encountered which require upgrading they are
629   // stored here with their replacement function.
630   using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
631   UpdatedIntrinsicMap UpgradedIntrinsics;
632 
633   // Several operations happen after the module header has been read, but
634   // before function bodies are processed. This keeps track of whether
635   // we've done this yet.
636   bool SeenFirstFunctionBody = false;
637 
638   /// When function bodies are initially scanned, this map contains info about
639   /// where to find deferred function body in the stream.
640   DenseMap<Function*, uint64_t> DeferredFunctionInfo;
641 
642   /// When Metadata block is initially scanned when parsing the module, we may
643   /// choose to defer parsing of the metadata. This vector contains info about
644   /// which Metadata blocks are deferred.
645   std::vector<uint64_t> DeferredMetadataInfo;
646 
647   /// These are basic blocks forward-referenced by block addresses.  They are
648   /// inserted lazily into functions when they're loaded.  The basic block ID is
649   /// its index into the vector.
650   DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
651   std::deque<Function *> BasicBlockFwdRefQueue;
652 
653   /// These are Functions that contain BlockAddresses which refer a different
654   /// Function. When parsing the different Function, queue Functions that refer
655   /// to the different Function. Those Functions must be materialized in order
656   /// to resolve their BlockAddress constants before the different Function
657   /// gets moved into another Module.
658   std::vector<Function *> BackwardRefFunctions;
659 
660   /// Indicates that we are using a new encoding for instruction operands where
661   /// most operands in the current FUNCTION_BLOCK are encoded relative to the
662   /// instruction number, for a more compact encoding.  Some instruction
663   /// operands are not relative to the instruction ID: basic block numbers, and
664   /// types. Once the old style function blocks have been phased out, we would
665   /// not need this flag.
666   bool UseRelativeIDs = false;
667 
668   /// True if all functions will be materialized, negating the need to process
669   /// (e.g.) blockaddress forward references.
670   bool WillMaterializeAllForwardRefs = false;
671 
672   bool StripDebugInfo = false;
673   TBAAVerifier TBAAVerifyHelper;
674 
675   std::vector<std::string> BundleTags;
676   SmallVector<SyncScope::ID, 8> SSIDs;
677 
678   std::optional<ValueTypeCallbackTy> ValueTypeCallback;
679 
680 public:
681   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
682                 StringRef ProducerIdentification, LLVMContext &Context);
683 
684   Error materializeForwardReferencedFunctions();
685 
686   Error materialize(GlobalValue *GV) override;
687   Error materializeModule() override;
688   std::vector<StructType *> getIdentifiedStructTypes() const override;
689 
690   /// Main interface to parsing a bitcode buffer.
691   /// \returns true if an error occurred.
692   Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
693                          bool IsImporting, ParserCallbacks Callbacks = {});
694 
695   static uint64_t decodeSignRotatedValue(uint64_t V);
696 
697   /// Materialize any deferred Metadata block.
698   Error materializeMetadata() override;
699 
700   void setStripDebugInfo() override;
701 
702 private:
703   std::vector<StructType *> IdentifiedStructTypes;
704   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
705   StructType *createIdentifiedStructType(LLVMContext &Context);
706 
707   static constexpr unsigned InvalidTypeID = ~0u;
708 
709   Type *getTypeByID(unsigned ID);
710   Type *getPtrElementTypeByID(unsigned ID);
711   unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
712   unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
713 
714   void callValueTypeCallback(Value *F, unsigned TypeID);
715   Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
716   Expected<Constant *> getValueForInitializer(unsigned ID);
717 
718   Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
719                         BasicBlock *ConstExprInsertBB) {
720     if (Ty && Ty->isMetadataTy())
721       return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
722     return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
723   }
724 
725   Metadata *getFnMetadataByID(unsigned ID) {
726     return MDLoader->getMetadataFwdRefOrLoad(ID);
727   }
728 
729   BasicBlock *getBasicBlock(unsigned ID) const {
730     if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
731     return FunctionBBs[ID];
732   }
733 
734   AttributeList getAttributes(unsigned i) const {
735     if (i-1 < MAttributes.size())
736       return MAttributes[i-1];
737     return AttributeList();
738   }
739 
740   /// Read a value/type pair out of the specified record from slot 'Slot'.
741   /// Increment Slot past the number of slots used in the record. Return true on
742   /// failure.
743   bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
744                         unsigned InstNum, Value *&ResVal, unsigned &TypeID,
745                         BasicBlock *ConstExprInsertBB) {
746     if (Slot == Record.size()) return true;
747     unsigned ValNo = (unsigned)Record[Slot++];
748     // Adjust the ValNo, if it was encoded relative to the InstNum.
749     if (UseRelativeIDs)
750       ValNo = InstNum - ValNo;
751     if (ValNo < InstNum) {
752       // If this is not a forward reference, just return the value we already
753       // have.
754       TypeID = ValueList.getTypeID(ValNo);
755       ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
756       assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
757              "Incorrect type ID stored for value");
758       return ResVal == nullptr;
759     }
760     if (Slot == Record.size())
761       return true;
762 
763     TypeID = (unsigned)Record[Slot++];
764     ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
765                             ConstExprInsertBB);
766     return ResVal == nullptr;
767   }
768 
769   /// Read a value out of the specified record from slot 'Slot'. Increment Slot
770   /// past the number of slots used by the value in the record. Return true if
771   /// there is an error.
772   bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
773                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
774                 BasicBlock *ConstExprInsertBB) {
775     if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
776       return true;
777     // All values currently take a single record slot.
778     ++Slot;
779     return false;
780   }
781 
782   /// Like popValue, but does not increment the Slot number.
783   bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
784                 unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
785                 BasicBlock *ConstExprInsertBB) {
786     ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
787     return ResVal == nullptr;
788   }
789 
790   /// Version of getValue that returns ResVal directly, or 0 if there is an
791   /// error.
792   Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
793                   unsigned InstNum, Type *Ty, unsigned TyID,
794                   BasicBlock *ConstExprInsertBB) {
795     if (Slot == Record.size()) return nullptr;
796     unsigned ValNo = (unsigned)Record[Slot];
797     // Adjust the ValNo, if it was encoded relative to the InstNum.
798     if (UseRelativeIDs)
799       ValNo = InstNum - ValNo;
800     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
801   }
802 
803   /// Like getValue, but decodes signed VBRs.
804   Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
805                         unsigned InstNum, Type *Ty, unsigned TyID,
806                         BasicBlock *ConstExprInsertBB) {
807     if (Slot == Record.size()) return nullptr;
808     unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
809     // Adjust the ValNo, if it was encoded relative to the InstNum.
810     if (UseRelativeIDs)
811       ValNo = InstNum - ValNo;
812     return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
813   }
814 
815   /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
816   /// corresponding argument's pointee type. Also upgrades intrinsics that now
817   /// require an elementtype attribute.
818   Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
819 
820   /// Converts alignment exponent (i.e. power of two (or zero)) to the
821   /// corresponding alignment to use. If alignment is too large, returns
822   /// a corresponding error code.
823   Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
824   Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
825   Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
826                     ParserCallbacks Callbacks = {});
827 
828   Error parseComdatRecord(ArrayRef<uint64_t> Record);
829   Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
830   Error parseFunctionRecord(ArrayRef<uint64_t> Record);
831   Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
832                                         ArrayRef<uint64_t> Record);
833 
834   Error parseAttributeBlock();
835   Error parseAttributeGroupBlock();
836   Error parseTypeTable();
837   Error parseTypeTableBody();
838   Error parseOperandBundleTags();
839   Error parseSyncScopeNames();
840 
841   Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
842                                 unsigned NameIndex, Triple &TT);
843   void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
844                                ArrayRef<uint64_t> Record);
845   Error parseValueSymbolTable(uint64_t Offset = 0);
846   Error parseGlobalValueSymbolTable();
847   Error parseConstants();
848   Error rememberAndSkipFunctionBodies();
849   Error rememberAndSkipFunctionBody();
850   /// Save the positions of the Metadata blocks and skip parsing the blocks.
851   Error rememberAndSkipMetadata();
852   Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
853   Error parseFunctionBody(Function *F);
854   Error globalCleanup();
855   Error resolveGlobalAndIndirectSymbolInits();
856   Error parseUseLists();
857   Error findFunctionInStream(
858       Function *F,
859       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
860 
861   SyncScope::ID getDecodedSyncScopeID(unsigned Val);
862 };
863 
864 /// Class to manage reading and parsing function summary index bitcode
865 /// files/sections.
866 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
867   /// The module index built during parsing.
868   ModuleSummaryIndex &TheIndex;
869 
870   /// Indicates whether we have encountered a global value summary section
871   /// yet during parsing.
872   bool SeenGlobalValSummary = false;
873 
874   /// Indicates whether we have already parsed the VST, used for error checking.
875   bool SeenValueSymbolTable = false;
876 
877   /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
878   /// Used to enable on-demand parsing of the VST.
879   uint64_t VSTOffset = 0;
880 
881   // Map to save ValueId to ValueInfo association that was recorded in the
882   // ValueSymbolTable. It is used after the VST is parsed to convert
883   // call graph edges read from the function summary from referencing
884   // callees by their ValueId to using the ValueInfo instead, which is how
885   // they are recorded in the summary index being built.
886   // We save a GUID which refers to the same global as the ValueInfo, but
887   // ignoring the linkage, i.e. for values other than local linkage they are
888   // identical (this is the second tuple member).
889   // The third tuple member is the real GUID of the ValueInfo.
890   DenseMap<unsigned,
891            std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>>
892       ValueIdToValueInfoMap;
893 
894   /// Map populated during module path string table parsing, from the
895   /// module ID to a string reference owned by the index's module
896   /// path string table, used to correlate with combined index
897   /// summary records.
898   DenseMap<uint64_t, StringRef> ModuleIdMap;
899 
900   /// Original source file name recorded in a bitcode record.
901   std::string SourceFileName;
902 
903   /// The string identifier given to this module by the client, normally the
904   /// path to the bitcode file.
905   StringRef ModulePath;
906 
907   /// Callback to ask whether a symbol is the prevailing copy when invoked
908   /// during combined index building.
909   std::function<bool(GlobalValue::GUID)> IsPrevailing;
910 
911   /// Saves the stack ids from the STACK_IDS record to consult when adding stack
912   /// ids from the lists in the callsite and alloc entries to the index.
913   std::vector<uint64_t> StackIds;
914 
915 public:
916   ModuleSummaryIndexBitcodeReader(
917       BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
918       StringRef ModulePath,
919       std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
920 
921   Error parseModule();
922 
923 private:
924   void setValueGUID(uint64_t ValueID, StringRef ValueName,
925                     GlobalValue::LinkageTypes Linkage,
926                     StringRef SourceFileName);
927   Error parseValueSymbolTable(
928       uint64_t Offset,
929       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
930   std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
931   std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
932                                                     bool IsOldProfileFormat,
933                                                     bool HasProfile,
934                                                     bool HasRelBF);
935   Error parseEntireSummary(unsigned ID);
936   Error parseModuleStringTable();
937   void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
938   void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
939                                        TypeIdCompatibleVtableInfo &TypeId);
940   std::vector<FunctionSummary::ParamAccess>
941   parseParamAccesses(ArrayRef<uint64_t> Record);
942 
943   template <bool AllowNullValueInfo = false>
944   std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
945   getValueInfoFromValueId(unsigned ValueId);
946 
947   void addThisModule();
948   ModuleSummaryIndex::ModuleInfo *getThisModule();
949 };
950 
951 } // end anonymous namespace
952 
953 std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
954                                                     Error Err) {
955   if (Err) {
956     std::error_code EC;
957     handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
958       EC = EIB.convertToErrorCode();
959       Ctx.emitError(EIB.message());
960     });
961     return EC;
962   }
963   return std::error_code();
964 }
965 
966 BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
967                              StringRef ProducerIdentification,
968                              LLVMContext &Context)
969     : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
970       ValueList(this->Stream.SizeInBytes(),
971                 [this](unsigned ValID, BasicBlock *InsertBB) {
972                   return materializeValue(ValID, InsertBB);
973                 }) {
974   this->ProducerIdentification = std::string(ProducerIdentification);
975 }
976 
977 Error BitcodeReader::materializeForwardReferencedFunctions() {
978   if (WillMaterializeAllForwardRefs)
979     return Error::success();
980 
981   // Prevent recursion.
982   WillMaterializeAllForwardRefs = true;
983 
984   while (!BasicBlockFwdRefQueue.empty()) {
985     Function *F = BasicBlockFwdRefQueue.front();
986     BasicBlockFwdRefQueue.pop_front();
987     assert(F && "Expected valid function");
988     if (!BasicBlockFwdRefs.count(F))
989       // Already materialized.
990       continue;
991 
992     // Check for a function that isn't materializable to prevent an infinite
993     // loop.  When parsing a blockaddress stored in a global variable, there
994     // isn't a trivial way to check if a function will have a body without a
995     // linear search through FunctionsWithBodies, so just check it here.
996     if (!F->isMaterializable())
997       return error("Never resolved function from blockaddress");
998 
999     // Try to materialize F.
1000     if (Error Err = materialize(F))
1001       return Err;
1002   }
1003   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
1004 
1005   for (Function *F : BackwardRefFunctions)
1006     if (Error Err = materialize(F))
1007       return Err;
1008   BackwardRefFunctions.clear();
1009 
1010   // Reset state.
1011   WillMaterializeAllForwardRefs = false;
1012   return Error::success();
1013 }
1014 
1015 //===----------------------------------------------------------------------===//
1016 //  Helper functions to implement forward reference resolution, etc.
1017 //===----------------------------------------------------------------------===//
1018 
1019 static bool hasImplicitComdat(size_t Val) {
1020   switch (Val) {
1021   default:
1022     return false;
1023   case 1:  // Old WeakAnyLinkage
1024   case 4:  // Old LinkOnceAnyLinkage
1025   case 10: // Old WeakODRLinkage
1026   case 11: // Old LinkOnceODRLinkage
1027     return true;
1028   }
1029 }
1030 
1031 static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
1032   switch (Val) {
1033   default: // Map unknown/new linkages to external
1034   case 0:
1035     return GlobalValue::ExternalLinkage;
1036   case 2:
1037     return GlobalValue::AppendingLinkage;
1038   case 3:
1039     return GlobalValue::InternalLinkage;
1040   case 5:
1041     return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
1042   case 6:
1043     return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
1044   case 7:
1045     return GlobalValue::ExternalWeakLinkage;
1046   case 8:
1047     return GlobalValue::CommonLinkage;
1048   case 9:
1049     return GlobalValue::PrivateLinkage;
1050   case 12:
1051     return GlobalValue::AvailableExternallyLinkage;
1052   case 13:
1053     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
1054   case 14:
1055     return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
1056   case 15:
1057     return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
1058   case 1: // Old value with implicit comdat.
1059   case 16:
1060     return GlobalValue::WeakAnyLinkage;
1061   case 10: // Old value with implicit comdat.
1062   case 17:
1063     return GlobalValue::WeakODRLinkage;
1064   case 4: // Old value with implicit comdat.
1065   case 18:
1066     return GlobalValue::LinkOnceAnyLinkage;
1067   case 11: // Old value with implicit comdat.
1068   case 19:
1069     return GlobalValue::LinkOnceODRLinkage;
1070   }
1071 }
1072 
1073 static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
1074   FunctionSummary::FFlags Flags;
1075   Flags.ReadNone = RawFlags & 0x1;
1076   Flags.ReadOnly = (RawFlags >> 1) & 0x1;
1077   Flags.NoRecurse = (RawFlags >> 2) & 0x1;
1078   Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
1079   Flags.NoInline = (RawFlags >> 4) & 0x1;
1080   Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
1081   Flags.NoUnwind = (RawFlags >> 6) & 0x1;
1082   Flags.MayThrow = (RawFlags >> 7) & 0x1;
1083   Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
1084   Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
1085   return Flags;
1086 }
1087 
1088 // Decode the flags for GlobalValue in the summary. The bits for each attribute:
1089 //
1090 // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
1091 // visibility: [8, 10).
1092 static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
1093                                                             uint64_t Version) {
1094   // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
1095   // like getDecodedLinkage() above. Any future change to the linkage enum and
1096   // to getDecodedLinkage() will need to be taken into account here as above.
1097   auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
1098   auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
1099   RawFlags = RawFlags >> 4;
1100   bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
1101   // The Live flag wasn't introduced until version 3. For dead stripping
1102   // to work correctly on earlier versions, we must conservatively treat all
1103   // values as live.
1104   bool Live = (RawFlags & 0x2) || Version < 3;
1105   bool Local = (RawFlags & 0x4);
1106   bool AutoHide = (RawFlags & 0x8);
1107 
1108   return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
1109                                      Live, Local, AutoHide);
1110 }
1111 
1112 // Decode the flags for GlobalVariable in the summary
1113 static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
1114   return GlobalVarSummary::GVarFlags(
1115       (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
1116       (RawFlags & 0x4) ? true : false,
1117       (GlobalObject::VCallVisibility)(RawFlags >> 3));
1118 }
1119 
1120 static std::pair<CalleeInfo::HotnessType, bool>
1121 getDecodedHotnessCallEdgeInfo(uint64_t RawFlags) {
1122   CalleeInfo::HotnessType Hotness =
1123       static_cast<CalleeInfo::HotnessType>(RawFlags & 0x7); // 3 bits
1124   bool HasTailCall = (RawFlags & 0x8);                      // 1 bit
1125   return {Hotness, HasTailCall};
1126 }
1127 
1128 static void getDecodedRelBFCallEdgeInfo(uint64_t RawFlags, uint64_t &RelBF,
1129                                         bool &HasTailCall) {
1130   static constexpr uint64_t RelBlockFreqMask =
1131       (1 << CalleeInfo::RelBlockFreqBits) - 1;
1132   RelBF = RawFlags & RelBlockFreqMask; // RelBlockFreqBits bits
1133   HasTailCall = (RawFlags & (1 << CalleeInfo::RelBlockFreqBits)); // 1 bit
1134 }
1135 
1136 static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
1137   switch (Val) {
1138   default: // Map unknown visibilities to default.
1139   case 0: return GlobalValue::DefaultVisibility;
1140   case 1: return GlobalValue::HiddenVisibility;
1141   case 2: return GlobalValue::ProtectedVisibility;
1142   }
1143 }
1144 
1145 static GlobalValue::DLLStorageClassTypes
1146 getDecodedDLLStorageClass(unsigned Val) {
1147   switch (Val) {
1148   default: // Map unknown values to default.
1149   case 0: return GlobalValue::DefaultStorageClass;
1150   case 1: return GlobalValue::DLLImportStorageClass;
1151   case 2: return GlobalValue::DLLExportStorageClass;
1152   }
1153 }
1154 
1155 static bool getDecodedDSOLocal(unsigned Val) {
1156   switch(Val) {
1157   default: // Map unknown values to preemptable.
1158   case 0:  return false;
1159   case 1:  return true;
1160   }
1161 }
1162 
1163 static std::optional<CodeModel::Model> getDecodedCodeModel(unsigned Val) {
1164   switch (Val) {
1165   case 1:
1166     return CodeModel::Tiny;
1167   case 2:
1168     return CodeModel::Small;
1169   case 3:
1170     return CodeModel::Kernel;
1171   case 4:
1172     return CodeModel::Medium;
1173   case 5:
1174     return CodeModel::Large;
1175   }
1176 
1177   return {};
1178 }
1179 
1180 static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
1181   switch (Val) {
1182     case 0: return GlobalVariable::NotThreadLocal;
1183     default: // Map unknown non-zero value to general dynamic.
1184     case 1: return GlobalVariable::GeneralDynamicTLSModel;
1185     case 2: return GlobalVariable::LocalDynamicTLSModel;
1186     case 3: return GlobalVariable::InitialExecTLSModel;
1187     case 4: return GlobalVariable::LocalExecTLSModel;
1188   }
1189 }
1190 
1191 static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
1192   switch (Val) {
1193     default: // Map unknown to UnnamedAddr::None.
1194     case 0: return GlobalVariable::UnnamedAddr::None;
1195     case 1: return GlobalVariable::UnnamedAddr::Global;
1196     case 2: return GlobalVariable::UnnamedAddr::Local;
1197   }
1198 }
1199 
1200 static int getDecodedCastOpcode(unsigned Val) {
1201   switch (Val) {
1202   default: return -1;
1203   case bitc::CAST_TRUNC   : return Instruction::Trunc;
1204   case bitc::CAST_ZEXT    : return Instruction::ZExt;
1205   case bitc::CAST_SEXT    : return Instruction::SExt;
1206   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
1207   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
1208   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
1209   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
1210   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
1211   case bitc::CAST_FPEXT   : return Instruction::FPExt;
1212   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
1213   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
1214   case bitc::CAST_BITCAST : return Instruction::BitCast;
1215   case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
1216   }
1217 }
1218 
1219 static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
1220   bool IsFP = Ty->isFPOrFPVectorTy();
1221   // UnOps are only valid for int/fp or vector of int/fp types
1222   if (!IsFP && !Ty->isIntOrIntVectorTy())
1223     return -1;
1224 
1225   switch (Val) {
1226   default:
1227     return -1;
1228   case bitc::UNOP_FNEG:
1229     return IsFP ? Instruction::FNeg : -1;
1230   }
1231 }
1232 
1233 static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
1234   bool IsFP = Ty->isFPOrFPVectorTy();
1235   // BinOps are only valid for int/fp or vector of int/fp types
1236   if (!IsFP && !Ty->isIntOrIntVectorTy())
1237     return -1;
1238 
1239   switch (Val) {
1240   default:
1241     return -1;
1242   case bitc::BINOP_ADD:
1243     return IsFP ? Instruction::FAdd : Instruction::Add;
1244   case bitc::BINOP_SUB:
1245     return IsFP ? Instruction::FSub : Instruction::Sub;
1246   case bitc::BINOP_MUL:
1247     return IsFP ? Instruction::FMul : Instruction::Mul;
1248   case bitc::BINOP_UDIV:
1249     return IsFP ? -1 : Instruction::UDiv;
1250   case bitc::BINOP_SDIV:
1251     return IsFP ? Instruction::FDiv : Instruction::SDiv;
1252   case bitc::BINOP_UREM:
1253     return IsFP ? -1 : Instruction::URem;
1254   case bitc::BINOP_SREM:
1255     return IsFP ? Instruction::FRem : Instruction::SRem;
1256   case bitc::BINOP_SHL:
1257     return IsFP ? -1 : Instruction::Shl;
1258   case bitc::BINOP_LSHR:
1259     return IsFP ? -1 : Instruction::LShr;
1260   case bitc::BINOP_ASHR:
1261     return IsFP ? -1 : Instruction::AShr;
1262   case bitc::BINOP_AND:
1263     return IsFP ? -1 : Instruction::And;
1264   case bitc::BINOP_OR:
1265     return IsFP ? -1 : Instruction::Or;
1266   case bitc::BINOP_XOR:
1267     return IsFP ? -1 : Instruction::Xor;
1268   }
1269 }
1270 
1271 static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
1272   switch (Val) {
1273   default: return AtomicRMWInst::BAD_BINOP;
1274   case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
1275   case bitc::RMW_ADD: return AtomicRMWInst::Add;
1276   case bitc::RMW_SUB: return AtomicRMWInst::Sub;
1277   case bitc::RMW_AND: return AtomicRMWInst::And;
1278   case bitc::RMW_NAND: return AtomicRMWInst::Nand;
1279   case bitc::RMW_OR: return AtomicRMWInst::Or;
1280   case bitc::RMW_XOR: return AtomicRMWInst::Xor;
1281   case bitc::RMW_MAX: return AtomicRMWInst::Max;
1282   case bitc::RMW_MIN: return AtomicRMWInst::Min;
1283   case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
1284   case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
1285   case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
1286   case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
1287   case bitc::RMW_FMAX: return AtomicRMWInst::FMax;
1288   case bitc::RMW_FMIN: return AtomicRMWInst::FMin;
1289   case bitc::RMW_UINC_WRAP:
1290     return AtomicRMWInst::UIncWrap;
1291   case bitc::RMW_UDEC_WRAP:
1292     return AtomicRMWInst::UDecWrap;
1293   }
1294 }
1295 
1296 static AtomicOrdering getDecodedOrdering(unsigned Val) {
1297   switch (Val) {
1298   case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
1299   case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
1300   case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
1301   case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
1302   case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
1303   case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
1304   default: // Map unknown orderings to sequentially-consistent.
1305   case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
1306   }
1307 }
1308 
1309 static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
1310   switch (Val) {
1311   default: // Map unknown selection kinds to any.
1312   case bitc::COMDAT_SELECTION_KIND_ANY:
1313     return Comdat::Any;
1314   case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
1315     return Comdat::ExactMatch;
1316   case bitc::COMDAT_SELECTION_KIND_LARGEST:
1317     return Comdat::Largest;
1318   case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
1319     return Comdat::NoDeduplicate;
1320   case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
1321     return Comdat::SameSize;
1322   }
1323 }
1324 
1325 static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
1326   FastMathFlags FMF;
1327   if (0 != (Val & bitc::UnsafeAlgebra))
1328     FMF.setFast();
1329   if (0 != (Val & bitc::AllowReassoc))
1330     FMF.setAllowReassoc();
1331   if (0 != (Val & bitc::NoNaNs))
1332     FMF.setNoNaNs();
1333   if (0 != (Val & bitc::NoInfs))
1334     FMF.setNoInfs();
1335   if (0 != (Val & bitc::NoSignedZeros))
1336     FMF.setNoSignedZeros();
1337   if (0 != (Val & bitc::AllowReciprocal))
1338     FMF.setAllowReciprocal();
1339   if (0 != (Val & bitc::AllowContract))
1340     FMF.setAllowContract(true);
1341   if (0 != (Val & bitc::ApproxFunc))
1342     FMF.setApproxFunc();
1343   return FMF;
1344 }
1345 
1346 static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
1347   // A GlobalValue with local linkage cannot have a DLL storage class.
1348   if (GV->hasLocalLinkage())
1349     return;
1350   switch (Val) {
1351   case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
1352   case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
1353   }
1354 }
1355 
1356 Type *BitcodeReader::getTypeByID(unsigned ID) {
1357   // The type table size is always specified correctly.
1358   if (ID >= TypeList.size())
1359     return nullptr;
1360 
1361   if (Type *Ty = TypeList[ID])
1362     return Ty;
1363 
1364   // If we have a forward reference, the only possible case is when it is to a
1365   // named struct.  Just create a placeholder for now.
1366   return TypeList[ID] = createIdentifiedStructType(Context);
1367 }
1368 
1369 unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
1370   auto It = ContainedTypeIDs.find(ID);
1371   if (It == ContainedTypeIDs.end())
1372     return InvalidTypeID;
1373 
1374   if (Idx >= It->second.size())
1375     return InvalidTypeID;
1376 
1377   return It->second[Idx];
1378 }
1379 
1380 Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
1381   if (ID >= TypeList.size())
1382     return nullptr;
1383 
1384   Type *Ty = TypeList[ID];
1385   if (!Ty->isPointerTy())
1386     return nullptr;
1387 
1388   return getTypeByID(getContainedTypeID(ID, 0));
1389 }
1390 
1391 unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
1392                                          ArrayRef<unsigned> ChildTypeIDs) {
1393   unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
1394   auto CacheKey = std::make_pair(Ty, ChildTypeID);
1395   auto It = VirtualTypeIDs.find(CacheKey);
1396   if (It != VirtualTypeIDs.end()) {
1397     // The cmpxchg return value is the only place we need more than one
1398     // contained type ID, however the second one will always be the same (i1),
1399     // so we don't need to include it in the cache key. This asserts that the
1400     // contained types are indeed as expected and there are no collisions.
1401     assert((ChildTypeIDs.empty() ||
1402             ContainedTypeIDs[It->second] == ChildTypeIDs) &&
1403            "Incorrect cached contained type IDs");
1404     return It->second;
1405   }
1406 
1407   unsigned TypeID = TypeList.size();
1408   TypeList.push_back(Ty);
1409   if (!ChildTypeIDs.empty())
1410     append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
1411   VirtualTypeIDs.insert({CacheKey, TypeID});
1412   return TypeID;
1413 }
1414 
1415 static bool isConstExprSupported(const BitcodeConstant *BC) {
1416   uint8_t Opcode = BC->Opcode;
1417 
1418   // These are not real constant expressions, always consider them supported.
1419   if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
1420     return true;
1421 
1422   // If -expand-constant-exprs is set, we want to consider all expressions
1423   // as unsupported.
1424   if (ExpandConstantExprs)
1425     return false;
1426 
1427   if (Instruction::isBinaryOp(Opcode))
1428     return ConstantExpr::isSupportedBinOp(Opcode);
1429 
1430   if (Instruction::isCast(Opcode))
1431     return ConstantExpr::isSupportedCastOp(Opcode);
1432 
1433   if (Opcode == Instruction::GetElementPtr)
1434     return ConstantExpr::isSupportedGetElementPtr(BC->SrcElemTy);
1435 
1436   switch (Opcode) {
1437   case Instruction::FNeg:
1438   case Instruction::Select:
1439     return false;
1440   default:
1441     return true;
1442   }
1443 }
1444 
1445 Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
1446                                                   BasicBlock *InsertBB) {
1447   // Quickly handle the case where there is no BitcodeConstant to resolve.
1448   if (StartValID < ValueList.size() && ValueList[StartValID] &&
1449       !isa<BitcodeConstant>(ValueList[StartValID]))
1450     return ValueList[StartValID];
1451 
1452   SmallDenseMap<unsigned, Value *> MaterializedValues;
1453   SmallVector<unsigned> Worklist;
1454   Worklist.push_back(StartValID);
1455   while (!Worklist.empty()) {
1456     unsigned ValID = Worklist.back();
1457     if (MaterializedValues.count(ValID)) {
1458       // Duplicate expression that was already handled.
1459       Worklist.pop_back();
1460       continue;
1461     }
1462 
1463     if (ValID >= ValueList.size() || !ValueList[ValID])
1464       return error("Invalid value ID");
1465 
1466     Value *V = ValueList[ValID];
1467     auto *BC = dyn_cast<BitcodeConstant>(V);
1468     if (!BC) {
1469       MaterializedValues.insert({ValID, V});
1470       Worklist.pop_back();
1471       continue;
1472     }
1473 
1474     // Iterate in reverse, so values will get popped from the worklist in
1475     // expected order.
1476     SmallVector<Value *> Ops;
1477     for (unsigned OpID : reverse(BC->getOperandIDs())) {
1478       auto It = MaterializedValues.find(OpID);
1479       if (It != MaterializedValues.end())
1480         Ops.push_back(It->second);
1481       else
1482         Worklist.push_back(OpID);
1483     }
1484 
1485     // Some expressions have not been resolved yet, handle them first and then
1486     // revisit this one.
1487     if (Ops.size() != BC->getOperandIDs().size())
1488       continue;
1489     std::reverse(Ops.begin(), Ops.end());
1490 
1491     SmallVector<Constant *> ConstOps;
1492     for (Value *Op : Ops)
1493       if (auto *C = dyn_cast<Constant>(Op))
1494         ConstOps.push_back(C);
1495 
1496     // Materialize as constant expression if possible.
1497     if (isConstExprSupported(BC) && ConstOps.size() == Ops.size()) {
1498       Constant *C;
1499       if (Instruction::isCast(BC->Opcode)) {
1500         C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
1501         if (!C)
1502           C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
1503       } else if (Instruction::isBinaryOp(BC->Opcode)) {
1504         C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
1505       } else {
1506         switch (BC->Opcode) {
1507         case BitcodeConstant::NoCFIOpcode: {
1508           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1509           if (!GV)
1510             return error("no_cfi operand must be GlobalValue");
1511           C = NoCFIValue::get(GV);
1512           break;
1513         }
1514         case BitcodeConstant::DSOLocalEquivalentOpcode: {
1515           auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
1516           if (!GV)
1517             return error("dso_local operand must be GlobalValue");
1518           C = DSOLocalEquivalent::get(GV);
1519           break;
1520         }
1521         case BitcodeConstant::BlockAddressOpcode: {
1522           Function *Fn = dyn_cast<Function>(ConstOps[0]);
1523           if (!Fn)
1524             return error("blockaddress operand must be a function");
1525 
1526           // If the function is already parsed we can insert the block address
1527           // right away.
1528           BasicBlock *BB;
1529           unsigned BBID = BC->Extra;
1530           if (!BBID)
1531             // Invalid reference to entry block.
1532             return error("Invalid ID");
1533           if (!Fn->empty()) {
1534             Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1535             for (size_t I = 0, E = BBID; I != E; ++I) {
1536               if (BBI == BBE)
1537                 return error("Invalid ID");
1538               ++BBI;
1539             }
1540             BB = &*BBI;
1541           } else {
1542             // Otherwise insert a placeholder and remember it so it can be
1543             // inserted when the function is parsed.
1544             auto &FwdBBs = BasicBlockFwdRefs[Fn];
1545             if (FwdBBs.empty())
1546               BasicBlockFwdRefQueue.push_back(Fn);
1547             if (FwdBBs.size() < BBID + 1)
1548               FwdBBs.resize(BBID + 1);
1549             if (!FwdBBs[BBID])
1550               FwdBBs[BBID] = BasicBlock::Create(Context);
1551             BB = FwdBBs[BBID];
1552           }
1553           C = BlockAddress::get(Fn, BB);
1554           break;
1555         }
1556         case BitcodeConstant::ConstantStructOpcode:
1557           C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps);
1558           break;
1559         case BitcodeConstant::ConstantArrayOpcode:
1560           C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps);
1561           break;
1562         case BitcodeConstant::ConstantVectorOpcode:
1563           C = ConstantVector::get(ConstOps);
1564           break;
1565         case Instruction::ICmp:
1566         case Instruction::FCmp:
1567           C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]);
1568           break;
1569         case Instruction::GetElementPtr:
1570           C = ConstantExpr::getGetElementPtr(BC->SrcElemTy, ConstOps[0],
1571                                              ArrayRef(ConstOps).drop_front(),
1572                                              BC->Flags, BC->getInRangeIndex());
1573           break;
1574         case Instruction::ExtractElement:
1575           C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
1576           break;
1577         case Instruction::InsertElement:
1578           C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
1579                                              ConstOps[2]);
1580           break;
1581         case Instruction::ShuffleVector: {
1582           SmallVector<int, 16> Mask;
1583           ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
1584           C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
1585           break;
1586         }
1587         default:
1588           llvm_unreachable("Unhandled bitcode constant");
1589         }
1590       }
1591 
1592       // Cache resolved constant.
1593       ValueList.replaceValueWithoutRAUW(ValID, C);
1594       MaterializedValues.insert({ValID, C});
1595       Worklist.pop_back();
1596       continue;
1597     }
1598 
1599     if (!InsertBB)
1600       return error(Twine("Value referenced by initializer is an unsupported "
1601                          "constant expression of type ") +
1602                    BC->getOpcodeName());
1603 
1604     // Materialize as instructions if necessary.
1605     Instruction *I;
1606     if (Instruction::isCast(BC->Opcode)) {
1607       I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
1608                            BC->getType(), "constexpr", InsertBB);
1609     } else if (Instruction::isUnaryOp(BC->Opcode)) {
1610       I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0],
1611                                 "constexpr", InsertBB);
1612     } else if (Instruction::isBinaryOp(BC->Opcode)) {
1613       I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0],
1614                                  Ops[1], "constexpr", InsertBB);
1615       if (isa<OverflowingBinaryOperator>(I)) {
1616         if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
1617           I->setHasNoSignedWrap();
1618         if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
1619           I->setHasNoUnsignedWrap();
1620       }
1621       if (isa<PossiblyExactOperator>(I) &&
1622           (BC->Flags & PossiblyExactOperator::IsExact))
1623         I->setIsExact();
1624     } else {
1625       switch (BC->Opcode) {
1626       case BitcodeConstant::ConstantVectorOpcode: {
1627         Type *IdxTy = Type::getInt32Ty(BC->getContext());
1628         Value *V = PoisonValue::get(BC->getType());
1629         for (auto Pair : enumerate(Ops)) {
1630           Value *Idx = ConstantInt::get(IdxTy, Pair.index());
1631           V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
1632                                         InsertBB);
1633         }
1634         I = cast<Instruction>(V);
1635         break;
1636       }
1637       case BitcodeConstant::ConstantStructOpcode:
1638       case BitcodeConstant::ConstantArrayOpcode: {
1639         Value *V = PoisonValue::get(BC->getType());
1640         for (auto Pair : enumerate(Ops))
1641           V = InsertValueInst::Create(V, Pair.value(), Pair.index(),
1642                                       "constexpr.ins", InsertBB);
1643         I = cast<Instruction>(V);
1644         break;
1645       }
1646       case Instruction::ICmp:
1647       case Instruction::FCmp:
1648         I = CmpInst::Create((Instruction::OtherOps)BC->Opcode,
1649                             (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
1650                             "constexpr", InsertBB);
1651         break;
1652       case Instruction::GetElementPtr:
1653         I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
1654                                       ArrayRef(Ops).drop_front(), "constexpr",
1655                                       InsertBB);
1656         if (BC->Flags)
1657           cast<GetElementPtrInst>(I)->setIsInBounds();
1658         break;
1659       case Instruction::Select:
1660         I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
1661         break;
1662       case Instruction::ExtractElement:
1663         I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
1664         break;
1665       case Instruction::InsertElement:
1666         I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
1667                                       InsertBB);
1668         break;
1669       case Instruction::ShuffleVector:
1670         I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
1671                                   InsertBB);
1672         break;
1673       default:
1674         llvm_unreachable("Unhandled bitcode constant");
1675       }
1676     }
1677 
1678     MaterializedValues.insert({ValID, I});
1679     Worklist.pop_back();
1680   }
1681 
1682   return MaterializedValues[StartValID];
1683 }
1684 
1685 Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
1686   Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
1687   if (!MaybeV)
1688     return MaybeV.takeError();
1689 
1690   // Result must be Constant if InsertBB is nullptr.
1691   return cast<Constant>(MaybeV.get());
1692 }
1693 
1694 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1695                                                       StringRef Name) {
1696   auto *Ret = StructType::create(Context, Name);
1697   IdentifiedStructTypes.push_back(Ret);
1698   return Ret;
1699 }
1700 
1701 StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1702   auto *Ret = StructType::create(Context);
1703   IdentifiedStructTypes.push_back(Ret);
1704   return Ret;
1705 }
1706 
1707 //===----------------------------------------------------------------------===//
1708 //  Functions for parsing blocks from the bitcode file
1709 //===----------------------------------------------------------------------===//
1710 
1711 static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
1712   switch (Val) {
1713   case Attribute::EndAttrKinds:
1714   case Attribute::EmptyKey:
1715   case Attribute::TombstoneKey:
1716     llvm_unreachable("Synthetic enumerators which should never get here");
1717 
1718   case Attribute::None:            return 0;
1719   case Attribute::ZExt:            return 1 << 0;
1720   case Attribute::SExt:            return 1 << 1;
1721   case Attribute::NoReturn:        return 1 << 2;
1722   case Attribute::InReg:           return 1 << 3;
1723   case Attribute::StructRet:       return 1 << 4;
1724   case Attribute::NoUnwind:        return 1 << 5;
1725   case Attribute::NoAlias:         return 1 << 6;
1726   case Attribute::ByVal:           return 1 << 7;
1727   case Attribute::Nest:            return 1 << 8;
1728   case Attribute::ReadNone:        return 1 << 9;
1729   case Attribute::ReadOnly:        return 1 << 10;
1730   case Attribute::NoInline:        return 1 << 11;
1731   case Attribute::AlwaysInline:    return 1 << 12;
1732   case Attribute::OptimizeForSize: return 1 << 13;
1733   case Attribute::StackProtect:    return 1 << 14;
1734   case Attribute::StackProtectReq: return 1 << 15;
1735   case Attribute::Alignment:       return 31 << 16;
1736   case Attribute::NoCapture:       return 1 << 21;
1737   case Attribute::NoRedZone:       return 1 << 22;
1738   case Attribute::NoImplicitFloat: return 1 << 23;
1739   case Attribute::Naked:           return 1 << 24;
1740   case Attribute::InlineHint:      return 1 << 25;
1741   case Attribute::StackAlignment:  return 7 << 26;
1742   case Attribute::ReturnsTwice:    return 1 << 29;
1743   case Attribute::UWTable:         return 1 << 30;
1744   case Attribute::NonLazyBind:     return 1U << 31;
1745   case Attribute::SanitizeAddress: return 1ULL << 32;
1746   case Attribute::MinSize:         return 1ULL << 33;
1747   case Attribute::NoDuplicate:     return 1ULL << 34;
1748   case Attribute::StackProtectStrong: return 1ULL << 35;
1749   case Attribute::SanitizeThread:  return 1ULL << 36;
1750   case Attribute::SanitizeMemory:  return 1ULL << 37;
1751   case Attribute::NoBuiltin:       return 1ULL << 38;
1752   case Attribute::Returned:        return 1ULL << 39;
1753   case Attribute::Cold:            return 1ULL << 40;
1754   case Attribute::Builtin:         return 1ULL << 41;
1755   case Attribute::OptimizeNone:    return 1ULL << 42;
1756   case Attribute::InAlloca:        return 1ULL << 43;
1757   case Attribute::NonNull:         return 1ULL << 44;
1758   case Attribute::JumpTable:       return 1ULL << 45;
1759   case Attribute::Convergent:      return 1ULL << 46;
1760   case Attribute::SafeStack:       return 1ULL << 47;
1761   case Attribute::NoRecurse:       return 1ULL << 48;
1762   // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
1763   // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
1764   case Attribute::SwiftSelf:       return 1ULL << 51;
1765   case Attribute::SwiftError:      return 1ULL << 52;
1766   case Attribute::WriteOnly:       return 1ULL << 53;
1767   case Attribute::Speculatable:    return 1ULL << 54;
1768   case Attribute::StrictFP:        return 1ULL << 55;
1769   case Attribute::SanitizeHWAddress: return 1ULL << 56;
1770   case Attribute::NoCfCheck:       return 1ULL << 57;
1771   case Attribute::OptForFuzzing:   return 1ULL << 58;
1772   case Attribute::ShadowCallStack: return 1ULL << 59;
1773   case Attribute::SpeculativeLoadHardening:
1774     return 1ULL << 60;
1775   case Attribute::ImmArg:
1776     return 1ULL << 61;
1777   case Attribute::WillReturn:
1778     return 1ULL << 62;
1779   case Attribute::NoFree:
1780     return 1ULL << 63;
1781   default:
1782     // Other attributes are not supported in the raw format,
1783     // as we ran out of space.
1784     return 0;
1785   }
1786   llvm_unreachable("Unsupported attribute type");
1787 }
1788 
1789 static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
1790   if (!Val) return;
1791 
1792   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1793        I = Attribute::AttrKind(I + 1)) {
1794     if (uint64_t A = (Val & getRawAttributeMask(I))) {
1795       if (I == Attribute::Alignment)
1796         B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
1797       else if (I == Attribute::StackAlignment)
1798         B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
1799       else if (Attribute::isTypeAttrKind(I))
1800         B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
1801       else
1802         B.addAttribute(I);
1803     }
1804   }
1805 }
1806 
1807 /// This fills an AttrBuilder object with the LLVM attributes that have
1808 /// been decoded from the given integer. This function must stay in sync with
1809 /// 'encodeLLVMAttributesForBitcode'.
1810 static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1811                                            uint64_t EncodedAttrs,
1812                                            uint64_t AttrIdx) {
1813   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
1814   // the bits above 31 down by 11 bits.
1815   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1816   assert((!Alignment || isPowerOf2_32(Alignment)) &&
1817          "Alignment must be a power of two.");
1818 
1819   if (Alignment)
1820     B.addAlignmentAttr(Alignment);
1821 
1822   uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
1823                    (EncodedAttrs & 0xffff);
1824 
1825   if (AttrIdx == AttributeList::FunctionIndex) {
1826     // Upgrade old memory attributes.
1827     MemoryEffects ME = MemoryEffects::unknown();
1828     if (Attrs & (1ULL << 9)) {
1829       // ReadNone
1830       Attrs &= ~(1ULL << 9);
1831       ME &= MemoryEffects::none();
1832     }
1833     if (Attrs & (1ULL << 10)) {
1834       // ReadOnly
1835       Attrs &= ~(1ULL << 10);
1836       ME &= MemoryEffects::readOnly();
1837     }
1838     if (Attrs & (1ULL << 49)) {
1839       // InaccessibleMemOnly
1840       Attrs &= ~(1ULL << 49);
1841       ME &= MemoryEffects::inaccessibleMemOnly();
1842     }
1843     if (Attrs & (1ULL << 50)) {
1844       // InaccessibleMemOrArgMemOnly
1845       Attrs &= ~(1ULL << 50);
1846       ME &= MemoryEffects::inaccessibleOrArgMemOnly();
1847     }
1848     if (Attrs & (1ULL << 53)) {
1849       // WriteOnly
1850       Attrs &= ~(1ULL << 53);
1851       ME &= MemoryEffects::writeOnly();
1852     }
1853     if (ME != MemoryEffects::unknown())
1854       B.addMemoryAttr(ME);
1855   }
1856 
1857   addRawAttributeValue(B, Attrs);
1858 }
1859 
1860 Error BitcodeReader::parseAttributeBlock() {
1861   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
1862     return Err;
1863 
1864   if (!MAttributes.empty())
1865     return error("Invalid multiple blocks");
1866 
1867   SmallVector<uint64_t, 64> Record;
1868 
1869   SmallVector<AttributeList, 8> Attrs;
1870 
1871   // Read all the records.
1872   while (true) {
1873     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
1874     if (!MaybeEntry)
1875       return MaybeEntry.takeError();
1876     BitstreamEntry Entry = MaybeEntry.get();
1877 
1878     switch (Entry.Kind) {
1879     case BitstreamEntry::SubBlock: // Handled for us already.
1880     case BitstreamEntry::Error:
1881       return error("Malformed block");
1882     case BitstreamEntry::EndBlock:
1883       return Error::success();
1884     case BitstreamEntry::Record:
1885       // The interesting case.
1886       break;
1887     }
1888 
1889     // Read a record.
1890     Record.clear();
1891     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
1892     if (!MaybeRecord)
1893       return MaybeRecord.takeError();
1894     switch (MaybeRecord.get()) {
1895     default:  // Default behavior: ignore.
1896       break;
1897     case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
1898       // Deprecated, but still needed to read old bitcode files.
1899       if (Record.size() & 1)
1900         return error("Invalid parameter attribute record");
1901 
1902       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1903         AttrBuilder B(Context);
1904         decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]);
1905         Attrs.push_back(AttributeList::get(Context, Record[i], B));
1906       }
1907 
1908       MAttributes.push_back(AttributeList::get(Context, Attrs));
1909       Attrs.clear();
1910       break;
1911     case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
1912       for (unsigned i = 0, e = Record.size(); i != e; ++i)
1913         Attrs.push_back(MAttributeGroups[Record[i]]);
1914 
1915       MAttributes.push_back(AttributeList::get(Context, Attrs));
1916       Attrs.clear();
1917       break;
1918     }
1919   }
1920 }
1921 
1922 // Returns Attribute::None on unrecognized codes.
1923 static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
1924   switch (Code) {
1925   default:
1926     return Attribute::None;
1927   case bitc::ATTR_KIND_ALIGNMENT:
1928     return Attribute::Alignment;
1929   case bitc::ATTR_KIND_ALWAYS_INLINE:
1930     return Attribute::AlwaysInline;
1931   case bitc::ATTR_KIND_BUILTIN:
1932     return Attribute::Builtin;
1933   case bitc::ATTR_KIND_BY_VAL:
1934     return Attribute::ByVal;
1935   case bitc::ATTR_KIND_IN_ALLOCA:
1936     return Attribute::InAlloca;
1937   case bitc::ATTR_KIND_COLD:
1938     return Attribute::Cold;
1939   case bitc::ATTR_KIND_CONVERGENT:
1940     return Attribute::Convergent;
1941   case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
1942     return Attribute::DisableSanitizerInstrumentation;
1943   case bitc::ATTR_KIND_ELEMENTTYPE:
1944     return Attribute::ElementType;
1945   case bitc::ATTR_KIND_FNRETTHUNK_EXTERN:
1946     return Attribute::FnRetThunkExtern;
1947   case bitc::ATTR_KIND_INLINE_HINT:
1948     return Attribute::InlineHint;
1949   case bitc::ATTR_KIND_IN_REG:
1950     return Attribute::InReg;
1951   case bitc::ATTR_KIND_JUMP_TABLE:
1952     return Attribute::JumpTable;
1953   case bitc::ATTR_KIND_MEMORY:
1954     return Attribute::Memory;
1955   case bitc::ATTR_KIND_NOFPCLASS:
1956     return Attribute::NoFPClass;
1957   case bitc::ATTR_KIND_MIN_SIZE:
1958     return Attribute::MinSize;
1959   case bitc::ATTR_KIND_NAKED:
1960     return Attribute::Naked;
1961   case bitc::ATTR_KIND_NEST:
1962     return Attribute::Nest;
1963   case bitc::ATTR_KIND_NO_ALIAS:
1964     return Attribute::NoAlias;
1965   case bitc::ATTR_KIND_NO_BUILTIN:
1966     return Attribute::NoBuiltin;
1967   case bitc::ATTR_KIND_NO_CALLBACK:
1968     return Attribute::NoCallback;
1969   case bitc::ATTR_KIND_NO_CAPTURE:
1970     return Attribute::NoCapture;
1971   case bitc::ATTR_KIND_NO_DUPLICATE:
1972     return Attribute::NoDuplicate;
1973   case bitc::ATTR_KIND_NOFREE:
1974     return Attribute::NoFree;
1975   case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1976     return Attribute::NoImplicitFloat;
1977   case bitc::ATTR_KIND_NO_INLINE:
1978     return Attribute::NoInline;
1979   case bitc::ATTR_KIND_NO_RECURSE:
1980     return Attribute::NoRecurse;
1981   case bitc::ATTR_KIND_NO_MERGE:
1982     return Attribute::NoMerge;
1983   case bitc::ATTR_KIND_NON_LAZY_BIND:
1984     return Attribute::NonLazyBind;
1985   case bitc::ATTR_KIND_NON_NULL:
1986     return Attribute::NonNull;
1987   case bitc::ATTR_KIND_DEREFERENCEABLE:
1988     return Attribute::Dereferenceable;
1989   case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1990     return Attribute::DereferenceableOrNull;
1991   case bitc::ATTR_KIND_ALLOC_ALIGN:
1992     return Attribute::AllocAlign;
1993   case bitc::ATTR_KIND_ALLOC_KIND:
1994     return Attribute::AllocKind;
1995   case bitc::ATTR_KIND_ALLOC_SIZE:
1996     return Attribute::AllocSize;
1997   case bitc::ATTR_KIND_ALLOCATED_POINTER:
1998     return Attribute::AllocatedPointer;
1999   case bitc::ATTR_KIND_NO_RED_ZONE:
2000     return Attribute::NoRedZone;
2001   case bitc::ATTR_KIND_NO_RETURN:
2002     return Attribute::NoReturn;
2003   case bitc::ATTR_KIND_NOSYNC:
2004     return Attribute::NoSync;
2005   case bitc::ATTR_KIND_NOCF_CHECK:
2006     return Attribute::NoCfCheck;
2007   case bitc::ATTR_KIND_NO_PROFILE:
2008     return Attribute::NoProfile;
2009   case bitc::ATTR_KIND_SKIP_PROFILE:
2010     return Attribute::SkipProfile;
2011   case bitc::ATTR_KIND_NO_UNWIND:
2012     return Attribute::NoUnwind;
2013   case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:
2014     return Attribute::NoSanitizeBounds;
2015   case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
2016     return Attribute::NoSanitizeCoverage;
2017   case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
2018     return Attribute::NullPointerIsValid;
2019   case bitc::ATTR_KIND_OPTIMIZE_FOR_DEBUGGING:
2020     return Attribute::OptimizeForDebugging;
2021   case bitc::ATTR_KIND_OPT_FOR_FUZZING:
2022     return Attribute::OptForFuzzing;
2023   case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
2024     return Attribute::OptimizeForSize;
2025   case bitc::ATTR_KIND_OPTIMIZE_NONE:
2026     return Attribute::OptimizeNone;
2027   case bitc::ATTR_KIND_READ_NONE:
2028     return Attribute::ReadNone;
2029   case bitc::ATTR_KIND_READ_ONLY:
2030     return Attribute::ReadOnly;
2031   case bitc::ATTR_KIND_RETURNED:
2032     return Attribute::Returned;
2033   case bitc::ATTR_KIND_RETURNS_TWICE:
2034     return Attribute::ReturnsTwice;
2035   case bitc::ATTR_KIND_S_EXT:
2036     return Attribute::SExt;
2037   case bitc::ATTR_KIND_SPECULATABLE:
2038     return Attribute::Speculatable;
2039   case bitc::ATTR_KIND_STACK_ALIGNMENT:
2040     return Attribute::StackAlignment;
2041   case bitc::ATTR_KIND_STACK_PROTECT:
2042     return Attribute::StackProtect;
2043   case bitc::ATTR_KIND_STACK_PROTECT_REQ:
2044     return Attribute::StackProtectReq;
2045   case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
2046     return Attribute::StackProtectStrong;
2047   case bitc::ATTR_KIND_SAFESTACK:
2048     return Attribute::SafeStack;
2049   case bitc::ATTR_KIND_SHADOWCALLSTACK:
2050     return Attribute::ShadowCallStack;
2051   case bitc::ATTR_KIND_STRICT_FP:
2052     return Attribute::StrictFP;
2053   case bitc::ATTR_KIND_STRUCT_RET:
2054     return Attribute::StructRet;
2055   case bitc::ATTR_KIND_SANITIZE_ADDRESS:
2056     return Attribute::SanitizeAddress;
2057   case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
2058     return Attribute::SanitizeHWAddress;
2059   case bitc::ATTR_KIND_SANITIZE_THREAD:
2060     return Attribute::SanitizeThread;
2061   case bitc::ATTR_KIND_SANITIZE_MEMORY:
2062     return Attribute::SanitizeMemory;
2063   case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
2064     return Attribute::SpeculativeLoadHardening;
2065   case bitc::ATTR_KIND_SWIFT_ERROR:
2066     return Attribute::SwiftError;
2067   case bitc::ATTR_KIND_SWIFT_SELF:
2068     return Attribute::SwiftSelf;
2069   case bitc::ATTR_KIND_SWIFT_ASYNC:
2070     return Attribute::SwiftAsync;
2071   case bitc::ATTR_KIND_UW_TABLE:
2072     return Attribute::UWTable;
2073   case bitc::ATTR_KIND_VSCALE_RANGE:
2074     return Attribute::VScaleRange;
2075   case bitc::ATTR_KIND_WILLRETURN:
2076     return Attribute::WillReturn;
2077   case bitc::ATTR_KIND_WRITEONLY:
2078     return Attribute::WriteOnly;
2079   case bitc::ATTR_KIND_Z_EXT:
2080     return Attribute::ZExt;
2081   case bitc::ATTR_KIND_IMMARG:
2082     return Attribute::ImmArg;
2083   case bitc::ATTR_KIND_SANITIZE_MEMTAG:
2084     return Attribute::SanitizeMemTag;
2085   case bitc::ATTR_KIND_PREALLOCATED:
2086     return Attribute::Preallocated;
2087   case bitc::ATTR_KIND_NOUNDEF:
2088     return Attribute::NoUndef;
2089   case bitc::ATTR_KIND_BYREF:
2090     return Attribute::ByRef;
2091   case bitc::ATTR_KIND_MUSTPROGRESS:
2092     return Attribute::MustProgress;
2093   case bitc::ATTR_KIND_HOT:
2094     return Attribute::Hot;
2095   case bitc::ATTR_KIND_PRESPLIT_COROUTINE:
2096     return Attribute::PresplitCoroutine;
2097   case bitc::ATTR_KIND_WRITABLE:
2098     return Attribute::Writable;
2099   case bitc::ATTR_KIND_CORO_ONLY_DESTROY_WHEN_COMPLETE:
2100     return Attribute::CoroDestroyOnlyWhenComplete;
2101   case bitc::ATTR_KIND_DEAD_ON_UNWIND:
2102     return Attribute::DeadOnUnwind;
2103   }
2104 }
2105 
2106 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
2107                                          MaybeAlign &Alignment) {
2108   // Note: Alignment in bitcode files is incremented by 1, so that zero
2109   // can be used for default alignment.
2110   if (Exponent > Value::MaxAlignmentExponent + 1)
2111     return error("Invalid alignment value");
2112   Alignment = decodeMaybeAlign(Exponent);
2113   return Error::success();
2114 }
2115 
2116 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2117   *Kind = getAttrFromCode(Code);
2118   if (*Kind == Attribute::None)
2119     return error("Unknown attribute kind (" + Twine(Code) + ")");
2120   return Error::success();
2121 }
2122 
2123 static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2124   switch (EncodedKind) {
2125   case bitc::ATTR_KIND_READ_NONE:
2126     ME &= MemoryEffects::none();
2127     return true;
2128   case bitc::ATTR_KIND_READ_ONLY:
2129     ME &= MemoryEffects::readOnly();
2130     return true;
2131   case bitc::ATTR_KIND_WRITEONLY:
2132     ME &= MemoryEffects::writeOnly();
2133     return true;
2134   case bitc::ATTR_KIND_ARGMEMONLY:
2135     ME &= MemoryEffects::argMemOnly();
2136     return true;
2137   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
2138     ME &= MemoryEffects::inaccessibleMemOnly();
2139     return true;
2140   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
2141     ME &= MemoryEffects::inaccessibleOrArgMemOnly();
2142     return true;
2143   default:
2144     return false;
2145   }
2146 }
2147 
2148 Error BitcodeReader::parseAttributeGroupBlock() {
2149   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
2150     return Err;
2151 
2152   if (!MAttributeGroups.empty())
2153     return error("Invalid multiple blocks");
2154 
2155   SmallVector<uint64_t, 64> Record;
2156 
2157   // Read all the records.
2158   while (true) {
2159     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2160     if (!MaybeEntry)
2161       return MaybeEntry.takeError();
2162     BitstreamEntry Entry = MaybeEntry.get();
2163 
2164     switch (Entry.Kind) {
2165     case BitstreamEntry::SubBlock: // Handled for us already.
2166     case BitstreamEntry::Error:
2167       return error("Malformed block");
2168     case BitstreamEntry::EndBlock:
2169       return Error::success();
2170     case BitstreamEntry::Record:
2171       // The interesting case.
2172       break;
2173     }
2174 
2175     // Read a record.
2176     Record.clear();
2177     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2178     if (!MaybeRecord)
2179       return MaybeRecord.takeError();
2180     switch (MaybeRecord.get()) {
2181     default:  // Default behavior: ignore.
2182       break;
2183     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2184       if (Record.size() < 3)
2185         return error("Invalid grp record");
2186 
2187       uint64_t GrpID = Record[0];
2188       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2189 
2190       AttrBuilder B(Context);
2191       MemoryEffects ME = MemoryEffects::unknown();
2192       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2193         if (Record[i] == 0) {        // Enum attribute
2194           Attribute::AttrKind Kind;
2195           uint64_t EncodedKind = Record[++i];
2196           if (Idx == AttributeList::FunctionIndex &&
2197               upgradeOldMemoryAttribute(ME, EncodedKind))
2198             continue;
2199 
2200           if (Error Err = parseAttrKind(EncodedKind, &Kind))
2201             return Err;
2202 
2203           // Upgrade old-style byval attribute to one with a type, even if it's
2204           // nullptr. We will have to insert the real type when we associate
2205           // this AttributeList with a function.
2206           if (Kind == Attribute::ByVal)
2207             B.addByValAttr(nullptr);
2208           else if (Kind == Attribute::StructRet)
2209             B.addStructRetAttr(nullptr);
2210           else if (Kind == Attribute::InAlloca)
2211             B.addInAllocaAttr(nullptr);
2212           else if (Kind == Attribute::UWTable)
2213             B.addUWTableAttr(UWTableKind::Default);
2214           else if (Attribute::isEnumAttrKind(Kind))
2215             B.addAttribute(Kind);
2216           else
2217             return error("Not an enum attribute");
2218         } else if (Record[i] == 1) { // Integer attribute
2219           Attribute::AttrKind Kind;
2220           if (Error Err = parseAttrKind(Record[++i], &Kind))
2221             return Err;
2222           if (!Attribute::isIntAttrKind(Kind))
2223             return error("Not an int attribute");
2224           if (Kind == Attribute::Alignment)
2225             B.addAlignmentAttr(Record[++i]);
2226           else if (Kind == Attribute::StackAlignment)
2227             B.addStackAlignmentAttr(Record[++i]);
2228           else if (Kind == Attribute::Dereferenceable)
2229             B.addDereferenceableAttr(Record[++i]);
2230           else if (Kind == Attribute::DereferenceableOrNull)
2231             B.addDereferenceableOrNullAttr(Record[++i]);
2232           else if (Kind == Attribute::AllocSize)
2233             B.addAllocSizeAttrFromRawRepr(Record[++i]);
2234           else if (Kind == Attribute::VScaleRange)
2235             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2236           else if (Kind == Attribute::UWTable)
2237             B.addUWTableAttr(UWTableKind(Record[++i]));
2238           else if (Kind == Attribute::AllocKind)
2239             B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2240           else if (Kind == Attribute::Memory)
2241             B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i]));
2242           else if (Kind == Attribute::NoFPClass)
2243             B.addNoFPClassAttr(
2244                 static_cast<FPClassTest>(Record[++i] & fcAllFlags));
2245         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
2246           bool HasValue = (Record[i++] == 4);
2247           SmallString<64> KindStr;
2248           SmallString<64> ValStr;
2249 
2250           while (Record[i] != 0 && i != e)
2251             KindStr += Record[i++];
2252           assert(Record[i] == 0 && "Kind string not null terminated");
2253 
2254           if (HasValue) {
2255             // Has a value associated with it.
2256             ++i; // Skip the '0' that terminates the "kind" string.
2257             while (Record[i] != 0 && i != e)
2258               ValStr += Record[i++];
2259             assert(Record[i] == 0 && "Value string not null terminated");
2260           }
2261 
2262           B.addAttribute(KindStr.str(), ValStr.str());
2263         } else if (Record[i] == 5 || Record[i] == 6) {
2264           bool HasType = Record[i] == 6;
2265           Attribute::AttrKind Kind;
2266           if (Error Err = parseAttrKind(Record[++i], &Kind))
2267             return Err;
2268           if (!Attribute::isTypeAttrKind(Kind))
2269             return error("Not a type attribute");
2270 
2271           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2272         } else {
2273           return error("Invalid attribute group entry");
2274         }
2275       }
2276 
2277       if (ME != MemoryEffects::unknown())
2278         B.addMemoryAttr(ME);
2279 
2280       UpgradeAttributes(B);
2281       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
2282       break;
2283     }
2284     }
2285   }
2286 }
2287 
2288 Error BitcodeReader::parseTypeTable() {
2289   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
2290     return Err;
2291 
2292   return parseTypeTableBody();
2293 }
2294 
2295 Error BitcodeReader::parseTypeTableBody() {
2296   if (!TypeList.empty())
2297     return error("Invalid multiple blocks");
2298 
2299   SmallVector<uint64_t, 64> Record;
2300   unsigned NumRecords = 0;
2301 
2302   SmallString<64> TypeName;
2303 
2304   // Read all the records for this type table.
2305   while (true) {
2306     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2307     if (!MaybeEntry)
2308       return MaybeEntry.takeError();
2309     BitstreamEntry Entry = MaybeEntry.get();
2310 
2311     switch (Entry.Kind) {
2312     case BitstreamEntry::SubBlock: // Handled for us already.
2313     case BitstreamEntry::Error:
2314       return error("Malformed block");
2315     case BitstreamEntry::EndBlock:
2316       if (NumRecords != TypeList.size())
2317         return error("Malformed block");
2318       return Error::success();
2319     case BitstreamEntry::Record:
2320       // The interesting case.
2321       break;
2322     }
2323 
2324     // Read a record.
2325     Record.clear();
2326     Type *ResultTy = nullptr;
2327     SmallVector<unsigned> ContainedIDs;
2328     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2329     if (!MaybeRecord)
2330       return MaybeRecord.takeError();
2331     switch (MaybeRecord.get()) {
2332     default:
2333       return error("Invalid value");
2334     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2335       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2336       // type list.  This allows us to reserve space.
2337       if (Record.empty())
2338         return error("Invalid numentry record");
2339       TypeList.resize(Record[0]);
2340       continue;
2341     case bitc::TYPE_CODE_VOID:      // VOID
2342       ResultTy = Type::getVoidTy(Context);
2343       break;
2344     case bitc::TYPE_CODE_HALF:     // HALF
2345       ResultTy = Type::getHalfTy(Context);
2346       break;
2347     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
2348       ResultTy = Type::getBFloatTy(Context);
2349       break;
2350     case bitc::TYPE_CODE_FLOAT:     // FLOAT
2351       ResultTy = Type::getFloatTy(Context);
2352       break;
2353     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
2354       ResultTy = Type::getDoubleTy(Context);
2355       break;
2356     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
2357       ResultTy = Type::getX86_FP80Ty(Context);
2358       break;
2359     case bitc::TYPE_CODE_FP128:     // FP128
2360       ResultTy = Type::getFP128Ty(Context);
2361       break;
2362     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2363       ResultTy = Type::getPPC_FP128Ty(Context);
2364       break;
2365     case bitc::TYPE_CODE_LABEL:     // LABEL
2366       ResultTy = Type::getLabelTy(Context);
2367       break;
2368     case bitc::TYPE_CODE_METADATA:  // METADATA
2369       ResultTy = Type::getMetadataTy(Context);
2370       break;
2371     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
2372       ResultTy = Type::getX86_MMXTy(Context);
2373       break;
2374     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
2375       ResultTy = Type::getX86_AMXTy(Context);
2376       break;
2377     case bitc::TYPE_CODE_TOKEN:     // TOKEN
2378       ResultTy = Type::getTokenTy(Context);
2379       break;
2380     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2381       if (Record.empty())
2382         return error("Invalid integer record");
2383 
2384       uint64_t NumBits = Record[0];
2385       if (NumBits < IntegerType::MIN_INT_BITS ||
2386           NumBits > IntegerType::MAX_INT_BITS)
2387         return error("Bitwidth for integer type out of range");
2388       ResultTy = IntegerType::get(Context, NumBits);
2389       break;
2390     }
2391     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2392                                     //          [pointee type, address space]
2393       if (Record.empty())
2394         return error("Invalid pointer record");
2395       unsigned AddressSpace = 0;
2396       if (Record.size() == 2)
2397         AddressSpace = Record[1];
2398       ResultTy = getTypeByID(Record[0]);
2399       if (!ResultTy ||
2400           !PointerType::isValidElementType(ResultTy))
2401         return error("Invalid type");
2402       ContainedIDs.push_back(Record[0]);
2403       ResultTy = PointerType::get(ResultTy, AddressSpace);
2404       break;
2405     }
2406     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2407       if (Record.size() != 1)
2408         return error("Invalid opaque pointer record");
2409       unsigned AddressSpace = Record[0];
2410       ResultTy = PointerType::get(Context, AddressSpace);
2411       break;
2412     }
2413     case bitc::TYPE_CODE_FUNCTION_OLD: {
2414       // Deprecated, but still needed to read old bitcode files.
2415       // FUNCTION: [vararg, attrid, retty, paramty x N]
2416       if (Record.size() < 3)
2417         return error("Invalid function record");
2418       SmallVector<Type*, 8> ArgTys;
2419       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2420         if (Type *T = getTypeByID(Record[i]))
2421           ArgTys.push_back(T);
2422         else
2423           break;
2424       }
2425 
2426       ResultTy = getTypeByID(Record[2]);
2427       if (!ResultTy || ArgTys.size() < Record.size()-3)
2428         return error("Invalid type");
2429 
2430       ContainedIDs.append(Record.begin() + 2, Record.end());
2431       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2432       break;
2433     }
2434     case bitc::TYPE_CODE_FUNCTION: {
2435       // FUNCTION: [vararg, retty, paramty x N]
2436       if (Record.size() < 2)
2437         return error("Invalid function record");
2438       SmallVector<Type*, 8> ArgTys;
2439       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2440         if (Type *T = getTypeByID(Record[i])) {
2441           if (!FunctionType::isValidArgumentType(T))
2442             return error("Invalid function argument type");
2443           ArgTys.push_back(T);
2444         }
2445         else
2446           break;
2447       }
2448 
2449       ResultTy = getTypeByID(Record[1]);
2450       if (!ResultTy || ArgTys.size() < Record.size()-2)
2451         return error("Invalid type");
2452 
2453       ContainedIDs.append(Record.begin() + 1, Record.end());
2454       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2455       break;
2456     }
2457     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
2458       if (Record.empty())
2459         return error("Invalid anon struct record");
2460       SmallVector<Type*, 8> EltTys;
2461       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2462         if (Type *T = getTypeByID(Record[i]))
2463           EltTys.push_back(T);
2464         else
2465           break;
2466       }
2467       if (EltTys.size() != Record.size()-1)
2468         return error("Invalid type");
2469       ContainedIDs.append(Record.begin() + 1, Record.end());
2470       ResultTy = StructType::get(Context, EltTys, Record[0]);
2471       break;
2472     }
2473     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
2474       if (convertToString(Record, 0, TypeName))
2475         return error("Invalid struct name record");
2476       continue;
2477 
2478     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2479       if (Record.empty())
2480         return error("Invalid named struct record");
2481 
2482       if (NumRecords >= TypeList.size())
2483         return error("Invalid TYPE table");
2484 
2485       // Check to see if this was forward referenced, if so fill in the temp.
2486       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2487       if (Res) {
2488         Res->setName(TypeName);
2489         TypeList[NumRecords] = nullptr;
2490       } else  // Otherwise, create a new struct.
2491         Res = createIdentifiedStructType(Context, TypeName);
2492       TypeName.clear();
2493 
2494       SmallVector<Type*, 8> EltTys;
2495       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2496         if (Type *T = getTypeByID(Record[i]))
2497           EltTys.push_back(T);
2498         else
2499           break;
2500       }
2501       if (EltTys.size() != Record.size()-1)
2502         return error("Invalid named struct record");
2503       Res->setBody(EltTys, Record[0]);
2504       ContainedIDs.append(Record.begin() + 1, Record.end());
2505       ResultTy = Res;
2506       break;
2507     }
2508     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
2509       if (Record.size() != 1)
2510         return error("Invalid opaque type record");
2511 
2512       if (NumRecords >= TypeList.size())
2513         return error("Invalid TYPE table");
2514 
2515       // Check to see if this was forward referenced, if so fill in the temp.
2516       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2517       if (Res) {
2518         Res->setName(TypeName);
2519         TypeList[NumRecords] = nullptr;
2520       } else  // Otherwise, create a new struct with no body.
2521         Res = createIdentifiedStructType(Context, TypeName);
2522       TypeName.clear();
2523       ResultTy = Res;
2524       break;
2525     }
2526     case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2527       if (Record.size() < 1)
2528         return error("Invalid target extension type record");
2529 
2530       if (NumRecords >= TypeList.size())
2531         return error("Invalid TYPE table");
2532 
2533       if (Record[0] >= Record.size())
2534         return error("Too many type parameters");
2535 
2536       unsigned NumTys = Record[0];
2537       SmallVector<Type *, 4> TypeParams;
2538       SmallVector<unsigned, 8> IntParams;
2539       for (unsigned i = 0; i < NumTys; i++) {
2540         if (Type *T = getTypeByID(Record[i + 1]))
2541           TypeParams.push_back(T);
2542         else
2543           return error("Invalid type");
2544       }
2545 
2546       for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2547         if (Record[i] > UINT_MAX)
2548           return error("Integer parameter too large");
2549         IntParams.push_back(Record[i]);
2550       }
2551       ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
2552       TypeName.clear();
2553       break;
2554     }
2555     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
2556       if (Record.size() < 2)
2557         return error("Invalid array type record");
2558       ResultTy = getTypeByID(Record[1]);
2559       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2560         return error("Invalid type");
2561       ContainedIDs.push_back(Record[1]);
2562       ResultTy = ArrayType::get(ResultTy, Record[0]);
2563       break;
2564     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
2565                                     //         [numelts, eltty, scalable]
2566       if (Record.size() < 2)
2567         return error("Invalid vector type record");
2568       if (Record[0] == 0)
2569         return error("Invalid vector length");
2570       ResultTy = getTypeByID(Record[1]);
2571       if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2572         return error("Invalid type");
2573       bool Scalable = Record.size() > 2 ? Record[2] : false;
2574       ContainedIDs.push_back(Record[1]);
2575       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2576       break;
2577     }
2578 
2579     if (NumRecords >= TypeList.size())
2580       return error("Invalid TYPE table");
2581     if (TypeList[NumRecords])
2582       return error(
2583           "Invalid TYPE table: Only named structs can be forward referenced");
2584     assert(ResultTy && "Didn't read a type?");
2585     TypeList[NumRecords] = ResultTy;
2586     if (!ContainedIDs.empty())
2587       ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2588     ++NumRecords;
2589   }
2590 }
2591 
2592 Error BitcodeReader::parseOperandBundleTags() {
2593   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2594     return Err;
2595 
2596   if (!BundleTags.empty())
2597     return error("Invalid multiple blocks");
2598 
2599   SmallVector<uint64_t, 64> Record;
2600 
2601   while (true) {
2602     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2603     if (!MaybeEntry)
2604       return MaybeEntry.takeError();
2605     BitstreamEntry Entry = MaybeEntry.get();
2606 
2607     switch (Entry.Kind) {
2608     case BitstreamEntry::SubBlock: // Handled for us already.
2609     case BitstreamEntry::Error:
2610       return error("Malformed block");
2611     case BitstreamEntry::EndBlock:
2612       return Error::success();
2613     case BitstreamEntry::Record:
2614       // The interesting case.
2615       break;
2616     }
2617 
2618     // Tags are implicitly mapped to integers by their order.
2619 
2620     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2621     if (!MaybeRecord)
2622       return MaybeRecord.takeError();
2623     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2624       return error("Invalid operand bundle record");
2625 
2626     // OPERAND_BUNDLE_TAG: [strchr x N]
2627     BundleTags.emplace_back();
2628     if (convertToString(Record, 0, BundleTags.back()))
2629       return error("Invalid operand bundle record");
2630     Record.clear();
2631   }
2632 }
2633 
2634 Error BitcodeReader::parseSyncScopeNames() {
2635   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2636     return Err;
2637 
2638   if (!SSIDs.empty())
2639     return error("Invalid multiple synchronization scope names blocks");
2640 
2641   SmallVector<uint64_t, 64> Record;
2642   while (true) {
2643     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2644     if (!MaybeEntry)
2645       return MaybeEntry.takeError();
2646     BitstreamEntry Entry = MaybeEntry.get();
2647 
2648     switch (Entry.Kind) {
2649     case BitstreamEntry::SubBlock: // Handled for us already.
2650     case BitstreamEntry::Error:
2651       return error("Malformed block");
2652     case BitstreamEntry::EndBlock:
2653       if (SSIDs.empty())
2654         return error("Invalid empty synchronization scope names block");
2655       return Error::success();
2656     case BitstreamEntry::Record:
2657       // The interesting case.
2658       break;
2659     }
2660 
2661     // Synchronization scope names are implicitly mapped to synchronization
2662     // scope IDs by their order.
2663 
2664     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2665     if (!MaybeRecord)
2666       return MaybeRecord.takeError();
2667     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2668       return error("Invalid sync scope record");
2669 
2670     SmallString<16> SSN;
2671     if (convertToString(Record, 0, SSN))
2672       return error("Invalid sync scope record");
2673 
2674     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2675     Record.clear();
2676   }
2677 }
2678 
2679 /// Associate a value with its name from the given index in the provided record.
2680 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2681                                              unsigned NameIndex, Triple &TT) {
2682   SmallString<128> ValueName;
2683   if (convertToString(Record, NameIndex, ValueName))
2684     return error("Invalid record");
2685   unsigned ValueID = Record[0];
2686   if (ValueID >= ValueList.size() || !ValueList[ValueID])
2687     return error("Invalid record");
2688   Value *V = ValueList[ValueID];
2689 
2690   StringRef NameStr(ValueName.data(), ValueName.size());
2691   if (NameStr.contains(0))
2692     return error("Invalid value name");
2693   V->setName(NameStr);
2694   auto *GO = dyn_cast<GlobalObject>(V);
2695   if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2696     GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2697   return V;
2698 }
2699 
2700 /// Helper to note and return the current location, and jump to the given
2701 /// offset.
2702 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2703                                                  BitstreamCursor &Stream) {
2704   // Save the current parsing location so we can jump back at the end
2705   // of the VST read.
2706   uint64_t CurrentBit = Stream.GetCurrentBitNo();
2707   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2708     return std::move(JumpFailed);
2709   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2710   if (!MaybeEntry)
2711     return MaybeEntry.takeError();
2712   if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
2713       MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
2714     return error("Expected value symbol table subblock");
2715   return CurrentBit;
2716 }
2717 
2718 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2719                                             Function *F,
2720                                             ArrayRef<uint64_t> Record) {
2721   // Note that we subtract 1 here because the offset is relative to one word
2722   // before the start of the identification or module block, which was
2723   // historically always the start of the regular bitcode header.
2724   uint64_t FuncWordOffset = Record[1] - 1;
2725   uint64_t FuncBitOffset = FuncWordOffset * 32;
2726   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2727   // Set the LastFunctionBlockBit to point to the last function block.
2728   // Later when parsing is resumed after function materialization,
2729   // we can simply skip that last function block.
2730   if (FuncBitOffset > LastFunctionBlockBit)
2731     LastFunctionBlockBit = FuncBitOffset;
2732 }
2733 
2734 /// Read a new-style GlobalValue symbol table.
2735 Error BitcodeReader::parseGlobalValueSymbolTable() {
2736   unsigned FuncBitcodeOffsetDelta =
2737       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2738 
2739   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2740     return Err;
2741 
2742   SmallVector<uint64_t, 64> Record;
2743   while (true) {
2744     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2745     if (!MaybeEntry)
2746       return MaybeEntry.takeError();
2747     BitstreamEntry Entry = MaybeEntry.get();
2748 
2749     switch (Entry.Kind) {
2750     case BitstreamEntry::SubBlock:
2751     case BitstreamEntry::Error:
2752       return error("Malformed block");
2753     case BitstreamEntry::EndBlock:
2754       return Error::success();
2755     case BitstreamEntry::Record:
2756       break;
2757     }
2758 
2759     Record.clear();
2760     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2761     if (!MaybeRecord)
2762       return MaybeRecord.takeError();
2763     switch (MaybeRecord.get()) {
2764     case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
2765       unsigned ValueID = Record[0];
2766       if (ValueID >= ValueList.size() || !ValueList[ValueID])
2767         return error("Invalid value reference in symbol table");
2768       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2769                               cast<Function>(ValueList[ValueID]), Record);
2770       break;
2771     }
2772     }
2773   }
2774 }
2775 
2776 /// Parse the value symbol table at either the current parsing location or
2777 /// at the given bit offset if provided.
2778 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2779   uint64_t CurrentBit;
2780   // Pass in the Offset to distinguish between calling for the module-level
2781   // VST (where we want to jump to the VST offset) and the function-level
2782   // VST (where we don't).
2783   if (Offset > 0) {
2784     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2785     if (!MaybeCurrentBit)
2786       return MaybeCurrentBit.takeError();
2787     CurrentBit = MaybeCurrentBit.get();
2788     // If this module uses a string table, read this as a module-level VST.
2789     if (UseStrtab) {
2790       if (Error Err = parseGlobalValueSymbolTable())
2791         return Err;
2792       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2793         return JumpFailed;
2794       return Error::success();
2795     }
2796     // Otherwise, the VST will be in a similar format to a function-level VST,
2797     // and will contain symbol names.
2798   }
2799 
2800   // Compute the delta between the bitcode indices in the VST (the word offset
2801   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2802   // expected by the lazy reader. The reader's EnterSubBlock expects to have
2803   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2804   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2805   // just before entering the VST subblock because: 1) the EnterSubBlock
2806   // changes the AbbrevID width; 2) the VST block is nested within the same
2807   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2808   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2809   // jump to the FUNCTION_BLOCK using this offset later, we don't want
2810   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2811   unsigned FuncBitcodeOffsetDelta =
2812       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2813 
2814   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2815     return Err;
2816 
2817   SmallVector<uint64_t, 64> Record;
2818 
2819   Triple TT(TheModule->getTargetTriple());
2820 
2821   // Read all the records for this value table.
2822   SmallString<128> ValueName;
2823 
2824   while (true) {
2825     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2826     if (!MaybeEntry)
2827       return MaybeEntry.takeError();
2828     BitstreamEntry Entry = MaybeEntry.get();
2829 
2830     switch (Entry.Kind) {
2831     case BitstreamEntry::SubBlock: // Handled for us already.
2832     case BitstreamEntry::Error:
2833       return error("Malformed block");
2834     case BitstreamEntry::EndBlock:
2835       if (Offset > 0)
2836         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2837           return JumpFailed;
2838       return Error::success();
2839     case BitstreamEntry::Record:
2840       // The interesting case.
2841       break;
2842     }
2843 
2844     // Read a record.
2845     Record.clear();
2846     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2847     if (!MaybeRecord)
2848       return MaybeRecord.takeError();
2849     switch (MaybeRecord.get()) {
2850     default:  // Default behavior: unknown type.
2851       break;
2852     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
2853       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2854       if (Error Err = ValOrErr.takeError())
2855         return Err;
2856       ValOrErr.get();
2857       break;
2858     }
2859     case bitc::VST_CODE_FNENTRY: {
2860       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2861       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2862       if (Error Err = ValOrErr.takeError())
2863         return Err;
2864       Value *V = ValOrErr.get();
2865 
2866       // Ignore function offsets emitted for aliases of functions in older
2867       // versions of LLVM.
2868       if (auto *F = dyn_cast<Function>(V))
2869         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2870       break;
2871     }
2872     case bitc::VST_CODE_BBENTRY: {
2873       if (convertToString(Record, 1, ValueName))
2874         return error("Invalid bbentry record");
2875       BasicBlock *BB = getBasicBlock(Record[0]);
2876       if (!BB)
2877         return error("Invalid bbentry record");
2878 
2879       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2880       ValueName.clear();
2881       break;
2882     }
2883     }
2884   }
2885 }
2886 
2887 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2888 /// encoding.
2889 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2890   if ((V & 1) == 0)
2891     return V >> 1;
2892   if (V != 1)
2893     return -(V >> 1);
2894   // There is no such thing as -0 with integers.  "-0" really means MININT.
2895   return 1ULL << 63;
2896 }
2897 
2898 /// Resolve all of the initializers for global values and aliases that we can.
2899 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2900   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2901   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
2902   std::vector<FunctionOperandInfo> FunctionOperandWorklist;
2903 
2904   GlobalInitWorklist.swap(GlobalInits);
2905   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2906   FunctionOperandWorklist.swap(FunctionOperands);
2907 
2908   while (!GlobalInitWorklist.empty()) {
2909     unsigned ValID = GlobalInitWorklist.back().second;
2910     if (ValID >= ValueList.size()) {
2911       // Not ready to resolve this yet, it requires something later in the file.
2912       GlobalInits.push_back(GlobalInitWorklist.back());
2913     } else {
2914       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2915       if (!MaybeC)
2916         return MaybeC.takeError();
2917       GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
2918     }
2919     GlobalInitWorklist.pop_back();
2920   }
2921 
2922   while (!IndirectSymbolInitWorklist.empty()) {
2923     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2924     if (ValID >= ValueList.size()) {
2925       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2926     } else {
2927       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2928       if (!MaybeC)
2929         return MaybeC.takeError();
2930       Constant *C = MaybeC.get();
2931       GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
2932       if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
2933         if (C->getType() != GV->getType())
2934           return error("Alias and aliasee types don't match");
2935         GA->setAliasee(C);
2936       } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
2937         GI->setResolver(C);
2938       } else {
2939         return error("Expected an alias or an ifunc");
2940       }
2941     }
2942     IndirectSymbolInitWorklist.pop_back();
2943   }
2944 
2945   while (!FunctionOperandWorklist.empty()) {
2946     FunctionOperandInfo &Info = FunctionOperandWorklist.back();
2947     if (Info.PersonalityFn) {
2948       unsigned ValID = Info.PersonalityFn - 1;
2949       if (ValID < ValueList.size()) {
2950         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2951         if (!MaybeC)
2952           return MaybeC.takeError();
2953         Info.F->setPersonalityFn(MaybeC.get());
2954         Info.PersonalityFn = 0;
2955       }
2956     }
2957     if (Info.Prefix) {
2958       unsigned ValID = Info.Prefix - 1;
2959       if (ValID < ValueList.size()) {
2960         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2961         if (!MaybeC)
2962           return MaybeC.takeError();
2963         Info.F->setPrefixData(MaybeC.get());
2964         Info.Prefix = 0;
2965       }
2966     }
2967     if (Info.Prologue) {
2968       unsigned ValID = Info.Prologue - 1;
2969       if (ValID < ValueList.size()) {
2970         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2971         if (!MaybeC)
2972           return MaybeC.takeError();
2973         Info.F->setPrologueData(MaybeC.get());
2974         Info.Prologue = 0;
2975       }
2976     }
2977     if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
2978       FunctionOperands.push_back(Info);
2979     FunctionOperandWorklist.pop_back();
2980   }
2981 
2982   return Error::success();
2983 }
2984 
2985 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2986   SmallVector<uint64_t, 8> Words(Vals.size());
2987   transform(Vals, Words.begin(),
2988                  BitcodeReader::decodeSignRotatedValue);
2989 
2990   return APInt(TypeBits, Words);
2991 }
2992 
2993 Error BitcodeReader::parseConstants() {
2994   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2995     return Err;
2996 
2997   SmallVector<uint64_t, 64> Record;
2998 
2999   // Read all the records for this value table.
3000   Type *CurTy = Type::getInt32Ty(Context);
3001   unsigned Int32TyID = getVirtualTypeID(CurTy);
3002   unsigned CurTyID = Int32TyID;
3003   Type *CurElemTy = nullptr;
3004   unsigned NextCstNo = ValueList.size();
3005 
3006   while (true) {
3007     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3008     if (!MaybeEntry)
3009       return MaybeEntry.takeError();
3010     BitstreamEntry Entry = MaybeEntry.get();
3011 
3012     switch (Entry.Kind) {
3013     case BitstreamEntry::SubBlock: // Handled for us already.
3014     case BitstreamEntry::Error:
3015       return error("Malformed block");
3016     case BitstreamEntry::EndBlock:
3017       if (NextCstNo != ValueList.size())
3018         return error("Invalid constant reference");
3019       return Error::success();
3020     case BitstreamEntry::Record:
3021       // The interesting case.
3022       break;
3023     }
3024 
3025     // Read a record.
3026     Record.clear();
3027     Type *VoidType = Type::getVoidTy(Context);
3028     Value *V = nullptr;
3029     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3030     if (!MaybeBitCode)
3031       return MaybeBitCode.takeError();
3032     switch (unsigned BitCode = MaybeBitCode.get()) {
3033     default:  // Default behavior: unknown constant
3034     case bitc::CST_CODE_UNDEF:     // UNDEF
3035       V = UndefValue::get(CurTy);
3036       break;
3037     case bitc::CST_CODE_POISON:    // POISON
3038       V = PoisonValue::get(CurTy);
3039       break;
3040     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
3041       if (Record.empty())
3042         return error("Invalid settype record");
3043       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3044         return error("Invalid settype record");
3045       if (TypeList[Record[0]] == VoidType)
3046         return error("Invalid constant type");
3047       CurTyID = Record[0];
3048       CurTy = TypeList[CurTyID];
3049       CurElemTy = getPtrElementTypeByID(CurTyID);
3050       continue;  // Skip the ValueList manipulation.
3051     case bitc::CST_CODE_NULL:      // NULL
3052       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
3053         return error("Invalid type for a constant null value");
3054       if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
3055         if (!TETy->hasProperty(TargetExtType::HasZeroInit))
3056           return error("Invalid type for a constant null value");
3057       V = Constant::getNullValue(CurTy);
3058       break;
3059     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
3060       if (!CurTy->isIntegerTy() || Record.empty())
3061         return error("Invalid integer const record");
3062       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
3063       break;
3064     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3065       if (!CurTy->isIntegerTy() || Record.empty())
3066         return error("Invalid wide integer const record");
3067 
3068       APInt VInt =
3069           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
3070       V = ConstantInt::get(Context, VInt);
3071 
3072       break;
3073     }
3074     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
3075       if (Record.empty())
3076         return error("Invalid float const record");
3077       if (CurTy->isHalfTy())
3078         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
3079                                              APInt(16, (uint16_t)Record[0])));
3080       else if (CurTy->isBFloatTy())
3081         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
3082                                              APInt(16, (uint32_t)Record[0])));
3083       else if (CurTy->isFloatTy())
3084         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
3085                                              APInt(32, (uint32_t)Record[0])));
3086       else if (CurTy->isDoubleTy())
3087         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
3088                                              APInt(64, Record[0])));
3089       else if (CurTy->isX86_FP80Ty()) {
3090         // Bits are not stored the same way as a normal i80 APInt, compensate.
3091         uint64_t Rearrange[2];
3092         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3093         Rearrange[1] = Record[0] >> 48;
3094         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
3095                                              APInt(80, Rearrange)));
3096       } else if (CurTy->isFP128Ty())
3097         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
3098                                              APInt(128, Record)));
3099       else if (CurTy->isPPC_FP128Ty())
3100         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
3101                                              APInt(128, Record)));
3102       else
3103         V = UndefValue::get(CurTy);
3104       break;
3105     }
3106 
3107     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3108       if (Record.empty())
3109         return error("Invalid aggregate record");
3110 
3111       unsigned Size = Record.size();
3112       SmallVector<unsigned, 16> Elts;
3113       for (unsigned i = 0; i != Size; ++i)
3114         Elts.push_back(Record[i]);
3115 
3116       if (isa<StructType>(CurTy)) {
3117         V = BitcodeConstant::create(
3118             Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3119       } else if (isa<ArrayType>(CurTy)) {
3120         V = BitcodeConstant::create(Alloc, CurTy,
3121                                     BitcodeConstant::ConstantArrayOpcode, Elts);
3122       } else if (isa<VectorType>(CurTy)) {
3123         V = BitcodeConstant::create(
3124             Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3125       } else {
3126         V = UndefValue::get(CurTy);
3127       }
3128       break;
3129     }
3130     case bitc::CST_CODE_STRING:    // STRING: [values]
3131     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3132       if (Record.empty())
3133         return error("Invalid string record");
3134 
3135       SmallString<16> Elts(Record.begin(), Record.end());
3136       V = ConstantDataArray::getString(Context, Elts,
3137                                        BitCode == bitc::CST_CODE_CSTRING);
3138       break;
3139     }
3140     case bitc::CST_CODE_DATA: {// DATA: [n x value]
3141       if (Record.empty())
3142         return error("Invalid data record");
3143 
3144       Type *EltTy;
3145       if (auto *Array = dyn_cast<ArrayType>(CurTy))
3146         EltTy = Array->getElementType();
3147       else
3148         EltTy = cast<VectorType>(CurTy)->getElementType();
3149       if (EltTy->isIntegerTy(8)) {
3150         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3151         if (isa<VectorType>(CurTy))
3152           V = ConstantDataVector::get(Context, Elts);
3153         else
3154           V = ConstantDataArray::get(Context, Elts);
3155       } else if (EltTy->isIntegerTy(16)) {
3156         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3157         if (isa<VectorType>(CurTy))
3158           V = ConstantDataVector::get(Context, Elts);
3159         else
3160           V = ConstantDataArray::get(Context, Elts);
3161       } else if (EltTy->isIntegerTy(32)) {
3162         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3163         if (isa<VectorType>(CurTy))
3164           V = ConstantDataVector::get(Context, Elts);
3165         else
3166           V = ConstantDataArray::get(Context, Elts);
3167       } else if (EltTy->isIntegerTy(64)) {
3168         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3169         if (isa<VectorType>(CurTy))
3170           V = ConstantDataVector::get(Context, Elts);
3171         else
3172           V = ConstantDataArray::get(Context, Elts);
3173       } else if (EltTy->isHalfTy()) {
3174         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3175         if (isa<VectorType>(CurTy))
3176           V = ConstantDataVector::getFP(EltTy, Elts);
3177         else
3178           V = ConstantDataArray::getFP(EltTy, Elts);
3179       } else if (EltTy->isBFloatTy()) {
3180         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3181         if (isa<VectorType>(CurTy))
3182           V = ConstantDataVector::getFP(EltTy, Elts);
3183         else
3184           V = ConstantDataArray::getFP(EltTy, Elts);
3185       } else if (EltTy->isFloatTy()) {
3186         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3187         if (isa<VectorType>(CurTy))
3188           V = ConstantDataVector::getFP(EltTy, Elts);
3189         else
3190           V = ConstantDataArray::getFP(EltTy, Elts);
3191       } else if (EltTy->isDoubleTy()) {
3192         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3193         if (isa<VectorType>(CurTy))
3194           V = ConstantDataVector::getFP(EltTy, Elts);
3195         else
3196           V = ConstantDataArray::getFP(EltTy, Elts);
3197       } else {
3198         return error("Invalid type for value");
3199       }
3200       break;
3201     }
3202     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
3203       if (Record.size() < 2)
3204         return error("Invalid unary op constexpr record");
3205       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
3206       if (Opc < 0) {
3207         V = UndefValue::get(CurTy);  // Unknown unop.
3208       } else {
3209         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3210       }
3211       break;
3212     }
3213     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
3214       if (Record.size() < 3)
3215         return error("Invalid binary op constexpr record");
3216       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3217       if (Opc < 0) {
3218         V = UndefValue::get(CurTy);  // Unknown binop.
3219       } else {
3220         uint8_t Flags = 0;
3221         if (Record.size() >= 4) {
3222           if (Opc == Instruction::Add ||
3223               Opc == Instruction::Sub ||
3224               Opc == Instruction::Mul ||
3225               Opc == Instruction::Shl) {
3226             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3227               Flags |= OverflowingBinaryOperator::NoSignedWrap;
3228             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3229               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3230           } else if (Opc == Instruction::SDiv ||
3231                      Opc == Instruction::UDiv ||
3232                      Opc == Instruction::LShr ||
3233                      Opc == Instruction::AShr) {
3234             if (Record[3] & (1 << bitc::PEO_EXACT))
3235               Flags |= PossiblyExactOperator::IsExact;
3236           }
3237         }
3238         V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
3239                                     {(unsigned)Record[1], (unsigned)Record[2]});
3240       }
3241       break;
3242     }
3243     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
3244       if (Record.size() < 3)
3245         return error("Invalid cast constexpr record");
3246       int Opc = getDecodedCastOpcode(Record[0]);
3247       if (Opc < 0) {
3248         V = UndefValue::get(CurTy);  // Unknown cast.
3249       } else {
3250         unsigned OpTyID = Record[1];
3251         Type *OpTy = getTypeByID(OpTyID);
3252         if (!OpTy)
3253           return error("Invalid cast constexpr record");
3254         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3255       }
3256       break;
3257     }
3258     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3259     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
3260     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
3261                                                      // operands]
3262       if (Record.size() < 2)
3263         return error("Constant GEP record must have at least two elements");
3264       unsigned OpNum = 0;
3265       Type *PointeeType = nullptr;
3266       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
3267           Record.size() % 2)
3268         PointeeType = getTypeByID(Record[OpNum++]);
3269 
3270       bool InBounds = false;
3271       std::optional<unsigned> InRangeIndex;
3272       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
3273         uint64_t Op = Record[OpNum++];
3274         InBounds = Op & 1;
3275         InRangeIndex = Op >> 1;
3276       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3277         InBounds = true;
3278 
3279       SmallVector<unsigned, 16> Elts;
3280       unsigned BaseTypeID = Record[OpNum];
3281       while (OpNum != Record.size()) {
3282         unsigned ElTyID = Record[OpNum++];
3283         Type *ElTy = getTypeByID(ElTyID);
3284         if (!ElTy)
3285           return error("Invalid getelementptr constexpr record");
3286         Elts.push_back(Record[OpNum++]);
3287       }
3288 
3289       if (Elts.size() < 1)
3290         return error("Invalid gep with no operands");
3291 
3292       Type *BaseType = getTypeByID(BaseTypeID);
3293       if (isa<VectorType>(BaseType)) {
3294         BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3295         BaseType = getTypeByID(BaseTypeID);
3296       }
3297 
3298       PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
3299       if (!OrigPtrTy)
3300         return error("GEP base operand must be pointer or vector of pointer");
3301 
3302       if (!PointeeType) {
3303         PointeeType = getPtrElementTypeByID(BaseTypeID);
3304         if (!PointeeType)
3305           return error("Missing element type for old-style constant GEP");
3306       }
3307 
3308       V = BitcodeConstant::create(Alloc, CurTy,
3309                                   {Instruction::GetElementPtr, InBounds,
3310                                    InRangeIndex.value_or(-1), PointeeType},
3311                                   Elts);
3312       break;
3313     }
3314     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
3315       if (Record.size() < 3)
3316         return error("Invalid select constexpr record");
3317 
3318       V = BitcodeConstant::create(
3319           Alloc, CurTy, Instruction::Select,
3320           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3321       break;
3322     }
3323     case bitc::CST_CODE_CE_EXTRACTELT
3324         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3325       if (Record.size() < 3)
3326         return error("Invalid extractelement constexpr record");
3327       unsigned OpTyID = Record[0];
3328       VectorType *OpTy =
3329         dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3330       if (!OpTy)
3331         return error("Invalid extractelement constexpr record");
3332       unsigned IdxRecord;
3333       if (Record.size() == 4) {
3334         unsigned IdxTyID = Record[2];
3335         Type *IdxTy = getTypeByID(IdxTyID);
3336         if (!IdxTy)
3337           return error("Invalid extractelement constexpr record");
3338         IdxRecord = Record[3];
3339       } else {
3340         // Deprecated, but still needed to read old bitcode files.
3341         IdxRecord = Record[2];
3342       }
3343       V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3344                                   {(unsigned)Record[1], IdxRecord});
3345       break;
3346     }
3347     case bitc::CST_CODE_CE_INSERTELT
3348         : { // CE_INSERTELT: [opval, opval, opty, opval]
3349       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3350       if (Record.size() < 3 || !OpTy)
3351         return error("Invalid insertelement constexpr record");
3352       unsigned IdxRecord;
3353       if (Record.size() == 4) {
3354         unsigned IdxTyID = Record[2];
3355         Type *IdxTy = getTypeByID(IdxTyID);
3356         if (!IdxTy)
3357           return error("Invalid insertelement constexpr record");
3358         IdxRecord = Record[3];
3359       } else {
3360         // Deprecated, but still needed to read old bitcode files.
3361         IdxRecord = Record[2];
3362       }
3363       V = BitcodeConstant::create(
3364           Alloc, CurTy, Instruction::InsertElement,
3365           {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3366       break;
3367     }
3368     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3369       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3370       if (Record.size() < 3 || !OpTy)
3371         return error("Invalid shufflevector constexpr record");
3372       V = BitcodeConstant::create(
3373           Alloc, CurTy, Instruction::ShuffleVector,
3374           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3375       break;
3376     }
3377     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3378       VectorType *RTy = dyn_cast<VectorType>(CurTy);
3379       VectorType *OpTy =
3380         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3381       if (Record.size() < 4 || !RTy || !OpTy)
3382         return error("Invalid shufflevector constexpr record");
3383       V = BitcodeConstant::create(
3384           Alloc, CurTy, Instruction::ShuffleVector,
3385           {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
3386       break;
3387     }
3388     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
3389       if (Record.size() < 4)
3390         return error("Invalid cmp constexpt record");
3391       unsigned OpTyID = Record[0];
3392       Type *OpTy = getTypeByID(OpTyID);
3393       if (!OpTy)
3394         return error("Invalid cmp constexpr record");
3395       V = BitcodeConstant::create(
3396           Alloc, CurTy,
3397           {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3398                                               : Instruction::ICmp),
3399            (uint8_t)Record[3]},
3400           {(unsigned)Record[1], (unsigned)Record[2]});
3401       break;
3402     }
3403     // This maintains backward compatibility, pre-asm dialect keywords.
3404     // Deprecated, but still needed to read old bitcode files.
3405     case bitc::CST_CODE_INLINEASM_OLD: {
3406       if (Record.size() < 2)
3407         return error("Invalid inlineasm record");
3408       std::string AsmStr, ConstrStr;
3409       bool HasSideEffects = Record[0] & 1;
3410       bool IsAlignStack = Record[0] >> 1;
3411       unsigned AsmStrSize = Record[1];
3412       if (2+AsmStrSize >= Record.size())
3413         return error("Invalid inlineasm record");
3414       unsigned ConstStrSize = Record[2+AsmStrSize];
3415       if (3+AsmStrSize+ConstStrSize > Record.size())
3416         return error("Invalid inlineasm record");
3417 
3418       for (unsigned i = 0; i != AsmStrSize; ++i)
3419         AsmStr += (char)Record[2+i];
3420       for (unsigned i = 0; i != ConstStrSize; ++i)
3421         ConstrStr += (char)Record[3+AsmStrSize+i];
3422       UpgradeInlineAsmString(&AsmStr);
3423       if (!CurElemTy)
3424         return error("Missing element type for old-style inlineasm");
3425       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3426                          HasSideEffects, IsAlignStack);
3427       break;
3428     }
3429     // This version adds support for the asm dialect keywords (e.g.,
3430     // inteldialect).
3431     case bitc::CST_CODE_INLINEASM_OLD2: {
3432       if (Record.size() < 2)
3433         return error("Invalid inlineasm record");
3434       std::string AsmStr, ConstrStr;
3435       bool HasSideEffects = Record[0] & 1;
3436       bool IsAlignStack = (Record[0] >> 1) & 1;
3437       unsigned AsmDialect = Record[0] >> 2;
3438       unsigned AsmStrSize = Record[1];
3439       if (2+AsmStrSize >= Record.size())
3440         return error("Invalid inlineasm record");
3441       unsigned ConstStrSize = Record[2+AsmStrSize];
3442       if (3+AsmStrSize+ConstStrSize > Record.size())
3443         return error("Invalid inlineasm record");
3444 
3445       for (unsigned i = 0; i != AsmStrSize; ++i)
3446         AsmStr += (char)Record[2+i];
3447       for (unsigned i = 0; i != ConstStrSize; ++i)
3448         ConstrStr += (char)Record[3+AsmStrSize+i];
3449       UpgradeInlineAsmString(&AsmStr);
3450       if (!CurElemTy)
3451         return error("Missing element type for old-style inlineasm");
3452       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3453                          HasSideEffects, IsAlignStack,
3454                          InlineAsm::AsmDialect(AsmDialect));
3455       break;
3456     }
3457     // This version adds support for the unwind keyword.
3458     case bitc::CST_CODE_INLINEASM_OLD3: {
3459       if (Record.size() < 2)
3460         return error("Invalid inlineasm record");
3461       unsigned OpNum = 0;
3462       std::string AsmStr, ConstrStr;
3463       bool HasSideEffects = Record[OpNum] & 1;
3464       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3465       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3466       bool CanThrow = (Record[OpNum] >> 3) & 1;
3467       ++OpNum;
3468       unsigned AsmStrSize = Record[OpNum];
3469       ++OpNum;
3470       if (OpNum + AsmStrSize >= Record.size())
3471         return error("Invalid inlineasm record");
3472       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3473       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3474         return error("Invalid inlineasm record");
3475 
3476       for (unsigned i = 0; i != AsmStrSize; ++i)
3477         AsmStr += (char)Record[OpNum + i];
3478       ++OpNum;
3479       for (unsigned i = 0; i != ConstStrSize; ++i)
3480         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3481       UpgradeInlineAsmString(&AsmStr);
3482       if (!CurElemTy)
3483         return error("Missing element type for old-style inlineasm");
3484       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3485                          HasSideEffects, IsAlignStack,
3486                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
3487       break;
3488     }
3489     // This version adds explicit function type.
3490     case bitc::CST_CODE_INLINEASM: {
3491       if (Record.size() < 3)
3492         return error("Invalid inlineasm record");
3493       unsigned OpNum = 0;
3494       auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
3495       ++OpNum;
3496       if (!FnTy)
3497         return error("Invalid inlineasm record");
3498       std::string AsmStr, ConstrStr;
3499       bool HasSideEffects = Record[OpNum] & 1;
3500       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3501       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3502       bool CanThrow = (Record[OpNum] >> 3) & 1;
3503       ++OpNum;
3504       unsigned AsmStrSize = Record[OpNum];
3505       ++OpNum;
3506       if (OpNum + AsmStrSize >= Record.size())
3507         return error("Invalid inlineasm record");
3508       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3509       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3510         return error("Invalid inlineasm record");
3511 
3512       for (unsigned i = 0; i != AsmStrSize; ++i)
3513         AsmStr += (char)Record[OpNum + i];
3514       ++OpNum;
3515       for (unsigned i = 0; i != ConstStrSize; ++i)
3516         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3517       UpgradeInlineAsmString(&AsmStr);
3518       V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3519                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
3520       break;
3521     }
3522     case bitc::CST_CODE_BLOCKADDRESS:{
3523       if (Record.size() < 3)
3524         return error("Invalid blockaddress record");
3525       unsigned FnTyID = Record[0];
3526       Type *FnTy = getTypeByID(FnTyID);
3527       if (!FnTy)
3528         return error("Invalid blockaddress record");
3529       V = BitcodeConstant::create(
3530           Alloc, CurTy,
3531           {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3532           Record[1]);
3533       break;
3534     }
3535     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3536       if (Record.size() < 2)
3537         return error("Invalid dso_local record");
3538       unsigned GVTyID = Record[0];
3539       Type *GVTy = getTypeByID(GVTyID);
3540       if (!GVTy)
3541         return error("Invalid dso_local record");
3542       V = BitcodeConstant::create(
3543           Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3544       break;
3545     }
3546     case bitc::CST_CODE_NO_CFI_VALUE: {
3547       if (Record.size() < 2)
3548         return error("Invalid no_cfi record");
3549       unsigned GVTyID = Record[0];
3550       Type *GVTy = getTypeByID(GVTyID);
3551       if (!GVTy)
3552         return error("Invalid no_cfi record");
3553       V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3554                                   Record[1]);
3555       break;
3556     }
3557     }
3558 
3559     assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3560     if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
3561       return Err;
3562     ++NextCstNo;
3563   }
3564 }
3565 
3566 Error BitcodeReader::parseUseLists() {
3567   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3568     return Err;
3569 
3570   // Read all the records.
3571   SmallVector<uint64_t, 64> Record;
3572 
3573   while (true) {
3574     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3575     if (!MaybeEntry)
3576       return MaybeEntry.takeError();
3577     BitstreamEntry Entry = MaybeEntry.get();
3578 
3579     switch (Entry.Kind) {
3580     case BitstreamEntry::SubBlock: // Handled for us already.
3581     case BitstreamEntry::Error:
3582       return error("Malformed block");
3583     case BitstreamEntry::EndBlock:
3584       return Error::success();
3585     case BitstreamEntry::Record:
3586       // The interesting case.
3587       break;
3588     }
3589 
3590     // Read a use list record.
3591     Record.clear();
3592     bool IsBB = false;
3593     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3594     if (!MaybeRecord)
3595       return MaybeRecord.takeError();
3596     switch (MaybeRecord.get()) {
3597     default:  // Default behavior: unknown type.
3598       break;
3599     case bitc::USELIST_CODE_BB:
3600       IsBB = true;
3601       [[fallthrough]];
3602     case bitc::USELIST_CODE_DEFAULT: {
3603       unsigned RecordLength = Record.size();
3604       if (RecordLength < 3)
3605         // Records should have at least an ID and two indexes.
3606         return error("Invalid record");
3607       unsigned ID = Record.pop_back_val();
3608 
3609       Value *V;
3610       if (IsBB) {
3611         assert(ID < FunctionBBs.size() && "Basic block not found");
3612         V = FunctionBBs[ID];
3613       } else
3614         V = ValueList[ID];
3615       unsigned NumUses = 0;
3616       SmallDenseMap<const Use *, unsigned, 16> Order;
3617       for (const Use &U : V->materialized_uses()) {
3618         if (++NumUses > Record.size())
3619           break;
3620         Order[&U] = Record[NumUses - 1];
3621       }
3622       if (Order.size() != Record.size() || NumUses > Record.size())
3623         // Mismatches can happen if the functions are being materialized lazily
3624         // (out-of-order), or a value has been upgraded.
3625         break;
3626 
3627       V->sortUseList([&](const Use &L, const Use &R) {
3628         return Order.lookup(&L) < Order.lookup(&R);
3629       });
3630       break;
3631     }
3632     }
3633   }
3634 }
3635 
3636 /// When we see the block for metadata, remember where it is and then skip it.
3637 /// This lets us lazily deserialize the metadata.
3638 Error BitcodeReader::rememberAndSkipMetadata() {
3639   // Save the current stream state.
3640   uint64_t CurBit = Stream.GetCurrentBitNo();
3641   DeferredMetadataInfo.push_back(CurBit);
3642 
3643   // Skip over the block for now.
3644   if (Error Err = Stream.SkipBlock())
3645     return Err;
3646   return Error::success();
3647 }
3648 
3649 Error BitcodeReader::materializeMetadata() {
3650   for (uint64_t BitPos : DeferredMetadataInfo) {
3651     // Move the bit stream to the saved position.
3652     if (Error JumpFailed = Stream.JumpToBit(BitPos))
3653       return JumpFailed;
3654     if (Error Err = MDLoader->parseModuleMetadata())
3655       return Err;
3656   }
3657 
3658   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3659   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3660   // multiple times.
3661   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3662     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3663       NamedMDNode *LinkerOpts =
3664           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3665       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3666         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3667     }
3668   }
3669 
3670   DeferredMetadataInfo.clear();
3671   return Error::success();
3672 }
3673 
3674 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3675 
3676 /// When we see the block for a function body, remember where it is and then
3677 /// skip it.  This lets us lazily deserialize the functions.
3678 Error BitcodeReader::rememberAndSkipFunctionBody() {
3679   // Get the function we are talking about.
3680   if (FunctionsWithBodies.empty())
3681     return error("Insufficient function protos");
3682 
3683   Function *Fn = FunctionsWithBodies.back();
3684   FunctionsWithBodies.pop_back();
3685 
3686   // Save the current stream state.
3687   uint64_t CurBit = Stream.GetCurrentBitNo();
3688   assert(
3689       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3690       "Mismatch between VST and scanned function offsets");
3691   DeferredFunctionInfo[Fn] = CurBit;
3692 
3693   // Skip over the function block for now.
3694   if (Error Err = Stream.SkipBlock())
3695     return Err;
3696   return Error::success();
3697 }
3698 
3699 Error BitcodeReader::globalCleanup() {
3700   // Patch the initializers for globals and aliases up.
3701   if (Error Err = resolveGlobalAndIndirectSymbolInits())
3702     return Err;
3703   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3704     return error("Malformed global initializer set");
3705 
3706   // Look for intrinsic functions which need to be upgraded at some point
3707   // and functions that need to have their function attributes upgraded.
3708   for (Function &F : *TheModule) {
3709     MDLoader->upgradeDebugIntrinsics(F);
3710     Function *NewFn;
3711     if (UpgradeIntrinsicFunction(&F, NewFn))
3712       UpgradedIntrinsics[&F] = NewFn;
3713     // Look for functions that rely on old function attribute behavior.
3714     UpgradeFunctionAttributes(F);
3715   }
3716 
3717   // Look for global variables which need to be renamed.
3718   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3719   for (GlobalVariable &GV : TheModule->globals())
3720     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3721       UpgradedVariables.emplace_back(&GV, Upgraded);
3722   for (auto &Pair : UpgradedVariables) {
3723     Pair.first->eraseFromParent();
3724     TheModule->insertGlobalVariable(Pair.second);
3725   }
3726 
3727   // Force deallocation of memory for these vectors to favor the client that
3728   // want lazy deserialization.
3729   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3730   std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3731   return Error::success();
3732 }
3733 
3734 /// Support for lazy parsing of function bodies. This is required if we
3735 /// either have an old bitcode file without a VST forward declaration record,
3736 /// or if we have an anonymous function being materialized, since anonymous
3737 /// functions do not have a name and are therefore not in the VST.
3738 Error BitcodeReader::rememberAndSkipFunctionBodies() {
3739   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3740     return JumpFailed;
3741 
3742   if (Stream.AtEndOfStream())
3743     return error("Could not find function in stream");
3744 
3745   if (!SeenFirstFunctionBody)
3746     return error("Trying to materialize functions before seeing function blocks");
3747 
3748   // An old bitcode file with the symbol table at the end would have
3749   // finished the parse greedily.
3750   assert(SeenValueSymbolTable);
3751 
3752   SmallVector<uint64_t, 64> Record;
3753 
3754   while (true) {
3755     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3756     if (!MaybeEntry)
3757       return MaybeEntry.takeError();
3758     llvm::BitstreamEntry Entry = MaybeEntry.get();
3759 
3760     switch (Entry.Kind) {
3761     default:
3762       return error("Expect SubBlock");
3763     case BitstreamEntry::SubBlock:
3764       switch (Entry.ID) {
3765       default:
3766         return error("Expect function block");
3767       case bitc::FUNCTION_BLOCK_ID:
3768         if (Error Err = rememberAndSkipFunctionBody())
3769           return Err;
3770         NextUnreadBit = Stream.GetCurrentBitNo();
3771         return Error::success();
3772       }
3773     }
3774   }
3775 }
3776 
3777 Error BitcodeReaderBase::readBlockInfo() {
3778   Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3779       Stream.ReadBlockInfoBlock();
3780   if (!MaybeNewBlockInfo)
3781     return MaybeNewBlockInfo.takeError();
3782   std::optional<BitstreamBlockInfo> NewBlockInfo =
3783       std::move(MaybeNewBlockInfo.get());
3784   if (!NewBlockInfo)
3785     return error("Malformed block");
3786   BlockInfo = std::move(*NewBlockInfo);
3787   return Error::success();
3788 }
3789 
3790 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3791   // v1: [selection_kind, name]
3792   // v2: [strtab_offset, strtab_size, selection_kind]
3793   StringRef Name;
3794   std::tie(Name, Record) = readNameFromStrtab(Record);
3795 
3796   if (Record.empty())
3797     return error("Invalid record");
3798   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3799   std::string OldFormatName;
3800   if (!UseStrtab) {
3801     if (Record.size() < 2)
3802       return error("Invalid record");
3803     unsigned ComdatNameSize = Record[1];
3804     if (ComdatNameSize > Record.size() - 2)
3805       return error("Comdat name size too large");
3806     OldFormatName.reserve(ComdatNameSize);
3807     for (unsigned i = 0; i != ComdatNameSize; ++i)
3808       OldFormatName += (char)Record[2 + i];
3809     Name = OldFormatName;
3810   }
3811   Comdat *C = TheModule->getOrInsertComdat(Name);
3812   C->setSelectionKind(SK);
3813   ComdatList.push_back(C);
3814   return Error::success();
3815 }
3816 
3817 static void inferDSOLocal(GlobalValue *GV) {
3818   // infer dso_local from linkage and visibility if it is not encoded.
3819   if (GV->hasLocalLinkage() ||
3820       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3821     GV->setDSOLocal(true);
3822 }
3823 
3824 GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
3825   GlobalValue::SanitizerMetadata Meta;
3826   if (V & (1 << 0))
3827     Meta.NoAddress = true;
3828   if (V & (1 << 1))
3829     Meta.NoHWAddress = true;
3830   if (V & (1 << 2))
3831     Meta.Memtag = true;
3832   if (V & (1 << 3))
3833     Meta.IsDynInit = true;
3834   return Meta;
3835 }
3836 
3837 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3838   // v1: [pointer type, isconst, initid, linkage, alignment, section,
3839   // visibility, threadlocal, unnamed_addr, externally_initialized,
3840   // dllstorageclass, comdat, attributes, preemption specifier,
3841   // partition strtab offset, partition strtab size] (name in VST)
3842   // v2: [strtab_offset, strtab_size, v1]
3843   // v3: [v2, code_model]
3844   StringRef Name;
3845   std::tie(Name, Record) = readNameFromStrtab(Record);
3846 
3847   if (Record.size() < 6)
3848     return error("Invalid record");
3849   unsigned TyID = Record[0];
3850   Type *Ty = getTypeByID(TyID);
3851   if (!Ty)
3852     return error("Invalid record");
3853   bool isConstant = Record[1] & 1;
3854   bool explicitType = Record[1] & 2;
3855   unsigned AddressSpace;
3856   if (explicitType) {
3857     AddressSpace = Record[1] >> 2;
3858   } else {
3859     if (!Ty->isPointerTy())
3860       return error("Invalid type for value");
3861     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3862     TyID = getContainedTypeID(TyID);
3863     Ty = getTypeByID(TyID);
3864     if (!Ty)
3865       return error("Missing element type for old-style global");
3866   }
3867 
3868   uint64_t RawLinkage = Record[3];
3869   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3870   MaybeAlign Alignment;
3871   if (Error Err = parseAlignmentValue(Record[4], Alignment))
3872     return Err;
3873   std::string Section;
3874   if (Record[5]) {
3875     if (Record[5] - 1 >= SectionTable.size())
3876       return error("Invalid ID");
3877     Section = SectionTable[Record[5] - 1];
3878   }
3879   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3880   // Local linkage must have default visibility.
3881   // auto-upgrade `hidden` and `protected` for old bitcode.
3882   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3883     Visibility = getDecodedVisibility(Record[6]);
3884 
3885   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3886   if (Record.size() > 7)
3887     TLM = getDecodedThreadLocalMode(Record[7]);
3888 
3889   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3890   if (Record.size() > 8)
3891     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3892 
3893   bool ExternallyInitialized = false;
3894   if (Record.size() > 9)
3895     ExternallyInitialized = Record[9];
3896 
3897   GlobalVariable *NewGV =
3898       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3899                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3900   if (Alignment)
3901     NewGV->setAlignment(*Alignment);
3902   if (!Section.empty())
3903     NewGV->setSection(Section);
3904   NewGV->setVisibility(Visibility);
3905   NewGV->setUnnamedAddr(UnnamedAddr);
3906 
3907   if (Record.size() > 10) {
3908     // A GlobalValue with local linkage cannot have a DLL storage class.
3909     if (!NewGV->hasLocalLinkage()) {
3910       NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3911     }
3912   } else {
3913     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3914   }
3915 
3916   ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
3917 
3918   // Remember which value to use for the global initializer.
3919   if (unsigned InitID = Record[2])
3920     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3921 
3922   if (Record.size() > 11) {
3923     if (unsigned ComdatID = Record[11]) {
3924       if (ComdatID > ComdatList.size())
3925         return error("Invalid global variable comdat ID");
3926       NewGV->setComdat(ComdatList[ComdatID - 1]);
3927     }
3928   } else if (hasImplicitComdat(RawLinkage)) {
3929     ImplicitComdatObjects.insert(NewGV);
3930   }
3931 
3932   if (Record.size() > 12) {
3933     auto AS = getAttributes(Record[12]).getFnAttrs();
3934     NewGV->setAttributes(AS);
3935   }
3936 
3937   if (Record.size() > 13) {
3938     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3939   }
3940   inferDSOLocal(NewGV);
3941 
3942   // Check whether we have enough values to read a partition name.
3943   if (Record.size() > 15)
3944     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3945 
3946   if (Record.size() > 16 && Record[16]) {
3947     llvm::GlobalValue::SanitizerMetadata Meta =
3948         deserializeSanitizerMetadata(Record[16]);
3949     NewGV->setSanitizerMetadata(Meta);
3950   }
3951 
3952   if (Record.size() > 17 && Record[17]) {
3953     if (auto CM = getDecodedCodeModel(Record[17]))
3954       NewGV->setCodeModel(*CM);
3955     else
3956       return error("Invalid global variable code model");
3957   }
3958 
3959   return Error::success();
3960 }
3961 
3962 void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
3963   if (ValueTypeCallback) {
3964     (*ValueTypeCallback)(
3965         F, TypeID, [this](unsigned I) { return getTypeByID(I); },
3966         [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
3967   }
3968 }
3969 
3970 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3971   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3972   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3973   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
3974   // v2: [strtab_offset, strtab_size, v1]
3975   StringRef Name;
3976   std::tie(Name, Record) = readNameFromStrtab(Record);
3977 
3978   if (Record.size() < 8)
3979     return error("Invalid record");
3980   unsigned FTyID = Record[0];
3981   Type *FTy = getTypeByID(FTyID);
3982   if (!FTy)
3983     return error("Invalid record");
3984   if (isa<PointerType>(FTy)) {
3985     FTyID = getContainedTypeID(FTyID, 0);
3986     FTy = getTypeByID(FTyID);
3987     if (!FTy)
3988       return error("Missing element type for old-style function");
3989   }
3990 
3991   if (!isa<FunctionType>(FTy))
3992     return error("Invalid type for value");
3993   auto CC = static_cast<CallingConv::ID>(Record[1]);
3994   if (CC & ~CallingConv::MaxID)
3995     return error("Invalid calling convention ID");
3996 
3997   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3998   if (Record.size() > 16)
3999     AddrSpace = Record[16];
4000 
4001   Function *Func =
4002       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
4003                        AddrSpace, Name, TheModule);
4004 
4005   assert(Func->getFunctionType() == FTy &&
4006          "Incorrect fully specified type provided for function");
4007   FunctionTypeIDs[Func] = FTyID;
4008 
4009   Func->setCallingConv(CC);
4010   bool isProto = Record[2];
4011   uint64_t RawLinkage = Record[3];
4012   Func->setLinkage(getDecodedLinkage(RawLinkage));
4013   Func->setAttributes(getAttributes(Record[4]));
4014   callValueTypeCallback(Func, FTyID);
4015 
4016   // Upgrade any old-style byval or sret without a type by propagating the
4017   // argument's pointee type. There should be no opaque pointers where the byval
4018   // type is implicit.
4019   for (unsigned i = 0; i != Func->arg_size(); ++i) {
4020     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4021                                      Attribute::InAlloca}) {
4022       if (!Func->hasParamAttribute(i, Kind))
4023         continue;
4024 
4025       if (Func->getParamAttribute(i, Kind).getValueAsType())
4026         continue;
4027 
4028       Func->removeParamAttr(i, Kind);
4029 
4030       unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4031       Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4032       if (!PtrEltTy)
4033         return error("Missing param element type for attribute upgrade");
4034 
4035       Attribute NewAttr;
4036       switch (Kind) {
4037       case Attribute::ByVal:
4038         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4039         break;
4040       case Attribute::StructRet:
4041         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4042         break;
4043       case Attribute::InAlloca:
4044         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4045         break;
4046       default:
4047         llvm_unreachable("not an upgraded type attribute");
4048       }
4049 
4050       Func->addParamAttr(i, NewAttr);
4051     }
4052   }
4053 
4054   if (Func->getCallingConv() == CallingConv::X86_INTR &&
4055       !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
4056     unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4057     Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4058     if (!ByValTy)
4059       return error("Missing param element type for x86_intrcc upgrade");
4060     Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
4061     Func->addParamAttr(0, NewAttr);
4062   }
4063 
4064   MaybeAlign Alignment;
4065   if (Error Err = parseAlignmentValue(Record[5], Alignment))
4066     return Err;
4067   if (Alignment)
4068     Func->setAlignment(*Alignment);
4069   if (Record[6]) {
4070     if (Record[6] - 1 >= SectionTable.size())
4071       return error("Invalid ID");
4072     Func->setSection(SectionTable[Record[6] - 1]);
4073   }
4074   // Local linkage must have default visibility.
4075   // auto-upgrade `hidden` and `protected` for old bitcode.
4076   if (!Func->hasLocalLinkage())
4077     Func->setVisibility(getDecodedVisibility(Record[7]));
4078   if (Record.size() > 8 && Record[8]) {
4079     if (Record[8] - 1 >= GCTable.size())
4080       return error("Invalid ID");
4081     Func->setGC(GCTable[Record[8] - 1]);
4082   }
4083   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4084   if (Record.size() > 9)
4085     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
4086   Func->setUnnamedAddr(UnnamedAddr);
4087 
4088   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4089   if (Record.size() > 10)
4090     OperandInfo.Prologue = Record[10];
4091 
4092   if (Record.size() > 11) {
4093     // A GlobalValue with local linkage cannot have a DLL storage class.
4094     if (!Func->hasLocalLinkage()) {
4095       Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4096     }
4097   } else {
4098     upgradeDLLImportExportLinkage(Func, RawLinkage);
4099   }
4100 
4101   if (Record.size() > 12) {
4102     if (unsigned ComdatID = Record[12]) {
4103       if (ComdatID > ComdatList.size())
4104         return error("Invalid function comdat ID");
4105       Func->setComdat(ComdatList[ComdatID - 1]);
4106     }
4107   } else if (hasImplicitComdat(RawLinkage)) {
4108     ImplicitComdatObjects.insert(Func);
4109   }
4110 
4111   if (Record.size() > 13)
4112     OperandInfo.Prefix = Record[13];
4113 
4114   if (Record.size() > 14)
4115     OperandInfo.PersonalityFn = Record[14];
4116 
4117   if (Record.size() > 15) {
4118     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
4119   }
4120   inferDSOLocal(Func);
4121 
4122   // Record[16] is the address space number.
4123 
4124   // Check whether we have enough values to read a partition name. Also make
4125   // sure Strtab has enough values.
4126   if (Record.size() > 18 && Strtab.data() &&
4127       Record[17] + Record[18] <= Strtab.size()) {
4128     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4129   }
4130 
4131   ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
4132 
4133   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4134     FunctionOperands.push_back(OperandInfo);
4135 
4136   // If this is a function with a body, remember the prototype we are
4137   // creating now, so that we can match up the body with them later.
4138   if (!isProto) {
4139     Func->setIsMaterializable(true);
4140     FunctionsWithBodies.push_back(Func);
4141     DeferredFunctionInfo[Func] = 0;
4142   }
4143   return Error::success();
4144 }
4145 
4146 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4147     unsigned BitCode, ArrayRef<uint64_t> Record) {
4148   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4149   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4150   // dllstorageclass, threadlocal, unnamed_addr,
4151   // preemption specifier] (name in VST)
4152   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4153   // visibility, dllstorageclass, threadlocal, unnamed_addr,
4154   // preemption specifier] (name in VST)
4155   // v2: [strtab_offset, strtab_size, v1]
4156   StringRef Name;
4157   std::tie(Name, Record) = readNameFromStrtab(Record);
4158 
4159   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4160   if (Record.size() < (3 + (unsigned)NewRecord))
4161     return error("Invalid record");
4162   unsigned OpNum = 0;
4163   unsigned TypeID = Record[OpNum++];
4164   Type *Ty = getTypeByID(TypeID);
4165   if (!Ty)
4166     return error("Invalid record");
4167 
4168   unsigned AddrSpace;
4169   if (!NewRecord) {
4170     auto *PTy = dyn_cast<PointerType>(Ty);
4171     if (!PTy)
4172       return error("Invalid type for value");
4173     AddrSpace = PTy->getAddressSpace();
4174     TypeID = getContainedTypeID(TypeID);
4175     Ty = getTypeByID(TypeID);
4176     if (!Ty)
4177       return error("Missing element type for old-style indirect symbol");
4178   } else {
4179     AddrSpace = Record[OpNum++];
4180   }
4181 
4182   auto Val = Record[OpNum++];
4183   auto Linkage = Record[OpNum++];
4184   GlobalValue *NewGA;
4185   if (BitCode == bitc::MODULE_CODE_ALIAS ||
4186       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4187     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4188                                 TheModule);
4189   else
4190     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4191                                 nullptr, TheModule);
4192 
4193   // Local linkage must have default visibility.
4194   // auto-upgrade `hidden` and `protected` for old bitcode.
4195   if (OpNum != Record.size()) {
4196     auto VisInd = OpNum++;
4197     if (!NewGA->hasLocalLinkage())
4198       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4199   }
4200   if (BitCode == bitc::MODULE_CODE_ALIAS ||
4201       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4202     if (OpNum != Record.size()) {
4203       auto S = Record[OpNum++];
4204       // A GlobalValue with local linkage cannot have a DLL storage class.
4205       if (!NewGA->hasLocalLinkage())
4206         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S));
4207     }
4208     else
4209       upgradeDLLImportExportLinkage(NewGA, Linkage);
4210     if (OpNum != Record.size())
4211       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4212     if (OpNum != Record.size())
4213       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4214   }
4215   if (OpNum != Record.size())
4216     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4217   inferDSOLocal(NewGA);
4218 
4219   // Check whether we have enough values to read a partition name.
4220   if (OpNum + 1 < Record.size()) {
4221     // Check Strtab has enough values for the partition.
4222     if (Record[OpNum] + Record[OpNum + 1] > Strtab.size())
4223       return error("Malformed partition, too large.");
4224     NewGA->setPartition(
4225         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4226     OpNum += 2;
4227   }
4228 
4229   ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
4230   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4231   return Error::success();
4232 }
4233 
4234 Error BitcodeReader::parseModule(uint64_t ResumeBit,
4235                                  bool ShouldLazyLoadMetadata,
4236                                  ParserCallbacks Callbacks) {
4237   this->ValueTypeCallback = std::move(Callbacks.ValueType);
4238   if (ResumeBit) {
4239     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4240       return JumpFailed;
4241   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4242     return Err;
4243 
4244   SmallVector<uint64_t, 64> Record;
4245 
4246   // Parts of bitcode parsing depend on the datalayout.  Make sure we
4247   // finalize the datalayout before we run any of that code.
4248   bool ResolvedDataLayout = false;
4249   // In order to support importing modules with illegal data layout strings,
4250   // delay parsing the data layout string until after upgrades and overrides
4251   // have been applied, allowing to fix illegal data layout strings.
4252   // Initialize to the current module's layout string in case none is specified.
4253   std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4254 
4255   auto ResolveDataLayout = [&]() -> Error {
4256     if (ResolvedDataLayout)
4257       return Error::success();
4258 
4259     // Datalayout and triple can't be parsed after this point.
4260     ResolvedDataLayout = true;
4261 
4262     // Auto-upgrade the layout string
4263     TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4264         TentativeDataLayoutStr, TheModule->getTargetTriple());
4265 
4266     // Apply override
4267     if (Callbacks.DataLayout) {
4268       if (auto LayoutOverride = (*Callbacks.DataLayout)(
4269               TheModule->getTargetTriple(), TentativeDataLayoutStr))
4270         TentativeDataLayoutStr = *LayoutOverride;
4271     }
4272 
4273     // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4274     Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4275     if (!MaybeDL)
4276       return MaybeDL.takeError();
4277 
4278     TheModule->setDataLayout(MaybeDL.get());
4279     return Error::success();
4280   };
4281 
4282   // Read all the records for this module.
4283   while (true) {
4284     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4285     if (!MaybeEntry)
4286       return MaybeEntry.takeError();
4287     llvm::BitstreamEntry Entry = MaybeEntry.get();
4288 
4289     switch (Entry.Kind) {
4290     case BitstreamEntry::Error:
4291       return error("Malformed block");
4292     case BitstreamEntry::EndBlock:
4293       if (Error Err = ResolveDataLayout())
4294         return Err;
4295       return globalCleanup();
4296 
4297     case BitstreamEntry::SubBlock:
4298       switch (Entry.ID) {
4299       default:  // Skip unknown content.
4300         if (Error Err = Stream.SkipBlock())
4301           return Err;
4302         break;
4303       case bitc::BLOCKINFO_BLOCK_ID:
4304         if (Error Err = readBlockInfo())
4305           return Err;
4306         break;
4307       case bitc::PARAMATTR_BLOCK_ID:
4308         if (Error Err = parseAttributeBlock())
4309           return Err;
4310         break;
4311       case bitc::PARAMATTR_GROUP_BLOCK_ID:
4312         if (Error Err = parseAttributeGroupBlock())
4313           return Err;
4314         break;
4315       case bitc::TYPE_BLOCK_ID_NEW:
4316         if (Error Err = parseTypeTable())
4317           return Err;
4318         break;
4319       case bitc::VALUE_SYMTAB_BLOCK_ID:
4320         if (!SeenValueSymbolTable) {
4321           // Either this is an old form VST without function index and an
4322           // associated VST forward declaration record (which would have caused
4323           // the VST to be jumped to and parsed before it was encountered
4324           // normally in the stream), or there were no function blocks to
4325           // trigger an earlier parsing of the VST.
4326           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4327           if (Error Err = parseValueSymbolTable())
4328             return Err;
4329           SeenValueSymbolTable = true;
4330         } else {
4331           // We must have had a VST forward declaration record, which caused
4332           // the parser to jump to and parse the VST earlier.
4333           assert(VSTOffset > 0);
4334           if (Error Err = Stream.SkipBlock())
4335             return Err;
4336         }
4337         break;
4338       case bitc::CONSTANTS_BLOCK_ID:
4339         if (Error Err = parseConstants())
4340           return Err;
4341         if (Error Err = resolveGlobalAndIndirectSymbolInits())
4342           return Err;
4343         break;
4344       case bitc::METADATA_BLOCK_ID:
4345         if (ShouldLazyLoadMetadata) {
4346           if (Error Err = rememberAndSkipMetadata())
4347             return Err;
4348           break;
4349         }
4350         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4351         if (Error Err = MDLoader->parseModuleMetadata())
4352           return Err;
4353         break;
4354       case bitc::METADATA_KIND_BLOCK_ID:
4355         if (Error Err = MDLoader->parseMetadataKinds())
4356           return Err;
4357         break;
4358       case bitc::FUNCTION_BLOCK_ID:
4359         if (Error Err = ResolveDataLayout())
4360           return Err;
4361 
4362         // If this is the first function body we've seen, reverse the
4363         // FunctionsWithBodies list.
4364         if (!SeenFirstFunctionBody) {
4365           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4366           if (Error Err = globalCleanup())
4367             return Err;
4368           SeenFirstFunctionBody = true;
4369         }
4370 
4371         if (VSTOffset > 0) {
4372           // If we have a VST forward declaration record, make sure we
4373           // parse the VST now if we haven't already. It is needed to
4374           // set up the DeferredFunctionInfo vector for lazy reading.
4375           if (!SeenValueSymbolTable) {
4376             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4377               return Err;
4378             SeenValueSymbolTable = true;
4379             // Fall through so that we record the NextUnreadBit below.
4380             // This is necessary in case we have an anonymous function that
4381             // is later materialized. Since it will not have a VST entry we
4382             // need to fall back to the lazy parse to find its offset.
4383           } else {
4384             // If we have a VST forward declaration record, but have already
4385             // parsed the VST (just above, when the first function body was
4386             // encountered here), then we are resuming the parse after
4387             // materializing functions. The ResumeBit points to the
4388             // start of the last function block recorded in the
4389             // DeferredFunctionInfo map. Skip it.
4390             if (Error Err = Stream.SkipBlock())
4391               return Err;
4392             continue;
4393           }
4394         }
4395 
4396         // Support older bitcode files that did not have the function
4397         // index in the VST, nor a VST forward declaration record, as
4398         // well as anonymous functions that do not have VST entries.
4399         // Build the DeferredFunctionInfo vector on the fly.
4400         if (Error Err = rememberAndSkipFunctionBody())
4401           return Err;
4402 
4403         // Suspend parsing when we reach the function bodies. Subsequent
4404         // materialization calls will resume it when necessary. If the bitcode
4405         // file is old, the symbol table will be at the end instead and will not
4406         // have been seen yet. In this case, just finish the parse now.
4407         if (SeenValueSymbolTable) {
4408           NextUnreadBit = Stream.GetCurrentBitNo();
4409           // After the VST has been parsed, we need to make sure intrinsic name
4410           // are auto-upgraded.
4411           return globalCleanup();
4412         }
4413         break;
4414       case bitc::USELIST_BLOCK_ID:
4415         if (Error Err = parseUseLists())
4416           return Err;
4417         break;
4418       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
4419         if (Error Err = parseOperandBundleTags())
4420           return Err;
4421         break;
4422       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
4423         if (Error Err = parseSyncScopeNames())
4424           return Err;
4425         break;
4426       }
4427       continue;
4428 
4429     case BitstreamEntry::Record:
4430       // The interesting case.
4431       break;
4432     }
4433 
4434     // Read a record.
4435     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4436     if (!MaybeBitCode)
4437       return MaybeBitCode.takeError();
4438     switch (unsigned BitCode = MaybeBitCode.get()) {
4439     default: break;  // Default behavior, ignore unknown content.
4440     case bitc::MODULE_CODE_VERSION: {
4441       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4442       if (!VersionOrErr)
4443         return VersionOrErr.takeError();
4444       UseRelativeIDs = *VersionOrErr >= 1;
4445       break;
4446     }
4447     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
4448       if (ResolvedDataLayout)
4449         return error("target triple too late in module");
4450       std::string S;
4451       if (convertToString(Record, 0, S))
4452         return error("Invalid record");
4453       TheModule->setTargetTriple(S);
4454       break;
4455     }
4456     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
4457       if (ResolvedDataLayout)
4458         return error("datalayout too late in module");
4459       if (convertToString(Record, 0, TentativeDataLayoutStr))
4460         return error("Invalid record");
4461       break;
4462     }
4463     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
4464       std::string S;
4465       if (convertToString(Record, 0, S))
4466         return error("Invalid record");
4467       TheModule->setModuleInlineAsm(S);
4468       break;
4469     }
4470     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
4471       // Deprecated, but still needed to read old bitcode files.
4472       std::string S;
4473       if (convertToString(Record, 0, S))
4474         return error("Invalid record");
4475       // Ignore value.
4476       break;
4477     }
4478     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
4479       std::string S;
4480       if (convertToString(Record, 0, S))
4481         return error("Invalid record");
4482       SectionTable.push_back(S);
4483       break;
4484     }
4485     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
4486       std::string S;
4487       if (convertToString(Record, 0, S))
4488         return error("Invalid record");
4489       GCTable.push_back(S);
4490       break;
4491     }
4492     case bitc::MODULE_CODE_COMDAT:
4493       if (Error Err = parseComdatRecord(Record))
4494         return Err;
4495       break;
4496     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4497     // written by ThinLinkBitcodeWriter. See
4498     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4499     // record
4500     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4501     case bitc::MODULE_CODE_GLOBALVAR:
4502       if (Error Err = parseGlobalVarRecord(Record))
4503         return Err;
4504       break;
4505     case bitc::MODULE_CODE_FUNCTION:
4506       if (Error Err = ResolveDataLayout())
4507         return Err;
4508       if (Error Err = parseFunctionRecord(Record))
4509         return Err;
4510       break;
4511     case bitc::MODULE_CODE_IFUNC:
4512     case bitc::MODULE_CODE_ALIAS:
4513     case bitc::MODULE_CODE_ALIAS_OLD:
4514       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4515         return Err;
4516       break;
4517     /// MODULE_CODE_VSTOFFSET: [offset]
4518     case bitc::MODULE_CODE_VSTOFFSET:
4519       if (Record.empty())
4520         return error("Invalid record");
4521       // Note that we subtract 1 here because the offset is relative to one word
4522       // before the start of the identification or module block, which was
4523       // historically always the start of the regular bitcode header.
4524       VSTOffset = Record[0] - 1;
4525       break;
4526     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4527     case bitc::MODULE_CODE_SOURCE_FILENAME:
4528       SmallString<128> ValueName;
4529       if (convertToString(Record, 0, ValueName))
4530         return error("Invalid record");
4531       TheModule->setSourceFileName(ValueName);
4532       break;
4533     }
4534     Record.clear();
4535   }
4536   this->ValueTypeCallback = std::nullopt;
4537   return Error::success();
4538 }
4539 
4540 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4541                                       bool IsImporting,
4542                                       ParserCallbacks Callbacks) {
4543   TheModule = M;
4544   MetadataLoaderCallbacks MDCallbacks;
4545   MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4546   MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4547     return getContainedTypeID(I, J);
4548   };
4549   MDCallbacks.MDType = Callbacks.MDType;
4550   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4551   return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4552 }
4553 
4554 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4555   if (!isa<PointerType>(PtrType))
4556     return error("Load/Store operand is not a pointer type");
4557   if (!PointerType::isLoadableOrStorableType(ValType))
4558     return error("Cannot load/store from pointer");
4559   return Error::success();
4560 }
4561 
4562 Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4563                                              ArrayRef<unsigned> ArgTyIDs) {
4564   AttributeList Attrs = CB->getAttributes();
4565   for (unsigned i = 0; i != CB->arg_size(); ++i) {
4566     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4567                                      Attribute::InAlloca}) {
4568       if (!Attrs.hasParamAttr(i, Kind) ||
4569           Attrs.getParamAttr(i, Kind).getValueAsType())
4570         continue;
4571 
4572       Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4573       if (!PtrEltTy)
4574         return error("Missing element type for typed attribute upgrade");
4575 
4576       Attribute NewAttr;
4577       switch (Kind) {
4578       case Attribute::ByVal:
4579         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4580         break;
4581       case Attribute::StructRet:
4582         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4583         break;
4584       case Attribute::InAlloca:
4585         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4586         break;
4587       default:
4588         llvm_unreachable("not an upgraded type attribute");
4589       }
4590 
4591       Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4592     }
4593   }
4594 
4595   if (CB->isInlineAsm()) {
4596     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
4597     unsigned ArgNo = 0;
4598     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4599       if (!CI.hasArg())
4600         continue;
4601 
4602       if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4603         Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4604         if (!ElemTy)
4605           return error("Missing element type for inline asm upgrade");
4606         Attrs = Attrs.addParamAttribute(
4607             Context, ArgNo,
4608             Attribute::get(Context, Attribute::ElementType, ElemTy));
4609       }
4610 
4611       ArgNo++;
4612     }
4613   }
4614 
4615   switch (CB->getIntrinsicID()) {
4616   case Intrinsic::preserve_array_access_index:
4617   case Intrinsic::preserve_struct_access_index:
4618   case Intrinsic::aarch64_ldaxr:
4619   case Intrinsic::aarch64_ldxr:
4620   case Intrinsic::aarch64_stlxr:
4621   case Intrinsic::aarch64_stxr:
4622   case Intrinsic::arm_ldaex:
4623   case Intrinsic::arm_ldrex:
4624   case Intrinsic::arm_stlex:
4625   case Intrinsic::arm_strex: {
4626     unsigned ArgNo;
4627     switch (CB->getIntrinsicID()) {
4628     case Intrinsic::aarch64_stlxr:
4629     case Intrinsic::aarch64_stxr:
4630     case Intrinsic::arm_stlex:
4631     case Intrinsic::arm_strex:
4632       ArgNo = 1;
4633       break;
4634     default:
4635       ArgNo = 0;
4636       break;
4637     }
4638     if (!Attrs.getParamElementType(ArgNo)) {
4639       Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4640       if (!ElTy)
4641         return error("Missing element type for elementtype upgrade");
4642       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4643       Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4644     }
4645     break;
4646   }
4647   default:
4648     break;
4649   }
4650 
4651   CB->setAttributes(Attrs);
4652   return Error::success();
4653 }
4654 
4655 /// Lazily parse the specified function body block.
4656 Error BitcodeReader::parseFunctionBody(Function *F) {
4657   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4658     return Err;
4659 
4660   // Unexpected unresolved metadata when parsing function.
4661   if (MDLoader->hasFwdRefs())
4662     return error("Invalid function metadata: incoming forward references");
4663 
4664   InstructionList.clear();
4665   unsigned ModuleValueListSize = ValueList.size();
4666   unsigned ModuleMDLoaderSize = MDLoader->size();
4667 
4668   // Add all the function arguments to the value table.
4669   unsigned ArgNo = 0;
4670   unsigned FTyID = FunctionTypeIDs[F];
4671   for (Argument &I : F->args()) {
4672     unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4673     assert(I.getType() == getTypeByID(ArgTyID) &&
4674            "Incorrect fully specified type for Function Argument");
4675     ValueList.push_back(&I, ArgTyID);
4676     ++ArgNo;
4677   }
4678   unsigned NextValueNo = ValueList.size();
4679   BasicBlock *CurBB = nullptr;
4680   unsigned CurBBNo = 0;
4681   // Block into which constant expressions from phi nodes are materialized.
4682   BasicBlock *PhiConstExprBB = nullptr;
4683   // Edge blocks for phi nodes into which constant expressions have been
4684   // expanded.
4685   SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
4686     ConstExprEdgeBBs;
4687 
4688   DebugLoc LastLoc;
4689   auto getLastInstruction = [&]() -> Instruction * {
4690     if (CurBB && !CurBB->empty())
4691       return &CurBB->back();
4692     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4693              !FunctionBBs[CurBBNo - 1]->empty())
4694       return &FunctionBBs[CurBBNo - 1]->back();
4695     return nullptr;
4696   };
4697 
4698   std::vector<OperandBundleDef> OperandBundles;
4699 
4700   // Read all the records.
4701   SmallVector<uint64_t, 64> Record;
4702 
4703   while (true) {
4704     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4705     if (!MaybeEntry)
4706       return MaybeEntry.takeError();
4707     llvm::BitstreamEntry Entry = MaybeEntry.get();
4708 
4709     switch (Entry.Kind) {
4710     case BitstreamEntry::Error:
4711       return error("Malformed block");
4712     case BitstreamEntry::EndBlock:
4713       goto OutOfRecordLoop;
4714 
4715     case BitstreamEntry::SubBlock:
4716       switch (Entry.ID) {
4717       default:  // Skip unknown content.
4718         if (Error Err = Stream.SkipBlock())
4719           return Err;
4720         break;
4721       case bitc::CONSTANTS_BLOCK_ID:
4722         if (Error Err = parseConstants())
4723           return Err;
4724         NextValueNo = ValueList.size();
4725         break;
4726       case bitc::VALUE_SYMTAB_BLOCK_ID:
4727         if (Error Err = parseValueSymbolTable())
4728           return Err;
4729         break;
4730       case bitc::METADATA_ATTACHMENT_ID:
4731         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4732           return Err;
4733         break;
4734       case bitc::METADATA_BLOCK_ID:
4735         assert(DeferredMetadataInfo.empty() &&
4736                "Must read all module-level metadata before function-level");
4737         if (Error Err = MDLoader->parseFunctionMetadata())
4738           return Err;
4739         break;
4740       case bitc::USELIST_BLOCK_ID:
4741         if (Error Err = parseUseLists())
4742           return Err;
4743         break;
4744       }
4745       continue;
4746 
4747     case BitstreamEntry::Record:
4748       // The interesting case.
4749       break;
4750     }
4751 
4752     // Read a record.
4753     Record.clear();
4754     Instruction *I = nullptr;
4755     unsigned ResTypeID = InvalidTypeID;
4756     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4757     if (!MaybeBitCode)
4758       return MaybeBitCode.takeError();
4759     switch (unsigned BitCode = MaybeBitCode.get()) {
4760     default: // Default behavior: reject
4761       return error("Invalid value");
4762     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4763       if (Record.empty() || Record[0] == 0)
4764         return error("Invalid record");
4765       // Create all the basic blocks for the function.
4766       FunctionBBs.resize(Record[0]);
4767 
4768       // See if anything took the address of blocks in this function.
4769       auto BBFRI = BasicBlockFwdRefs.find(F);
4770       if (BBFRI == BasicBlockFwdRefs.end()) {
4771         for (BasicBlock *&BB : FunctionBBs)
4772           BB = BasicBlock::Create(Context, "", F);
4773       } else {
4774         auto &BBRefs = BBFRI->second;
4775         // Check for invalid basic block references.
4776         if (BBRefs.size() > FunctionBBs.size())
4777           return error("Invalid ID");
4778         assert(!BBRefs.empty() && "Unexpected empty array");
4779         assert(!BBRefs.front() && "Invalid reference to entry block");
4780         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4781              ++I)
4782           if (I < RE && BBRefs[I]) {
4783             BBRefs[I]->insertInto(F);
4784             FunctionBBs[I] = BBRefs[I];
4785           } else {
4786             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4787           }
4788 
4789         // Erase from the table.
4790         BasicBlockFwdRefs.erase(BBFRI);
4791       }
4792 
4793       CurBB = FunctionBBs[0];
4794       continue;
4795     }
4796 
4797     case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
4798       // The record should not be emitted if it's an empty list.
4799       if (Record.empty())
4800         return error("Invalid record");
4801       // When we have the RARE case of a BlockAddress Constant that is not
4802       // scoped to the Function it refers to, we need to conservatively
4803       // materialize the referred to Function, regardless of whether or not
4804       // that Function will ultimately be linked, otherwise users of
4805       // BitcodeReader might start splicing out Function bodies such that we
4806       // might no longer be able to materialize the BlockAddress since the
4807       // BasicBlock (and entire body of the Function) the BlockAddress refers
4808       // to may have been moved. In the case that the user of BitcodeReader
4809       // decides ultimately not to link the Function body, materializing here
4810       // could be considered wasteful, but it's better than a deserialization
4811       // failure as described. This keeps BitcodeReader unaware of complex
4812       // linkage policy decisions such as those use by LTO, leaving those
4813       // decisions "one layer up."
4814       for (uint64_t ValID : Record)
4815         if (auto *F = dyn_cast<Function>(ValueList[ValID]))
4816           BackwardRefFunctions.push_back(F);
4817         else
4818           return error("Invalid record");
4819 
4820       continue;
4821 
4822     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4823       // This record indicates that the last instruction is at the same
4824       // location as the previous instruction with a location.
4825       I = getLastInstruction();
4826 
4827       if (!I)
4828         return error("Invalid record");
4829       I->setDebugLoc(LastLoc);
4830       I = nullptr;
4831       continue;
4832 
4833     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4834       I = getLastInstruction();
4835       if (!I || Record.size() < 4)
4836         return error("Invalid record");
4837 
4838       unsigned Line = Record[0], Col = Record[1];
4839       unsigned ScopeID = Record[2], IAID = Record[3];
4840       bool isImplicitCode = Record.size() == 5 && Record[4];
4841 
4842       MDNode *Scope = nullptr, *IA = nullptr;
4843       if (ScopeID) {
4844         Scope = dyn_cast_or_null<MDNode>(
4845             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4846         if (!Scope)
4847           return error("Invalid record");
4848       }
4849       if (IAID) {
4850         IA = dyn_cast_or_null<MDNode>(
4851             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4852         if (!IA)
4853           return error("Invalid record");
4854       }
4855       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4856                                 isImplicitCode);
4857       I->setDebugLoc(LastLoc);
4858       I = nullptr;
4859       continue;
4860     }
4861     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4862       unsigned OpNum = 0;
4863       Value *LHS;
4864       unsigned TypeID;
4865       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
4866           OpNum+1 > Record.size())
4867         return error("Invalid record");
4868 
4869       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4870       if (Opc == -1)
4871         return error("Invalid record");
4872       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4873       ResTypeID = TypeID;
4874       InstructionList.push_back(I);
4875       if (OpNum < Record.size()) {
4876         if (isa<FPMathOperator>(I)) {
4877           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4878           if (FMF.any())
4879             I->setFastMathFlags(FMF);
4880         }
4881       }
4882       break;
4883     }
4884     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4885       unsigned OpNum = 0;
4886       Value *LHS, *RHS;
4887       unsigned TypeID;
4888       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
4889           popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
4890                    CurBB) ||
4891           OpNum+1 > Record.size())
4892         return error("Invalid record");
4893 
4894       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4895       if (Opc == -1)
4896         return error("Invalid record");
4897       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4898       ResTypeID = TypeID;
4899       InstructionList.push_back(I);
4900       if (OpNum < Record.size()) {
4901         if (Opc == Instruction::Add ||
4902             Opc == Instruction::Sub ||
4903             Opc == Instruction::Mul ||
4904             Opc == Instruction::Shl) {
4905           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4906             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4907           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4908             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4909         } else if (Opc == Instruction::SDiv ||
4910                    Opc == Instruction::UDiv ||
4911                    Opc == Instruction::LShr ||
4912                    Opc == Instruction::AShr) {
4913           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4914             cast<BinaryOperator>(I)->setIsExact(true);
4915         } else if (Opc == Instruction::Or) {
4916           if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
4917             cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
4918         } else if (isa<FPMathOperator>(I)) {
4919           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4920           if (FMF.any())
4921             I->setFastMathFlags(FMF);
4922         }
4923       }
4924       break;
4925     }
4926     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4927       unsigned OpNum = 0;
4928       Value *Op;
4929       unsigned OpTypeID;
4930       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
4931           OpNum + 1 > Record.size())
4932         return error("Invalid record");
4933 
4934       ResTypeID = Record[OpNum++];
4935       Type *ResTy = getTypeByID(ResTypeID);
4936       int Opc = getDecodedCastOpcode(Record[OpNum++]);
4937 
4938       if (Opc == -1 || !ResTy)
4939         return error("Invalid record");
4940       Instruction *Temp = nullptr;
4941       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4942         if (Temp) {
4943           InstructionList.push_back(Temp);
4944           assert(CurBB && "No current BB?");
4945           Temp->insertInto(CurBB, CurBB->end());
4946         }
4947       } else {
4948         auto CastOp = (Instruction::CastOps)Opc;
4949         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4950           return error("Invalid cast");
4951         I = CastInst::Create(CastOp, Op, ResTy);
4952       }
4953       if (OpNum < Record.size() && isa<PossiblyNonNegInst>(I) &&
4954           (Record[OpNum] & (1 << bitc::PNNI_NON_NEG)))
4955         I->setNonNeg(true);
4956       InstructionList.push_back(I);
4957       break;
4958     }
4959     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4960     case bitc::FUNC_CODE_INST_GEP_OLD:
4961     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4962       unsigned OpNum = 0;
4963 
4964       unsigned TyID;
4965       Type *Ty;
4966       bool InBounds;
4967 
4968       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4969         InBounds = Record[OpNum++];
4970         TyID = Record[OpNum++];
4971         Ty = getTypeByID(TyID);
4972       } else {
4973         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4974         TyID = InvalidTypeID;
4975         Ty = nullptr;
4976       }
4977 
4978       Value *BasePtr;
4979       unsigned BasePtrTypeID;
4980       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
4981                            CurBB))
4982         return error("Invalid record");
4983 
4984       if (!Ty) {
4985         TyID = getContainedTypeID(BasePtrTypeID);
4986         if (BasePtr->getType()->isVectorTy())
4987           TyID = getContainedTypeID(TyID);
4988         Ty = getTypeByID(TyID);
4989       }
4990 
4991       SmallVector<Value*, 16> GEPIdx;
4992       while (OpNum != Record.size()) {
4993         Value *Op;
4994         unsigned OpTypeID;
4995         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
4996           return error("Invalid record");
4997         GEPIdx.push_back(Op);
4998       }
4999 
5000       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
5001 
5002       ResTypeID = TyID;
5003       if (cast<GEPOperator>(I)->getNumIndices() != 0) {
5004         auto GTI = std::next(gep_type_begin(I));
5005         for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
5006           unsigned SubType = 0;
5007           if (GTI.isStruct()) {
5008             ConstantInt *IdxC =
5009                 Idx->getType()->isVectorTy()
5010                     ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
5011                     : cast<ConstantInt>(Idx);
5012             SubType = IdxC->getZExtValue();
5013           }
5014           ResTypeID = getContainedTypeID(ResTypeID, SubType);
5015           ++GTI;
5016         }
5017       }
5018 
5019       // At this point ResTypeID is the result element type. We need a pointer
5020       // or vector of pointer to it.
5021       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
5022       if (I->getType()->isVectorTy())
5023         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5024 
5025       InstructionList.push_back(I);
5026       if (InBounds)
5027         cast<GetElementPtrInst>(I)->setIsInBounds(true);
5028       break;
5029     }
5030 
5031     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
5032                                        // EXTRACTVAL: [opty, opval, n x indices]
5033       unsigned OpNum = 0;
5034       Value *Agg;
5035       unsigned AggTypeID;
5036       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5037         return error("Invalid record");
5038       Type *Ty = Agg->getType();
5039 
5040       unsigned RecSize = Record.size();
5041       if (OpNum == RecSize)
5042         return error("EXTRACTVAL: Invalid instruction with 0 indices");
5043 
5044       SmallVector<unsigned, 4> EXTRACTVALIdx;
5045       ResTypeID = AggTypeID;
5046       for (; OpNum != RecSize; ++OpNum) {
5047         bool IsArray = Ty->isArrayTy();
5048         bool IsStruct = Ty->isStructTy();
5049         uint64_t Index = Record[OpNum];
5050 
5051         if (!IsStruct && !IsArray)
5052           return error("EXTRACTVAL: Invalid type");
5053         if ((unsigned)Index != Index)
5054           return error("Invalid value");
5055         if (IsStruct && Index >= Ty->getStructNumElements())
5056           return error("EXTRACTVAL: Invalid struct index");
5057         if (IsArray && Index >= Ty->getArrayNumElements())
5058           return error("EXTRACTVAL: Invalid array index");
5059         EXTRACTVALIdx.push_back((unsigned)Index);
5060 
5061         if (IsStruct) {
5062           Ty = Ty->getStructElementType(Index);
5063           ResTypeID = getContainedTypeID(ResTypeID, Index);
5064         } else {
5065           Ty = Ty->getArrayElementType();
5066           ResTypeID = getContainedTypeID(ResTypeID);
5067         }
5068       }
5069 
5070       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
5071       InstructionList.push_back(I);
5072       break;
5073     }
5074 
5075     case bitc::FUNC_CODE_INST_INSERTVAL: {
5076                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
5077       unsigned OpNum = 0;
5078       Value *Agg;
5079       unsigned AggTypeID;
5080       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5081         return error("Invalid record");
5082       Value *Val;
5083       unsigned ValTypeID;
5084       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5085         return error("Invalid record");
5086 
5087       unsigned RecSize = Record.size();
5088       if (OpNum == RecSize)
5089         return error("INSERTVAL: Invalid instruction with 0 indices");
5090 
5091       SmallVector<unsigned, 4> INSERTVALIdx;
5092       Type *CurTy = Agg->getType();
5093       for (; OpNum != RecSize; ++OpNum) {
5094         bool IsArray = CurTy->isArrayTy();
5095         bool IsStruct = CurTy->isStructTy();
5096         uint64_t Index = Record[OpNum];
5097 
5098         if (!IsStruct && !IsArray)
5099           return error("INSERTVAL: Invalid type");
5100         if ((unsigned)Index != Index)
5101           return error("Invalid value");
5102         if (IsStruct && Index >= CurTy->getStructNumElements())
5103           return error("INSERTVAL: Invalid struct index");
5104         if (IsArray && Index >= CurTy->getArrayNumElements())
5105           return error("INSERTVAL: Invalid array index");
5106 
5107         INSERTVALIdx.push_back((unsigned)Index);
5108         if (IsStruct)
5109           CurTy = CurTy->getStructElementType(Index);
5110         else
5111           CurTy = CurTy->getArrayElementType();
5112       }
5113 
5114       if (CurTy != Val->getType())
5115         return error("Inserted value type doesn't match aggregate type");
5116 
5117       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
5118       ResTypeID = AggTypeID;
5119       InstructionList.push_back(I);
5120       break;
5121     }
5122 
5123     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5124       // obsolete form of select
5125       // handles select i1 ... in old bitcode
5126       unsigned OpNum = 0;
5127       Value *TrueVal, *FalseVal, *Cond;
5128       unsigned TypeID;
5129       Type *CondType = Type::getInt1Ty(Context);
5130       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
5131                            CurBB) ||
5132           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
5133                    FalseVal, CurBB) ||
5134           popValue(Record, OpNum, NextValueNo, CondType,
5135                    getVirtualTypeID(CondType), Cond, CurBB))
5136         return error("Invalid record");
5137 
5138       I = SelectInst::Create(Cond, TrueVal, FalseVal);
5139       ResTypeID = TypeID;
5140       InstructionList.push_back(I);
5141       break;
5142     }
5143 
5144     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
5145       // new form of select
5146       // handles select i1 or select [N x i1]
5147       unsigned OpNum = 0;
5148       Value *TrueVal, *FalseVal, *Cond;
5149       unsigned ValTypeID, CondTypeID;
5150       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5151                            CurBB) ||
5152           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
5153                    FalseVal, CurBB) ||
5154           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
5155         return error("Invalid record");
5156 
5157       // select condition can be either i1 or [N x i1]
5158       if (VectorType* vector_type =
5159           dyn_cast<VectorType>(Cond->getType())) {
5160         // expect <n x i1>
5161         if (vector_type->getElementType() != Type::getInt1Ty(Context))
5162           return error("Invalid type for value");
5163       } else {
5164         // expect i1
5165         if (Cond->getType() != Type::getInt1Ty(Context))
5166           return error("Invalid type for value");
5167       }
5168 
5169       I = SelectInst::Create(Cond, TrueVal, FalseVal);
5170       ResTypeID = ValTypeID;
5171       InstructionList.push_back(I);
5172       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
5173         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5174         if (FMF.any())
5175           I->setFastMathFlags(FMF);
5176       }
5177       break;
5178     }
5179 
5180     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5181       unsigned OpNum = 0;
5182       Value *Vec, *Idx;
5183       unsigned VecTypeID, IdxTypeID;
5184       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5185           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5186         return error("Invalid record");
5187       if (!Vec->getType()->isVectorTy())
5188         return error("Invalid type for value");
5189       I = ExtractElementInst::Create(Vec, Idx);
5190       ResTypeID = getContainedTypeID(VecTypeID);
5191       InstructionList.push_back(I);
5192       break;
5193     }
5194 
5195     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5196       unsigned OpNum = 0;
5197       Value *Vec, *Elt, *Idx;
5198       unsigned VecTypeID, IdxTypeID;
5199       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5200         return error("Invalid record");
5201       if (!Vec->getType()->isVectorTy())
5202         return error("Invalid type for value");
5203       if (popValue(Record, OpNum, NextValueNo,
5204                    cast<VectorType>(Vec->getType())->getElementType(),
5205                    getContainedTypeID(VecTypeID), Elt, CurBB) ||
5206           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5207         return error("Invalid record");
5208       I = InsertElementInst::Create(Vec, Elt, Idx);
5209       ResTypeID = VecTypeID;
5210       InstructionList.push_back(I);
5211       break;
5212     }
5213 
5214     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5215       unsigned OpNum = 0;
5216       Value *Vec1, *Vec2, *Mask;
5217       unsigned Vec1TypeID;
5218       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5219                            CurBB) ||
5220           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5221                    Vec2, CurBB))
5222         return error("Invalid record");
5223 
5224       unsigned MaskTypeID;
5225       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5226         return error("Invalid record");
5227       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5228         return error("Invalid type for value");
5229 
5230       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5231       ResTypeID =
5232           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5233       InstructionList.push_back(I);
5234       break;
5235     }
5236 
5237     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
5238       // Old form of ICmp/FCmp returning bool
5239       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5240       // both legal on vectors but had different behaviour.
5241     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5242       // FCmp/ICmp returning bool or vector of bool
5243 
5244       unsigned OpNum = 0;
5245       Value *LHS, *RHS;
5246       unsigned LHSTypeID;
5247       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5248           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5249                    CurBB))
5250         return error("Invalid record");
5251 
5252       if (OpNum >= Record.size())
5253         return error(
5254             "Invalid record: operand number exceeded available operands");
5255 
5256       CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
5257       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5258       FastMathFlags FMF;
5259       if (IsFP && Record.size() > OpNum+1)
5260         FMF = getDecodedFastMathFlags(Record[++OpNum]);
5261 
5262       if (OpNum+1 != Record.size())
5263         return error("Invalid record");
5264 
5265       if (IsFP) {
5266         if (!CmpInst::isFPPredicate(PredVal))
5267           return error("Invalid fcmp predicate");
5268         I = new FCmpInst(PredVal, LHS, RHS);
5269       } else {
5270         if (!CmpInst::isIntPredicate(PredVal))
5271           return error("Invalid icmp predicate");
5272         I = new ICmpInst(PredVal, LHS, RHS);
5273       }
5274 
5275       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5276       if (LHS->getType()->isVectorTy())
5277         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5278 
5279       if (FMF.any())
5280         I->setFastMathFlags(FMF);
5281       InstructionList.push_back(I);
5282       break;
5283     }
5284 
5285     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5286       {
5287         unsigned Size = Record.size();
5288         if (Size == 0) {
5289           I = ReturnInst::Create(Context);
5290           InstructionList.push_back(I);
5291           break;
5292         }
5293 
5294         unsigned OpNum = 0;
5295         Value *Op = nullptr;
5296         unsigned OpTypeID;
5297         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5298           return error("Invalid record");
5299         if (OpNum != Record.size())
5300           return error("Invalid record");
5301 
5302         I = ReturnInst::Create(Context, Op);
5303         InstructionList.push_back(I);
5304         break;
5305       }
5306     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5307       if (Record.size() != 1 && Record.size() != 3)
5308         return error("Invalid record");
5309       BasicBlock *TrueDest = getBasicBlock(Record[0]);
5310       if (!TrueDest)
5311         return error("Invalid record");
5312 
5313       if (Record.size() == 1) {
5314         I = BranchInst::Create(TrueDest);
5315         InstructionList.push_back(I);
5316       }
5317       else {
5318         BasicBlock *FalseDest = getBasicBlock(Record[1]);
5319         Type *CondType = Type::getInt1Ty(Context);
5320         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
5321                                getVirtualTypeID(CondType), CurBB);
5322         if (!FalseDest || !Cond)
5323           return error("Invalid record");
5324         I = BranchInst::Create(TrueDest, FalseDest, Cond);
5325         InstructionList.push_back(I);
5326       }
5327       break;
5328     }
5329     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5330       if (Record.size() != 1 && Record.size() != 2)
5331         return error("Invalid record");
5332       unsigned Idx = 0;
5333       Type *TokenTy = Type::getTokenTy(Context);
5334       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5335                                    getVirtualTypeID(TokenTy), CurBB);
5336       if (!CleanupPad)
5337         return error("Invalid record");
5338       BasicBlock *UnwindDest = nullptr;
5339       if (Record.size() == 2) {
5340         UnwindDest = getBasicBlock(Record[Idx++]);
5341         if (!UnwindDest)
5342           return error("Invalid record");
5343       }
5344 
5345       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5346       InstructionList.push_back(I);
5347       break;
5348     }
5349     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5350       if (Record.size() != 2)
5351         return error("Invalid record");
5352       unsigned Idx = 0;
5353       Type *TokenTy = Type::getTokenTy(Context);
5354       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5355                                  getVirtualTypeID(TokenTy), CurBB);
5356       if (!CatchPad)
5357         return error("Invalid record");
5358       BasicBlock *BB = getBasicBlock(Record[Idx++]);
5359       if (!BB)
5360         return error("Invalid record");
5361 
5362       I = CatchReturnInst::Create(CatchPad, BB);
5363       InstructionList.push_back(I);
5364       break;
5365     }
5366     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5367       // We must have, at minimum, the outer scope and the number of arguments.
5368       if (Record.size() < 2)
5369         return error("Invalid record");
5370 
5371       unsigned Idx = 0;
5372 
5373       Type *TokenTy = Type::getTokenTy(Context);
5374       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5375                                   getVirtualTypeID(TokenTy), CurBB);
5376       if (!ParentPad)
5377         return error("Invalid record");
5378 
5379       unsigned NumHandlers = Record[Idx++];
5380 
5381       SmallVector<BasicBlock *, 2> Handlers;
5382       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5383         BasicBlock *BB = getBasicBlock(Record[Idx++]);
5384         if (!BB)
5385           return error("Invalid record");
5386         Handlers.push_back(BB);
5387       }
5388 
5389       BasicBlock *UnwindDest = nullptr;
5390       if (Idx + 1 == Record.size()) {
5391         UnwindDest = getBasicBlock(Record[Idx++]);
5392         if (!UnwindDest)
5393           return error("Invalid record");
5394       }
5395 
5396       if (Record.size() != Idx)
5397         return error("Invalid record");
5398 
5399       auto *CatchSwitch =
5400           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5401       for (BasicBlock *Handler : Handlers)
5402         CatchSwitch->addHandler(Handler);
5403       I = CatchSwitch;
5404       ResTypeID = getVirtualTypeID(I->getType());
5405       InstructionList.push_back(I);
5406       break;
5407     }
5408     case bitc::FUNC_CODE_INST_CATCHPAD:
5409     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5410       // We must have, at minimum, the outer scope and the number of arguments.
5411       if (Record.size() < 2)
5412         return error("Invalid record");
5413 
5414       unsigned Idx = 0;
5415 
5416       Type *TokenTy = Type::getTokenTy(Context);
5417       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5418                                   getVirtualTypeID(TokenTy), CurBB);
5419       if (!ParentPad)
5420         return error("Invald record");
5421 
5422       unsigned NumArgOperands = Record[Idx++];
5423 
5424       SmallVector<Value *, 2> Args;
5425       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5426         Value *Val;
5427         unsigned ValTypeID;
5428         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5429           return error("Invalid record");
5430         Args.push_back(Val);
5431       }
5432 
5433       if (Record.size() != Idx)
5434         return error("Invalid record");
5435 
5436       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5437         I = CleanupPadInst::Create(ParentPad, Args);
5438       else
5439         I = CatchPadInst::Create(ParentPad, Args);
5440       ResTypeID = getVirtualTypeID(I->getType());
5441       InstructionList.push_back(I);
5442       break;
5443     }
5444     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5445       // Check magic
5446       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5447         // "New" SwitchInst format with case ranges. The changes to write this
5448         // format were reverted but we still recognize bitcode that uses it.
5449         // Hopefully someday we will have support for case ranges and can use
5450         // this format again.
5451 
5452         unsigned OpTyID = Record[1];
5453         Type *OpTy = getTypeByID(OpTyID);
5454         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5455 
5456         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5457         BasicBlock *Default = getBasicBlock(Record[3]);
5458         if (!OpTy || !Cond || !Default)
5459           return error("Invalid record");
5460 
5461         unsigned NumCases = Record[4];
5462 
5463         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5464         InstructionList.push_back(SI);
5465 
5466         unsigned CurIdx = 5;
5467         for (unsigned i = 0; i != NumCases; ++i) {
5468           SmallVector<ConstantInt*, 1> CaseVals;
5469           unsigned NumItems = Record[CurIdx++];
5470           for (unsigned ci = 0; ci != NumItems; ++ci) {
5471             bool isSingleNumber = Record[CurIdx++];
5472 
5473             APInt Low;
5474             unsigned ActiveWords = 1;
5475             if (ValueBitWidth > 64)
5476               ActiveWords = Record[CurIdx++];
5477             Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5478                                 ValueBitWidth);
5479             CurIdx += ActiveWords;
5480 
5481             if (!isSingleNumber) {
5482               ActiveWords = 1;
5483               if (ValueBitWidth > 64)
5484                 ActiveWords = Record[CurIdx++];
5485               APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5486                                          ValueBitWidth);
5487               CurIdx += ActiveWords;
5488 
5489               // FIXME: It is not clear whether values in the range should be
5490               // compared as signed or unsigned values. The partially
5491               // implemented changes that used this format in the past used
5492               // unsigned comparisons.
5493               for ( ; Low.ule(High); ++Low)
5494                 CaseVals.push_back(ConstantInt::get(Context, Low));
5495             } else
5496               CaseVals.push_back(ConstantInt::get(Context, Low));
5497           }
5498           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5499           for (ConstantInt *Cst : CaseVals)
5500             SI->addCase(Cst, DestBB);
5501         }
5502         I = SI;
5503         break;
5504       }
5505 
5506       // Old SwitchInst format without case ranges.
5507 
5508       if (Record.size() < 3 || (Record.size() & 1) == 0)
5509         return error("Invalid record");
5510       unsigned OpTyID = Record[0];
5511       Type *OpTy = getTypeByID(OpTyID);
5512       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5513       BasicBlock *Default = getBasicBlock(Record[2]);
5514       if (!OpTy || !Cond || !Default)
5515         return error("Invalid record");
5516       unsigned NumCases = (Record.size()-3)/2;
5517       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5518       InstructionList.push_back(SI);
5519       for (unsigned i = 0, e = NumCases; i != e; ++i) {
5520         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5521             getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
5522         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5523         if (!CaseVal || !DestBB) {
5524           delete SI;
5525           return error("Invalid record");
5526         }
5527         SI->addCase(CaseVal, DestBB);
5528       }
5529       I = SI;
5530       break;
5531     }
5532     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5533       if (Record.size() < 2)
5534         return error("Invalid record");
5535       unsigned OpTyID = Record[0];
5536       Type *OpTy = getTypeByID(OpTyID);
5537       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5538       if (!OpTy || !Address)
5539         return error("Invalid record");
5540       unsigned NumDests = Record.size()-2;
5541       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5542       InstructionList.push_back(IBI);
5543       for (unsigned i = 0, e = NumDests; i != e; ++i) {
5544         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5545           IBI->addDestination(DestBB);
5546         } else {
5547           delete IBI;
5548           return error("Invalid record");
5549         }
5550       }
5551       I = IBI;
5552       break;
5553     }
5554 
5555     case bitc::FUNC_CODE_INST_INVOKE: {
5556       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5557       if (Record.size() < 4)
5558         return error("Invalid record");
5559       unsigned OpNum = 0;
5560       AttributeList PAL = getAttributes(Record[OpNum++]);
5561       unsigned CCInfo = Record[OpNum++];
5562       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5563       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5564 
5565       unsigned FTyID = InvalidTypeID;
5566       FunctionType *FTy = nullptr;
5567       if ((CCInfo >> 13) & 1) {
5568         FTyID = Record[OpNum++];
5569         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5570         if (!FTy)
5571           return error("Explicit invoke type is not a function type");
5572       }
5573 
5574       Value *Callee;
5575       unsigned CalleeTypeID;
5576       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5577                            CurBB))
5578         return error("Invalid record");
5579 
5580       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5581       if (!CalleeTy)
5582         return error("Callee is not a pointer");
5583       if (!FTy) {
5584         FTyID = getContainedTypeID(CalleeTypeID);
5585         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5586         if (!FTy)
5587           return error("Callee is not of pointer to function type");
5588       }
5589       if (Record.size() < FTy->getNumParams() + OpNum)
5590         return error("Insufficient operands to call");
5591 
5592       SmallVector<Value*, 16> Ops;
5593       SmallVector<unsigned, 16> ArgTyIDs;
5594       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5595         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5596         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5597                                ArgTyID, CurBB));
5598         ArgTyIDs.push_back(ArgTyID);
5599         if (!Ops.back())
5600           return error("Invalid record");
5601       }
5602 
5603       if (!FTy->isVarArg()) {
5604         if (Record.size() != OpNum)
5605           return error("Invalid record");
5606       } else {
5607         // Read type/value pairs for varargs params.
5608         while (OpNum != Record.size()) {
5609           Value *Op;
5610           unsigned OpTypeID;
5611           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5612             return error("Invalid record");
5613           Ops.push_back(Op);
5614           ArgTyIDs.push_back(OpTypeID);
5615         }
5616       }
5617 
5618       // Upgrade the bundles if needed.
5619       if (!OperandBundles.empty())
5620         UpgradeOperandBundles(OperandBundles);
5621 
5622       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5623                              OperandBundles);
5624       ResTypeID = getContainedTypeID(FTyID);
5625       OperandBundles.clear();
5626       InstructionList.push_back(I);
5627       cast<InvokeInst>(I)->setCallingConv(
5628           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5629       cast<InvokeInst>(I)->setAttributes(PAL);
5630       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5631         I->deleteValue();
5632         return Err;
5633       }
5634 
5635       break;
5636     }
5637     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5638       unsigned Idx = 0;
5639       Value *Val = nullptr;
5640       unsigned ValTypeID;
5641       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5642         return error("Invalid record");
5643       I = ResumeInst::Create(Val);
5644       InstructionList.push_back(I);
5645       break;
5646     }
5647     case bitc::FUNC_CODE_INST_CALLBR: {
5648       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5649       unsigned OpNum = 0;
5650       AttributeList PAL = getAttributes(Record[OpNum++]);
5651       unsigned CCInfo = Record[OpNum++];
5652 
5653       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5654       unsigned NumIndirectDests = Record[OpNum++];
5655       SmallVector<BasicBlock *, 16> IndirectDests;
5656       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
5657         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
5658 
5659       unsigned FTyID = InvalidTypeID;
5660       FunctionType *FTy = nullptr;
5661       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5662         FTyID = Record[OpNum++];
5663         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5664         if (!FTy)
5665           return error("Explicit call type is not a function type");
5666       }
5667 
5668       Value *Callee;
5669       unsigned CalleeTypeID;
5670       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5671                            CurBB))
5672         return error("Invalid record");
5673 
5674       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5675       if (!OpTy)
5676         return error("Callee is not a pointer type");
5677       if (!FTy) {
5678         FTyID = getContainedTypeID(CalleeTypeID);
5679         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5680         if (!FTy)
5681           return error("Callee is not of pointer to function type");
5682       }
5683       if (Record.size() < FTy->getNumParams() + OpNum)
5684         return error("Insufficient operands to call");
5685 
5686       SmallVector<Value*, 16> Args;
5687       SmallVector<unsigned, 16> ArgTyIDs;
5688       // Read the fixed params.
5689       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5690         Value *Arg;
5691         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5692         if (FTy->getParamType(i)->isLabelTy())
5693           Arg = getBasicBlock(Record[OpNum]);
5694         else
5695           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5696                          ArgTyID, CurBB);
5697         if (!Arg)
5698           return error("Invalid record");
5699         Args.push_back(Arg);
5700         ArgTyIDs.push_back(ArgTyID);
5701       }
5702 
5703       // Read type/value pairs for varargs params.
5704       if (!FTy->isVarArg()) {
5705         if (OpNum != Record.size())
5706           return error("Invalid record");
5707       } else {
5708         while (OpNum != Record.size()) {
5709           Value *Op;
5710           unsigned OpTypeID;
5711           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5712             return error("Invalid record");
5713           Args.push_back(Op);
5714           ArgTyIDs.push_back(OpTypeID);
5715         }
5716       }
5717 
5718       // Upgrade the bundles if needed.
5719       if (!OperandBundles.empty())
5720         UpgradeOperandBundles(OperandBundles);
5721 
5722       if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
5723         InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
5724         auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
5725           return CI.Type == InlineAsm::isLabel;
5726         };
5727         if (none_of(ConstraintInfo, IsLabelConstraint)) {
5728           // Upgrade explicit blockaddress arguments to label constraints.
5729           // Verify that the last arguments are blockaddress arguments that
5730           // match the indirect destinations. Clang always generates callbr
5731           // in this form. We could support reordering with more effort.
5732           unsigned FirstBlockArg = Args.size() - IndirectDests.size();
5733           for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
5734             unsigned LabelNo = ArgNo - FirstBlockArg;
5735             auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
5736             if (!BA || BA->getFunction() != F ||
5737                 LabelNo > IndirectDests.size() ||
5738                 BA->getBasicBlock() != IndirectDests[LabelNo])
5739               return error("callbr argument does not match indirect dest");
5740           }
5741 
5742           // Remove blockaddress arguments.
5743           Args.erase(Args.begin() + FirstBlockArg, Args.end());
5744           ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
5745 
5746           // Recreate the function type with less arguments.
5747           SmallVector<Type *> ArgTys;
5748           for (Value *Arg : Args)
5749             ArgTys.push_back(Arg->getType());
5750           FTy =
5751               FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
5752 
5753           // Update constraint string to use label constraints.
5754           std::string Constraints = IA->getConstraintString();
5755           unsigned ArgNo = 0;
5756           size_t Pos = 0;
5757           for (const auto &CI : ConstraintInfo) {
5758             if (CI.hasArg()) {
5759               if (ArgNo >= FirstBlockArg)
5760                 Constraints.insert(Pos, "!");
5761               ++ArgNo;
5762             }
5763 
5764             // Go to next constraint in string.
5765             Pos = Constraints.find(',', Pos);
5766             if (Pos == std::string::npos)
5767               break;
5768             ++Pos;
5769           }
5770 
5771           Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
5772                                   IA->hasSideEffects(), IA->isAlignStack(),
5773                                   IA->getDialect(), IA->canThrow());
5774         }
5775       }
5776 
5777       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
5778                              OperandBundles);
5779       ResTypeID = getContainedTypeID(FTyID);
5780       OperandBundles.clear();
5781       InstructionList.push_back(I);
5782       cast<CallBrInst>(I)->setCallingConv(
5783           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5784       cast<CallBrInst>(I)->setAttributes(PAL);
5785       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5786         I->deleteValue();
5787         return Err;
5788       }
5789       break;
5790     }
5791     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5792       I = new UnreachableInst(Context);
5793       InstructionList.push_back(I);
5794       break;
5795     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5796       if (Record.empty())
5797         return error("Invalid phi record");
5798       // The first record specifies the type.
5799       unsigned TyID = Record[0];
5800       Type *Ty = getTypeByID(TyID);
5801       if (!Ty)
5802         return error("Invalid phi record");
5803 
5804       // Phi arguments are pairs of records of [value, basic block].
5805       // There is an optional final record for fast-math-flags if this phi has a
5806       // floating-point type.
5807       size_t NumArgs = (Record.size() - 1) / 2;
5808       PHINode *PN = PHINode::Create(Ty, NumArgs);
5809       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
5810         PN->deleteValue();
5811         return error("Invalid phi record");
5812       }
5813       InstructionList.push_back(PN);
5814 
5815       SmallDenseMap<BasicBlock *, Value *> Args;
5816       for (unsigned i = 0; i != NumArgs; i++) {
5817         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
5818         if (!BB) {
5819           PN->deleteValue();
5820           return error("Invalid phi BB");
5821         }
5822 
5823         // Phi nodes may contain the same predecessor multiple times, in which
5824         // case the incoming value must be identical. Directly reuse the already
5825         // seen value here, to avoid expanding a constant expression multiple
5826         // times.
5827         auto It = Args.find(BB);
5828         if (It != Args.end()) {
5829           PN->addIncoming(It->second, BB);
5830           continue;
5831         }
5832 
5833         // If there already is a block for this edge (from a different phi),
5834         // use it.
5835         BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
5836         if (!EdgeBB) {
5837           // Otherwise, use a temporary block (that we will discard if it
5838           // turns out to be unnecessary).
5839           if (!PhiConstExprBB)
5840             PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
5841           EdgeBB = PhiConstExprBB;
5842         }
5843 
5844         // With the new function encoding, it is possible that operands have
5845         // negative IDs (for forward references).  Use a signed VBR
5846         // representation to keep the encoding small.
5847         Value *V;
5848         if (UseRelativeIDs)
5849           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
5850         else
5851           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
5852         if (!V) {
5853           PN->deleteValue();
5854           PhiConstExprBB->eraseFromParent();
5855           return error("Invalid phi record");
5856         }
5857 
5858         if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
5859           ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
5860           PhiConstExprBB = nullptr;
5861         }
5862         PN->addIncoming(V, BB);
5863         Args.insert({BB, V});
5864       }
5865       I = PN;
5866       ResTypeID = TyID;
5867 
5868       // If there are an even number of records, the final record must be FMF.
5869       if (Record.size() % 2 == 0) {
5870         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
5871         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
5872         if (FMF.any())
5873           I->setFastMathFlags(FMF);
5874       }
5875 
5876       break;
5877     }
5878 
5879     case bitc::FUNC_CODE_INST_LANDINGPAD:
5880     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
5881       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5882       unsigned Idx = 0;
5883       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5884         if (Record.size() < 3)
5885           return error("Invalid record");
5886       } else {
5887         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5888         if (Record.size() < 4)
5889           return error("Invalid record");
5890       }
5891       ResTypeID = Record[Idx++];
5892       Type *Ty = getTypeByID(ResTypeID);
5893       if (!Ty)
5894         return error("Invalid record");
5895       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5896         Value *PersFn = nullptr;
5897         unsigned PersFnTypeID;
5898         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
5899                              nullptr))
5900           return error("Invalid record");
5901 
5902         if (!F->hasPersonalityFn())
5903           F->setPersonalityFn(cast<Constant>(PersFn));
5904         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5905           return error("Personality function mismatch");
5906       }
5907 
5908       bool IsCleanup = !!Record[Idx++];
5909       unsigned NumClauses = Record[Idx++];
5910       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5911       LP->setCleanup(IsCleanup);
5912       for (unsigned J = 0; J != NumClauses; ++J) {
5913         LandingPadInst::ClauseType CT =
5914           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5915         Value *Val;
5916         unsigned ValTypeID;
5917 
5918         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
5919                              nullptr)) {
5920           delete LP;
5921           return error("Invalid record");
5922         }
5923 
5924         assert((CT != LandingPadInst::Catch ||
5925                 !isa<ArrayType>(Val->getType())) &&
5926                "Catch clause has a invalid type!");
5927         assert((CT != LandingPadInst::Filter ||
5928                 isa<ArrayType>(Val->getType())) &&
5929                "Filter clause has invalid type!");
5930         LP->addClause(cast<Constant>(Val));
5931       }
5932 
5933       I = LP;
5934       InstructionList.push_back(I);
5935       break;
5936     }
5937 
5938     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5939       if (Record.size() != 4 && Record.size() != 5)
5940         return error("Invalid record");
5941       using APV = AllocaPackedValues;
5942       const uint64_t Rec = Record[3];
5943       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
5944       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
5945       unsigned TyID = Record[0];
5946       Type *Ty = getTypeByID(TyID);
5947       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
5948         TyID = getContainedTypeID(TyID);
5949         Ty = getTypeByID(TyID);
5950         if (!Ty)
5951           return error("Missing element type for old-style alloca");
5952       }
5953       unsigned OpTyID = Record[1];
5954       Type *OpTy = getTypeByID(OpTyID);
5955       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
5956       MaybeAlign Align;
5957       uint64_t AlignExp =
5958           Bitfield::get<APV::AlignLower>(Rec) |
5959           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5960       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
5961         return Err;
5962       }
5963       if (!Ty || !Size)
5964         return error("Invalid record");
5965 
5966       const DataLayout &DL = TheModule->getDataLayout();
5967       unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
5968 
5969       SmallPtrSet<Type *, 4> Visited;
5970       if (!Align && !Ty->isSized(&Visited))
5971         return error("alloca of unsized type");
5972       if (!Align)
5973         Align = DL.getPrefTypeAlign(Ty);
5974 
5975       if (!Size->getType()->isIntegerTy())
5976         return error("alloca element count must have integer type");
5977 
5978       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
5979       AI->setUsedWithInAlloca(InAlloca);
5980       AI->setSwiftError(SwiftError);
5981       I = AI;
5982       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
5983       InstructionList.push_back(I);
5984       break;
5985     }
5986     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5987       unsigned OpNum = 0;
5988       Value *Op;
5989       unsigned OpTypeID;
5990       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5991           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5992         return error("Invalid record");
5993 
5994       if (!isa<PointerType>(Op->getType()))
5995         return error("Load operand is not a pointer type");
5996 
5997       Type *Ty = nullptr;
5998       if (OpNum + 3 == Record.size()) {
5999         ResTypeID = Record[OpNum++];
6000         Ty = getTypeByID(ResTypeID);
6001       } else {
6002         ResTypeID = getContainedTypeID(OpTypeID);
6003         Ty = getTypeByID(ResTypeID);
6004       }
6005 
6006       if (!Ty)
6007         return error("Missing load type");
6008 
6009       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6010         return Err;
6011 
6012       MaybeAlign Align;
6013       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6014         return Err;
6015       SmallPtrSet<Type *, 4> Visited;
6016       if (!Align && !Ty->isSized(&Visited))
6017         return error("load of unsized type");
6018       if (!Align)
6019         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6020       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
6021       InstructionList.push_back(I);
6022       break;
6023     }
6024     case bitc::FUNC_CODE_INST_LOADATOMIC: {
6025        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6026       unsigned OpNum = 0;
6027       Value *Op;
6028       unsigned OpTypeID;
6029       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6030           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6031         return error("Invalid record");
6032 
6033       if (!isa<PointerType>(Op->getType()))
6034         return error("Load operand is not a pointer type");
6035 
6036       Type *Ty = nullptr;
6037       if (OpNum + 5 == Record.size()) {
6038         ResTypeID = Record[OpNum++];
6039         Ty = getTypeByID(ResTypeID);
6040       } else {
6041         ResTypeID = getContainedTypeID(OpTypeID);
6042         Ty = getTypeByID(ResTypeID);
6043       }
6044 
6045       if (!Ty)
6046         return error("Missing atomic load type");
6047 
6048       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6049         return Err;
6050 
6051       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6052       if (Ordering == AtomicOrdering::NotAtomic ||
6053           Ordering == AtomicOrdering::Release ||
6054           Ordering == AtomicOrdering::AcquireRelease)
6055         return error("Invalid record");
6056       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6057         return error("Invalid record");
6058       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6059 
6060       MaybeAlign Align;
6061       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6062         return Err;
6063       if (!Align)
6064         return error("Alignment missing from atomic load");
6065       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
6066       InstructionList.push_back(I);
6067       break;
6068     }
6069     case bitc::FUNC_CODE_INST_STORE:
6070     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6071       unsigned OpNum = 0;
6072       Value *Val, *Ptr;
6073       unsigned PtrTypeID, ValTypeID;
6074       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6075         return error("Invalid record");
6076 
6077       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6078         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6079           return error("Invalid record");
6080       } else {
6081         ValTypeID = getContainedTypeID(PtrTypeID);
6082         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6083                      ValTypeID, Val, CurBB))
6084           return error("Invalid record");
6085       }
6086 
6087       if (OpNum + 2 != Record.size())
6088         return error("Invalid record");
6089 
6090       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6091         return Err;
6092       MaybeAlign Align;
6093       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6094         return Err;
6095       SmallPtrSet<Type *, 4> Visited;
6096       if (!Align && !Val->getType()->isSized(&Visited))
6097         return error("store of unsized type");
6098       if (!Align)
6099         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
6100       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6101       InstructionList.push_back(I);
6102       break;
6103     }
6104     case bitc::FUNC_CODE_INST_STOREATOMIC:
6105     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
6106       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6107       unsigned OpNum = 0;
6108       Value *Val, *Ptr;
6109       unsigned PtrTypeID, ValTypeID;
6110       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6111           !isa<PointerType>(Ptr->getType()))
6112         return error("Invalid record");
6113       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
6114         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6115           return error("Invalid record");
6116       } else {
6117         ValTypeID = getContainedTypeID(PtrTypeID);
6118         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6119                      ValTypeID, Val, CurBB))
6120           return error("Invalid record");
6121       }
6122 
6123       if (OpNum + 4 != Record.size())
6124         return error("Invalid record");
6125 
6126       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6127         return Err;
6128       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6129       if (Ordering == AtomicOrdering::NotAtomic ||
6130           Ordering == AtomicOrdering::Acquire ||
6131           Ordering == AtomicOrdering::AcquireRelease)
6132         return error("Invalid record");
6133       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6134       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6135         return error("Invalid record");
6136 
6137       MaybeAlign Align;
6138       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6139         return Err;
6140       if (!Align)
6141         return error("Alignment missing from atomic store");
6142       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6143       InstructionList.push_back(I);
6144       break;
6145     }
6146     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6147       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6148       // failure_ordering?, weak?]
6149       const size_t NumRecords = Record.size();
6150       unsigned OpNum = 0;
6151       Value *Ptr = nullptr;
6152       unsigned PtrTypeID;
6153       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6154         return error("Invalid record");
6155 
6156       if (!isa<PointerType>(Ptr->getType()))
6157         return error("Cmpxchg operand is not a pointer type");
6158 
6159       Value *Cmp = nullptr;
6160       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6161       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6162                    CmpTypeID, Cmp, CurBB))
6163         return error("Invalid record");
6164 
6165       Value *New = nullptr;
6166       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
6167                    New, CurBB) ||
6168           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6169         return error("Invalid record");
6170 
6171       const AtomicOrdering SuccessOrdering =
6172           getDecodedOrdering(Record[OpNum + 1]);
6173       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6174           SuccessOrdering == AtomicOrdering::Unordered)
6175         return error("Invalid record");
6176 
6177       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6178 
6179       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6180         return Err;
6181 
6182       const AtomicOrdering FailureOrdering =
6183           NumRecords < 7
6184               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6185               : getDecodedOrdering(Record[OpNum + 3]);
6186 
6187       if (FailureOrdering == AtomicOrdering::NotAtomic ||
6188           FailureOrdering == AtomicOrdering::Unordered)
6189         return error("Invalid record");
6190 
6191       const Align Alignment(
6192           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6193 
6194       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6195                                 FailureOrdering, SSID);
6196       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
6197 
6198       if (NumRecords < 8) {
6199         // Before weak cmpxchgs existed, the instruction simply returned the
6200         // value loaded from memory, so bitcode files from that era will be
6201         // expecting the first component of a modern cmpxchg.
6202         I->insertInto(CurBB, CurBB->end());
6203         I = ExtractValueInst::Create(I, 0);
6204         ResTypeID = CmpTypeID;
6205       } else {
6206         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
6207         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6208         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6209       }
6210 
6211       InstructionList.push_back(I);
6212       break;
6213     }
6214     case bitc::FUNC_CODE_INST_CMPXCHG: {
6215       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6216       // failure_ordering, weak, align?]
6217       const size_t NumRecords = Record.size();
6218       unsigned OpNum = 0;
6219       Value *Ptr = nullptr;
6220       unsigned PtrTypeID;
6221       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6222         return error("Invalid record");
6223 
6224       if (!isa<PointerType>(Ptr->getType()))
6225         return error("Cmpxchg operand is not a pointer type");
6226 
6227       Value *Cmp = nullptr;
6228       unsigned CmpTypeID;
6229       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6230         return error("Invalid record");
6231 
6232       Value *Val = nullptr;
6233       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
6234                    CurBB))
6235         return error("Invalid record");
6236 
6237       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6238         return error("Invalid record");
6239 
6240       const bool IsVol = Record[OpNum];
6241 
6242       const AtomicOrdering SuccessOrdering =
6243           getDecodedOrdering(Record[OpNum + 1]);
6244       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6245         return error("Invalid cmpxchg success ordering");
6246 
6247       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6248 
6249       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6250         return Err;
6251 
6252       const AtomicOrdering FailureOrdering =
6253           getDecodedOrdering(Record[OpNum + 3]);
6254       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6255         return error("Invalid cmpxchg failure ordering");
6256 
6257       const bool IsWeak = Record[OpNum + 4];
6258 
6259       MaybeAlign Alignment;
6260 
6261       if (NumRecords == (OpNum + 6)) {
6262         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6263           return Err;
6264       }
6265       if (!Alignment)
6266         Alignment =
6267             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6268 
6269       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6270                                 FailureOrdering, SSID);
6271       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6272       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6273 
6274       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6275       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6276 
6277       InstructionList.push_back(I);
6278       break;
6279     }
6280     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
6281     case bitc::FUNC_CODE_INST_ATOMICRMW: {
6282       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6283       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6284       const size_t NumRecords = Record.size();
6285       unsigned OpNum = 0;
6286 
6287       Value *Ptr = nullptr;
6288       unsigned PtrTypeID;
6289       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6290         return error("Invalid record");
6291 
6292       if (!isa<PointerType>(Ptr->getType()))
6293         return error("Invalid record");
6294 
6295       Value *Val = nullptr;
6296       unsigned ValTypeID = InvalidTypeID;
6297       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
6298         ValTypeID = getContainedTypeID(PtrTypeID);
6299         if (popValue(Record, OpNum, NextValueNo,
6300                      getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6301           return error("Invalid record");
6302       } else {
6303         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6304           return error("Invalid record");
6305       }
6306 
6307       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6308         return error("Invalid record");
6309 
6310       const AtomicRMWInst::BinOp Operation =
6311           getDecodedRMWOperation(Record[OpNum]);
6312       if (Operation < AtomicRMWInst::FIRST_BINOP ||
6313           Operation > AtomicRMWInst::LAST_BINOP)
6314         return error("Invalid record");
6315 
6316       const bool IsVol = Record[OpNum + 1];
6317 
6318       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6319       if (Ordering == AtomicOrdering::NotAtomic ||
6320           Ordering == AtomicOrdering::Unordered)
6321         return error("Invalid record");
6322 
6323       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6324 
6325       MaybeAlign Alignment;
6326 
6327       if (NumRecords == (OpNum + 5)) {
6328         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6329           return Err;
6330       }
6331 
6332       if (!Alignment)
6333         Alignment =
6334             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6335 
6336       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
6337       ResTypeID = ValTypeID;
6338       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6339 
6340       InstructionList.push_back(I);
6341       break;
6342     }
6343     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6344       if (2 != Record.size())
6345         return error("Invalid record");
6346       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
6347       if (Ordering == AtomicOrdering::NotAtomic ||
6348           Ordering == AtomicOrdering::Unordered ||
6349           Ordering == AtomicOrdering::Monotonic)
6350         return error("Invalid record");
6351       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
6352       I = new FenceInst(Context, Ordering, SSID);
6353       InstructionList.push_back(I);
6354       break;
6355     }
6356     case bitc::FUNC_CODE_INST_CALL: {
6357       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6358       if (Record.size() < 3)
6359         return error("Invalid record");
6360 
6361       unsigned OpNum = 0;
6362       AttributeList PAL = getAttributes(Record[OpNum++]);
6363       unsigned CCInfo = Record[OpNum++];
6364 
6365       FastMathFlags FMF;
6366       if ((CCInfo >> bitc::CALL_FMF) & 1) {
6367         FMF = getDecodedFastMathFlags(Record[OpNum++]);
6368         if (!FMF.any())
6369           return error("Fast math flags indicator set for call with no FMF");
6370       }
6371 
6372       unsigned FTyID = InvalidTypeID;
6373       FunctionType *FTy = nullptr;
6374       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6375         FTyID = Record[OpNum++];
6376         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6377         if (!FTy)
6378           return error("Explicit call type is not a function type");
6379       }
6380 
6381       Value *Callee;
6382       unsigned CalleeTypeID;
6383       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6384                            CurBB))
6385         return error("Invalid record");
6386 
6387       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6388       if (!OpTy)
6389         return error("Callee is not a pointer type");
6390       if (!FTy) {
6391         FTyID = getContainedTypeID(CalleeTypeID);
6392         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6393         if (!FTy)
6394           return error("Callee is not of pointer to function type");
6395       }
6396       if (Record.size() < FTy->getNumParams() + OpNum)
6397         return error("Insufficient operands to call");
6398 
6399       SmallVector<Value*, 16> Args;
6400       SmallVector<unsigned, 16> ArgTyIDs;
6401       // Read the fixed params.
6402       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6403         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6404         if (FTy->getParamType(i)->isLabelTy())
6405           Args.push_back(getBasicBlock(Record[OpNum]));
6406         else
6407           Args.push_back(getValue(Record, OpNum, NextValueNo,
6408                                   FTy->getParamType(i), ArgTyID, CurBB));
6409         ArgTyIDs.push_back(ArgTyID);
6410         if (!Args.back())
6411           return error("Invalid record");
6412       }
6413 
6414       // Read type/value pairs for varargs params.
6415       if (!FTy->isVarArg()) {
6416         if (OpNum != Record.size())
6417           return error("Invalid record");
6418       } else {
6419         while (OpNum != Record.size()) {
6420           Value *Op;
6421           unsigned OpTypeID;
6422           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6423             return error("Invalid record");
6424           Args.push_back(Op);
6425           ArgTyIDs.push_back(OpTypeID);
6426         }
6427       }
6428 
6429       // Upgrade the bundles if needed.
6430       if (!OperandBundles.empty())
6431         UpgradeOperandBundles(OperandBundles);
6432 
6433       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
6434       ResTypeID = getContainedTypeID(FTyID);
6435       OperandBundles.clear();
6436       InstructionList.push_back(I);
6437       cast<CallInst>(I)->setCallingConv(
6438           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6439       CallInst::TailCallKind TCK = CallInst::TCK_None;
6440       if (CCInfo & (1 << bitc::CALL_TAIL))
6441         TCK = CallInst::TCK_Tail;
6442       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6443         TCK = CallInst::TCK_MustTail;
6444       if (CCInfo & (1 << bitc::CALL_NOTAIL))
6445         TCK = CallInst::TCK_NoTail;
6446       cast<CallInst>(I)->setTailCallKind(TCK);
6447       cast<CallInst>(I)->setAttributes(PAL);
6448       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6449         I->deleteValue();
6450         return Err;
6451       }
6452       if (FMF.any()) {
6453         if (!isa<FPMathOperator>(I))
6454           return error("Fast-math-flags specified for call without "
6455                        "floating-point scalar or vector return type");
6456         I->setFastMathFlags(FMF);
6457       }
6458       break;
6459     }
6460     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6461       if (Record.size() < 3)
6462         return error("Invalid record");
6463       unsigned OpTyID = Record[0];
6464       Type *OpTy = getTypeByID(OpTyID);
6465       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6466       ResTypeID = Record[2];
6467       Type *ResTy = getTypeByID(ResTypeID);
6468       if (!OpTy || !Op || !ResTy)
6469         return error("Invalid record");
6470       I = new VAArgInst(Op, ResTy);
6471       InstructionList.push_back(I);
6472       break;
6473     }
6474 
6475     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
6476       // A call or an invoke can be optionally prefixed with some variable
6477       // number of operand bundle blocks.  These blocks are read into
6478       // OperandBundles and consumed at the next call or invoke instruction.
6479 
6480       if (Record.empty() || Record[0] >= BundleTags.size())
6481         return error("Invalid record");
6482 
6483       std::vector<Value *> Inputs;
6484 
6485       unsigned OpNum = 1;
6486       while (OpNum != Record.size()) {
6487         Value *Op;
6488         unsigned OpTypeID;
6489         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6490           return error("Invalid record");
6491         Inputs.push_back(Op);
6492       }
6493 
6494       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6495       continue;
6496     }
6497 
6498     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6499       unsigned OpNum = 0;
6500       Value *Op = nullptr;
6501       unsigned OpTypeID;
6502       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6503         return error("Invalid record");
6504       if (OpNum != Record.size())
6505         return error("Invalid record");
6506 
6507       I = new FreezeInst(Op);
6508       ResTypeID = OpTypeID;
6509       InstructionList.push_back(I);
6510       break;
6511     }
6512     }
6513 
6514     // Add instruction to end of current BB.  If there is no current BB, reject
6515     // this file.
6516     if (!CurBB) {
6517       I->deleteValue();
6518       return error("Invalid instruction with no BB");
6519     }
6520     if (!OperandBundles.empty()) {
6521       I->deleteValue();
6522       return error("Operand bundles found with no consumer");
6523     }
6524     I->insertInto(CurBB, CurBB->end());
6525 
6526     // If this was a terminator instruction, move to the next block.
6527     if (I->isTerminator()) {
6528       ++CurBBNo;
6529       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6530     }
6531 
6532     // Non-void values get registered in the value table for future use.
6533     if (!I->getType()->isVoidTy()) {
6534       assert(I->getType() == getTypeByID(ResTypeID) &&
6535              "Incorrect result type ID");
6536       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
6537         return Err;
6538     }
6539   }
6540 
6541 OutOfRecordLoop:
6542 
6543   if (!OperandBundles.empty())
6544     return error("Operand bundles found with no consumer");
6545 
6546   // Check the function list for unresolved values.
6547   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
6548     if (!A->getParent()) {
6549       // We found at least one unresolved value.  Nuke them all to avoid leaks.
6550       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
6551         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6552           A->replaceAllUsesWith(PoisonValue::get(A->getType()));
6553           delete A;
6554         }
6555       }
6556       return error("Never resolved value found in function");
6557     }
6558   }
6559 
6560   // Unexpected unresolved metadata about to be dropped.
6561   if (MDLoader->hasFwdRefs())
6562     return error("Invalid function metadata: outgoing forward refs");
6563 
6564   if (PhiConstExprBB)
6565     PhiConstExprBB->eraseFromParent();
6566 
6567   for (const auto &Pair : ConstExprEdgeBBs) {
6568     BasicBlock *From = Pair.first.first;
6569     BasicBlock *To = Pair.first.second;
6570     BasicBlock *EdgeBB = Pair.second;
6571     BranchInst::Create(To, EdgeBB);
6572     From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
6573     To->replacePhiUsesWith(From, EdgeBB);
6574     EdgeBB->moveBefore(To);
6575   }
6576 
6577   // Trim the value list down to the size it was before we parsed this function.
6578   ValueList.shrinkTo(ModuleValueListSize);
6579   MDLoader->shrinkTo(ModuleMDLoaderSize);
6580   std::vector<BasicBlock*>().swap(FunctionBBs);
6581   return Error::success();
6582 }
6583 
6584 /// Find the function body in the bitcode stream
6585 Error BitcodeReader::findFunctionInStream(
6586     Function *F,
6587     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
6588   while (DeferredFunctionInfoIterator->second == 0) {
6589     // This is the fallback handling for the old format bitcode that
6590     // didn't contain the function index in the VST, or when we have
6591     // an anonymous function which would not have a VST entry.
6592     // Assert that we have one of those two cases.
6593     assert(VSTOffset == 0 || !F->hasName());
6594     // Parse the next body in the stream and set its position in the
6595     // DeferredFunctionInfo map.
6596     if (Error Err = rememberAndSkipFunctionBodies())
6597       return Err;
6598   }
6599   return Error::success();
6600 }
6601 
6602 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
6603   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
6604     return SyncScope::ID(Val);
6605   if (Val >= SSIDs.size())
6606     return SyncScope::System; // Map unknown synchronization scopes to system.
6607   return SSIDs[Val];
6608 }
6609 
6610 //===----------------------------------------------------------------------===//
6611 // GVMaterializer implementation
6612 //===----------------------------------------------------------------------===//
6613 
6614 Error BitcodeReader::materialize(GlobalValue *GV) {
6615   Function *F = dyn_cast<Function>(GV);
6616   // If it's not a function or is already material, ignore the request.
6617   if (!F || !F->isMaterializable())
6618     return Error::success();
6619 
6620   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
6621   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
6622   // If its position is recorded as 0, its body is somewhere in the stream
6623   // but we haven't seen it yet.
6624   if (DFII->second == 0)
6625     if (Error Err = findFunctionInStream(F, DFII))
6626       return Err;
6627 
6628   // Materialize metadata before parsing any function bodies.
6629   if (Error Err = materializeMetadata())
6630     return Err;
6631 
6632   // Move the bit stream to the saved position of the deferred function body.
6633   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
6634     return JumpFailed;
6635   if (Error Err = parseFunctionBody(F))
6636     return Err;
6637   F->setIsMaterializable(false);
6638 
6639   if (StripDebugInfo)
6640     stripDebugInfo(*F);
6641 
6642   // Upgrade any old intrinsic calls in the function.
6643   for (auto &I : UpgradedIntrinsics) {
6644     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
6645       if (CallInst *CI = dyn_cast<CallInst>(U))
6646         UpgradeIntrinsicCall(CI, I.second);
6647   }
6648 
6649   // Finish fn->subprogram upgrade for materialized functions.
6650   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
6651     F->setSubprogram(SP);
6652 
6653   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
6654   if (!MDLoader->isStrippingTBAA()) {
6655     for (auto &I : instructions(F)) {
6656       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
6657       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
6658         continue;
6659       MDLoader->setStripTBAA(true);
6660       stripTBAA(F->getParent());
6661     }
6662   }
6663 
6664   for (auto &I : instructions(F)) {
6665     // "Upgrade" older incorrect branch weights by dropping them.
6666     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6667       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6668         MDString *MDS = cast<MDString>(MD->getOperand(0));
6669         StringRef ProfName = MDS->getString();
6670         // Check consistency of !prof branch_weights metadata.
6671         if (!ProfName.equals("branch_weights"))
6672           continue;
6673         unsigned ExpectedNumOperands = 0;
6674         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6675           ExpectedNumOperands = BI->getNumSuccessors();
6676         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6677           ExpectedNumOperands = SI->getNumSuccessors();
6678         else if (isa<CallInst>(&I))
6679           ExpectedNumOperands = 1;
6680         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6681           ExpectedNumOperands = IBI->getNumDestinations();
6682         else if (isa<SelectInst>(&I))
6683           ExpectedNumOperands = 2;
6684         else
6685           continue; // ignore and continue.
6686 
6687         // If branch weight doesn't match, just strip branch weight.
6688         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
6689           I.setMetadata(LLVMContext::MD_prof, nullptr);
6690       }
6691     }
6692 
6693     // Remove incompatible attributes on function calls.
6694     if (auto *CI = dyn_cast<CallBase>(&I)) {
6695       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
6696           CI->getFunctionType()->getReturnType()));
6697 
6698       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
6699         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
6700                                         CI->getArgOperand(ArgNo)->getType()));
6701     }
6702   }
6703 
6704   // Look for functions that rely on old function attribute behavior.
6705   UpgradeFunctionAttributes(*F);
6706 
6707   // Bring in any functions that this function forward-referenced via
6708   // blockaddresses.
6709   return materializeForwardReferencedFunctions();
6710 }
6711 
6712 Error BitcodeReader::materializeModule() {
6713   if (Error Err = materializeMetadata())
6714     return Err;
6715 
6716   // Promise to materialize all forward references.
6717   WillMaterializeAllForwardRefs = true;
6718 
6719   // Iterate over the module, deserializing any functions that are still on
6720   // disk.
6721   for (Function &F : *TheModule) {
6722     if (Error Err = materialize(&F))
6723       return Err;
6724   }
6725   // At this point, if there are any function bodies, parse the rest of
6726   // the bits in the module past the last function block we have recorded
6727   // through either lazy scanning or the VST.
6728   if (LastFunctionBlockBit || NextUnreadBit)
6729     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
6730                                     ? LastFunctionBlockBit
6731                                     : NextUnreadBit))
6732       return Err;
6733 
6734   // Check that all block address forward references got resolved (as we
6735   // promised above).
6736   if (!BasicBlockFwdRefs.empty())
6737     return error("Never resolved function from blockaddress");
6738 
6739   // Upgrade any intrinsic calls that slipped through (should not happen!) and
6740   // delete the old functions to clean up. We can't do this unless the entire
6741   // module is materialized because there could always be another function body
6742   // with calls to the old function.
6743   for (auto &I : UpgradedIntrinsics) {
6744     for (auto *U : I.first->users()) {
6745       if (CallInst *CI = dyn_cast<CallInst>(U))
6746         UpgradeIntrinsicCall(CI, I.second);
6747     }
6748     if (!I.first->use_empty())
6749       I.first->replaceAllUsesWith(I.second);
6750     I.first->eraseFromParent();
6751   }
6752   UpgradedIntrinsics.clear();
6753 
6754   UpgradeDebugInfo(*TheModule);
6755 
6756   UpgradeModuleFlags(*TheModule);
6757 
6758   UpgradeARCRuntime(*TheModule);
6759 
6760   return Error::success();
6761 }
6762 
6763 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
6764   return IdentifiedStructTypes;
6765 }
6766 
6767 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
6768     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
6769     StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
6770     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
6771       ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
6772 
6773 void ModuleSummaryIndexBitcodeReader::addThisModule() {
6774   TheIndex.addModule(ModulePath);
6775 }
6776 
6777 ModuleSummaryIndex::ModuleInfo *
6778 ModuleSummaryIndexBitcodeReader::getThisModule() {
6779   return TheIndex.getModule(ModulePath);
6780 }
6781 
6782 template <bool AllowNullValueInfo>
6783 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
6784 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
6785   auto VGI = ValueIdToValueInfoMap[ValueId];
6786   // We can have a null value info for memprof callsite info records in
6787   // distributed ThinLTO index files when the callee function summary is not
6788   // included in the index. The bitcode writer records 0 in that case,
6789   // and the caller of this helper will set AllowNullValueInfo to true.
6790   assert(AllowNullValueInfo || std::get<0>(VGI));
6791   return VGI;
6792 }
6793 
6794 void ModuleSummaryIndexBitcodeReader::setValueGUID(
6795     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
6796     StringRef SourceFileName) {
6797   std::string GlobalId =
6798       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
6799   auto ValueGUID = GlobalValue::getGUID(GlobalId);
6800   auto OriginalNameID = ValueGUID;
6801   if (GlobalValue::isLocalLinkage(Linkage))
6802     OriginalNameID = GlobalValue::getGUID(ValueName);
6803   if (PrintSummaryGUIDs)
6804     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
6805            << ValueName << "\n";
6806 
6807   // UseStrtab is false for legacy summary formats and value names are
6808   // created on stack. In that case we save the name in a string saver in
6809   // the index so that the value name can be recorded.
6810   ValueIdToValueInfoMap[ValueID] = std::make_tuple(
6811       TheIndex.getOrInsertValueInfo(
6812           ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
6813       OriginalNameID, ValueGUID);
6814 }
6815 
6816 // Specialized value symbol table parser used when reading module index
6817 // blocks where we don't actually create global values. The parsed information
6818 // is saved in the bitcode reader for use when later parsing summaries.
6819 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
6820     uint64_t Offset,
6821     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
6822   // With a strtab the VST is not required to parse the summary.
6823   if (UseStrtab)
6824     return Error::success();
6825 
6826   assert(Offset > 0 && "Expected non-zero VST offset");
6827   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
6828   if (!MaybeCurrentBit)
6829     return MaybeCurrentBit.takeError();
6830   uint64_t CurrentBit = MaybeCurrentBit.get();
6831 
6832   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
6833     return Err;
6834 
6835   SmallVector<uint64_t, 64> Record;
6836 
6837   // Read all the records for this value table.
6838   SmallString<128> ValueName;
6839 
6840   while (true) {
6841     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6842     if (!MaybeEntry)
6843       return MaybeEntry.takeError();
6844     BitstreamEntry Entry = MaybeEntry.get();
6845 
6846     switch (Entry.Kind) {
6847     case BitstreamEntry::SubBlock: // Handled for us already.
6848     case BitstreamEntry::Error:
6849       return error("Malformed block");
6850     case BitstreamEntry::EndBlock:
6851       // Done parsing VST, jump back to wherever we came from.
6852       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
6853         return JumpFailed;
6854       return Error::success();
6855     case BitstreamEntry::Record:
6856       // The interesting case.
6857       break;
6858     }
6859 
6860     // Read a record.
6861     Record.clear();
6862     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6863     if (!MaybeRecord)
6864       return MaybeRecord.takeError();
6865     switch (MaybeRecord.get()) {
6866     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
6867       break;
6868     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
6869       if (convertToString(Record, 1, ValueName))
6870         return error("Invalid record");
6871       unsigned ValueID = Record[0];
6872       assert(!SourceFileName.empty());
6873       auto VLI = ValueIdToLinkageMap.find(ValueID);
6874       assert(VLI != ValueIdToLinkageMap.end() &&
6875              "No linkage found for VST entry?");
6876       auto Linkage = VLI->second;
6877       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6878       ValueName.clear();
6879       break;
6880     }
6881     case bitc::VST_CODE_FNENTRY: {
6882       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
6883       if (convertToString(Record, 2, ValueName))
6884         return error("Invalid record");
6885       unsigned ValueID = Record[0];
6886       assert(!SourceFileName.empty());
6887       auto VLI = ValueIdToLinkageMap.find(ValueID);
6888       assert(VLI != ValueIdToLinkageMap.end() &&
6889              "No linkage found for VST entry?");
6890       auto Linkage = VLI->second;
6891       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6892       ValueName.clear();
6893       break;
6894     }
6895     case bitc::VST_CODE_COMBINED_ENTRY: {
6896       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6897       unsigned ValueID = Record[0];
6898       GlobalValue::GUID RefGUID = Record[1];
6899       // The "original name", which is the second value of the pair will be
6900       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6901       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
6902           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
6903       break;
6904     }
6905     }
6906   }
6907 }
6908 
6909 // Parse just the blocks needed for building the index out of the module.
6910 // At the end of this routine the module Index is populated with a map
6911 // from global value id to GlobalValueSummary objects.
6912 Error ModuleSummaryIndexBitcodeReader::parseModule() {
6913   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6914     return Err;
6915 
6916   SmallVector<uint64_t, 64> Record;
6917   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6918   unsigned ValueId = 0;
6919 
6920   // Read the index for this module.
6921   while (true) {
6922     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6923     if (!MaybeEntry)
6924       return MaybeEntry.takeError();
6925     llvm::BitstreamEntry Entry = MaybeEntry.get();
6926 
6927     switch (Entry.Kind) {
6928     case BitstreamEntry::Error:
6929       return error("Malformed block");
6930     case BitstreamEntry::EndBlock:
6931       return Error::success();
6932 
6933     case BitstreamEntry::SubBlock:
6934       switch (Entry.ID) {
6935       default: // Skip unknown content.
6936         if (Error Err = Stream.SkipBlock())
6937           return Err;
6938         break;
6939       case bitc::BLOCKINFO_BLOCK_ID:
6940         // Need to parse these to get abbrev ids (e.g. for VST)
6941         if (Error Err = readBlockInfo())
6942           return Err;
6943         break;
6944       case bitc::VALUE_SYMTAB_BLOCK_ID:
6945         // Should have been parsed earlier via VSTOffset, unless there
6946         // is no summary section.
6947         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6948                 !SeenGlobalValSummary) &&
6949                "Expected early VST parse via VSTOffset record");
6950         if (Error Err = Stream.SkipBlock())
6951           return Err;
6952         break;
6953       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6954       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
6955         // Add the module if it is a per-module index (has a source file name).
6956         if (!SourceFileName.empty())
6957           addThisModule();
6958         assert(!SeenValueSymbolTable &&
6959                "Already read VST when parsing summary block?");
6960         // We might not have a VST if there were no values in the
6961         // summary. An empty summary block generated when we are
6962         // performing ThinLTO compiles so we don't later invoke
6963         // the regular LTO process on them.
6964         if (VSTOffset > 0) {
6965           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6966             return Err;
6967           SeenValueSymbolTable = true;
6968         }
6969         SeenGlobalValSummary = true;
6970         if (Error Err = parseEntireSummary(Entry.ID))
6971           return Err;
6972         break;
6973       case bitc::MODULE_STRTAB_BLOCK_ID:
6974         if (Error Err = parseModuleStringTable())
6975           return Err;
6976         break;
6977       }
6978       continue;
6979 
6980     case BitstreamEntry::Record: {
6981         Record.clear();
6982         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6983         if (!MaybeBitCode)
6984           return MaybeBitCode.takeError();
6985         switch (MaybeBitCode.get()) {
6986         default:
6987           break; // Default behavior, ignore unknown content.
6988         case bitc::MODULE_CODE_VERSION: {
6989           if (Error Err = parseVersionRecord(Record).takeError())
6990             return Err;
6991           break;
6992         }
6993         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6994         case bitc::MODULE_CODE_SOURCE_FILENAME: {
6995           SmallString<128> ValueName;
6996           if (convertToString(Record, 0, ValueName))
6997             return error("Invalid record");
6998           SourceFileName = ValueName.c_str();
6999           break;
7000         }
7001         /// MODULE_CODE_HASH: [5*i32]
7002         case bitc::MODULE_CODE_HASH: {
7003           if (Record.size() != 5)
7004             return error("Invalid hash length " + Twine(Record.size()).str());
7005           auto &Hash = getThisModule()->second;
7006           int Pos = 0;
7007           for (auto &Val : Record) {
7008             assert(!(Val >> 32) && "Unexpected high bits set");
7009             Hash[Pos++] = Val;
7010           }
7011           break;
7012         }
7013         /// MODULE_CODE_VSTOFFSET: [offset]
7014         case bitc::MODULE_CODE_VSTOFFSET:
7015           if (Record.empty())
7016             return error("Invalid record");
7017           // Note that we subtract 1 here because the offset is relative to one
7018           // word before the start of the identification or module block, which
7019           // was historically always the start of the regular bitcode header.
7020           VSTOffset = Record[0] - 1;
7021           break;
7022         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
7023         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
7024         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
7025         // v2: [strtab offset, strtab size, v1]
7026         case bitc::MODULE_CODE_GLOBALVAR:
7027         case bitc::MODULE_CODE_FUNCTION:
7028         case bitc::MODULE_CODE_ALIAS: {
7029           StringRef Name;
7030           ArrayRef<uint64_t> GVRecord;
7031           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7032           if (GVRecord.size() <= 3)
7033             return error("Invalid record");
7034           uint64_t RawLinkage = GVRecord[3];
7035           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
7036           if (!UseStrtab) {
7037             ValueIdToLinkageMap[ValueId++] = Linkage;
7038             break;
7039           }
7040 
7041           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
7042           break;
7043         }
7044         }
7045       }
7046       continue;
7047     }
7048   }
7049 }
7050 
7051 std::vector<ValueInfo>
7052 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7053   std::vector<ValueInfo> Ret;
7054   Ret.reserve(Record.size());
7055   for (uint64_t RefValueId : Record)
7056     Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7057   return Ret;
7058 }
7059 
7060 std::vector<FunctionSummary::EdgeTy>
7061 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7062                                               bool IsOldProfileFormat,
7063                                               bool HasProfile, bool HasRelBF) {
7064   std::vector<FunctionSummary::EdgeTy> Ret;
7065   Ret.reserve(Record.size());
7066   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7067     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7068     bool HasTailCall = false;
7069     uint64_t RelBF = 0;
7070     ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7071     if (IsOldProfileFormat) {
7072       I += 1; // Skip old callsitecount field
7073       if (HasProfile)
7074         I += 1; // Skip old profilecount field
7075     } else if (HasProfile)
7076       std::tie(Hotness, HasTailCall) =
7077           getDecodedHotnessCallEdgeInfo(Record[++I]);
7078     else if (HasRelBF)
7079       getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7080     Ret.push_back(FunctionSummary::EdgeTy{
7081         Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
7082   }
7083   return Ret;
7084 }
7085 
7086 static void
7087 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
7088                                        WholeProgramDevirtResolution &Wpd) {
7089   uint64_t ArgNum = Record[Slot++];
7090   WholeProgramDevirtResolution::ByArg &B =
7091       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7092   Slot += ArgNum;
7093 
7094   B.TheKind =
7095       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
7096   B.Info = Record[Slot++];
7097   B.Byte = Record[Slot++];
7098   B.Bit = Record[Slot++];
7099 }
7100 
7101 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
7102                                               StringRef Strtab, size_t &Slot,
7103                                               TypeIdSummary &TypeId) {
7104   uint64_t Id = Record[Slot++];
7105   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7106 
7107   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7108   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7109                         static_cast<size_t>(Record[Slot + 1])};
7110   Slot += 2;
7111 
7112   uint64_t ResByArgNum = Record[Slot++];
7113   for (uint64_t I = 0; I != ResByArgNum; ++I)
7114     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
7115 }
7116 
7117 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
7118                                      StringRef Strtab,
7119                                      ModuleSummaryIndex &TheIndex) {
7120   size_t Slot = 0;
7121   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7122       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7123   Slot += 2;
7124 
7125   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7126   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7127   TypeId.TTRes.AlignLog2 = Record[Slot++];
7128   TypeId.TTRes.SizeM1 = Record[Slot++];
7129   TypeId.TTRes.BitMask = Record[Slot++];
7130   TypeId.TTRes.InlineBits = Record[Slot++];
7131 
7132   while (Slot < Record.size())
7133     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7134 }
7135 
7136 std::vector<FunctionSummary::ParamAccess>
7137 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7138   auto ReadRange = [&]() {
7139     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
7140                 BitcodeReader::decodeSignRotatedValue(Record.front()));
7141     Record = Record.drop_front();
7142     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
7143                 BitcodeReader::decodeSignRotatedValue(Record.front()));
7144     Record = Record.drop_front();
7145     ConstantRange Range{Lower, Upper};
7146     assert(!Range.isFullSet());
7147     assert(!Range.isUpperSignWrapped());
7148     return Range;
7149   };
7150 
7151   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7152   while (!Record.empty()) {
7153     PendingParamAccesses.emplace_back();
7154     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7155     ParamAccess.ParamNo = Record.front();
7156     Record = Record.drop_front();
7157     ParamAccess.Use = ReadRange();
7158     ParamAccess.Calls.resize(Record.front());
7159     Record = Record.drop_front();
7160     for (auto &Call : ParamAccess.Calls) {
7161       Call.ParamNo = Record.front();
7162       Record = Record.drop_front();
7163       Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
7164       Record = Record.drop_front();
7165       Call.Offsets = ReadRange();
7166     }
7167   }
7168   return PendingParamAccesses;
7169 }
7170 
7171 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7172     ArrayRef<uint64_t> Record, size_t &Slot,
7173     TypeIdCompatibleVtableInfo &TypeId) {
7174   uint64_t Offset = Record[Slot++];
7175   ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7176   TypeId.push_back({Offset, Callee});
7177 }
7178 
7179 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7180     ArrayRef<uint64_t> Record) {
7181   size_t Slot = 0;
7182   TypeIdCompatibleVtableInfo &TypeId =
7183       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
7184           {Strtab.data() + Record[Slot],
7185            static_cast<size_t>(Record[Slot + 1])});
7186   Slot += 2;
7187 
7188   while (Slot < Record.size())
7189     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7190 }
7191 
7192 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
7193                            unsigned WOCnt) {
7194   // Readonly and writeonly refs are in the end of the refs list.
7195   assert(ROCnt + WOCnt <= Refs.size());
7196   unsigned FirstWORef = Refs.size() - WOCnt;
7197   unsigned RefNo = FirstWORef - ROCnt;
7198   for (; RefNo < FirstWORef; ++RefNo)
7199     Refs[RefNo].setReadOnly();
7200   for (; RefNo < Refs.size(); ++RefNo)
7201     Refs[RefNo].setWriteOnly();
7202 }
7203 
7204 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
7205 // objects in the index.
7206 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7207   if (Error Err = Stream.EnterSubBlock(ID))
7208     return Err;
7209   SmallVector<uint64_t, 64> Record;
7210 
7211   // Parse version
7212   {
7213     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7214     if (!MaybeEntry)
7215       return MaybeEntry.takeError();
7216     BitstreamEntry Entry = MaybeEntry.get();
7217 
7218     if (Entry.Kind != BitstreamEntry::Record)
7219       return error("Invalid Summary Block: record for version expected");
7220     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7221     if (!MaybeRecord)
7222       return MaybeRecord.takeError();
7223     if (MaybeRecord.get() != bitc::FS_VERSION)
7224       return error("Invalid Summary Block: version expected");
7225   }
7226   const uint64_t Version = Record[0];
7227   const bool IsOldProfileFormat = Version == 1;
7228   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
7229     return error("Invalid summary version " + Twine(Version) +
7230                  ". Version should be in the range [1-" +
7231                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7232                  "].");
7233   Record.clear();
7234 
7235   // Keep around the last seen summary to be used when we see an optional
7236   // "OriginalName" attachement.
7237   GlobalValueSummary *LastSeenSummary = nullptr;
7238   GlobalValue::GUID LastSeenGUID = 0;
7239 
7240   // We can expect to see any number of type ID information records before
7241   // each function summary records; these variables store the information
7242   // collected so far so that it can be used to create the summary object.
7243   std::vector<GlobalValue::GUID> PendingTypeTests;
7244   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7245       PendingTypeCheckedLoadVCalls;
7246   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7247       PendingTypeCheckedLoadConstVCalls;
7248   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7249 
7250   std::vector<CallsiteInfo> PendingCallsites;
7251   std::vector<AllocInfo> PendingAllocs;
7252 
7253   while (true) {
7254     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7255     if (!MaybeEntry)
7256       return MaybeEntry.takeError();
7257     BitstreamEntry Entry = MaybeEntry.get();
7258 
7259     switch (Entry.Kind) {
7260     case BitstreamEntry::SubBlock: // Handled for us already.
7261     case BitstreamEntry::Error:
7262       return error("Malformed block");
7263     case BitstreamEntry::EndBlock:
7264       return Error::success();
7265     case BitstreamEntry::Record:
7266       // The interesting case.
7267       break;
7268     }
7269 
7270     // Read a record. The record format depends on whether this
7271     // is a per-module index or a combined index file. In the per-module
7272     // case the records contain the associated value's ID for correlation
7273     // with VST entries. In the combined index the correlation is done
7274     // via the bitcode offset of the summary records (which were saved
7275     // in the combined index VST entries). The records also contain
7276     // information used for ThinLTO renaming and importing.
7277     Record.clear();
7278     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7279     if (!MaybeBitCode)
7280       return MaybeBitCode.takeError();
7281     switch (unsigned BitCode = MaybeBitCode.get()) {
7282     default: // Default behavior: ignore.
7283       break;
7284     case bitc::FS_FLAGS: {  // [flags]
7285       TheIndex.setFlags(Record[0]);
7286       break;
7287     }
7288     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
7289       uint64_t ValueID = Record[0];
7290       GlobalValue::GUID RefGUID = Record[1];
7291       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7292           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
7293       break;
7294     }
7295     // FS_PERMODULE is legacy and does not have support for the tail call flag.
7296     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7297     //                numrefs x valueid, n x (valueid)]
7298     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7299     //                        numrefs x valueid,
7300     //                        n x (valueid, hotness+tailcall flags)]
7301     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7302     //                      numrefs x valueid,
7303     //                      n x (valueid, relblockfreq+tailcall)]
7304     case bitc::FS_PERMODULE:
7305     case bitc::FS_PERMODULE_RELBF:
7306     case bitc::FS_PERMODULE_PROFILE: {
7307       unsigned ValueID = Record[0];
7308       uint64_t RawFlags = Record[1];
7309       unsigned InstCount = Record[2];
7310       uint64_t RawFunFlags = 0;
7311       unsigned NumRefs = Record[3];
7312       unsigned NumRORefs = 0, NumWORefs = 0;
7313       int RefListStartIndex = 4;
7314       if (Version >= 4) {
7315         RawFunFlags = Record[3];
7316         NumRefs = Record[4];
7317         RefListStartIndex = 5;
7318         if (Version >= 5) {
7319           NumRORefs = Record[5];
7320           RefListStartIndex = 6;
7321           if (Version >= 7) {
7322             NumWORefs = Record[6];
7323             RefListStartIndex = 7;
7324           }
7325         }
7326       }
7327 
7328       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7329       // The module path string ref set in the summary must be owned by the
7330       // index's module string table. Since we don't have a module path
7331       // string table section in the per-module index, we create a single
7332       // module path string table entry with an empty (0) ID to take
7333       // ownership.
7334       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7335       assert(Record.size() >= RefListStartIndex + NumRefs &&
7336              "Record size inconsistent with number of references");
7337       std::vector<ValueInfo> Refs = makeRefList(
7338           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7339       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7340       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7341       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
7342           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7343           IsOldProfileFormat, HasProfile, HasRelBF);
7344       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7345       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7346       // In order to save memory, only record the memprof summaries if this is
7347       // the prevailing copy of a symbol. The linker doesn't resolve local
7348       // linkage values so don't check whether those are prevailing.
7349       auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7350       if (IsPrevailing &&
7351           !GlobalValue::isLocalLinkage(LT) &&
7352           !IsPrevailing(std::get<2>(VIAndOriginalGUID))) {
7353         PendingCallsites.clear();
7354         PendingAllocs.clear();
7355       }
7356       auto FS = std::make_unique<FunctionSummary>(
7357           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
7358           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
7359           std::move(PendingTypeTestAssumeVCalls),
7360           std::move(PendingTypeCheckedLoadVCalls),
7361           std::move(PendingTypeTestAssumeConstVCalls),
7362           std::move(PendingTypeCheckedLoadConstVCalls),
7363           std::move(PendingParamAccesses), std::move(PendingCallsites),
7364           std::move(PendingAllocs));
7365       FS->setModulePath(getThisModule()->first());
7366       FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7367       TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7368                                      std::move(FS));
7369       break;
7370     }
7371     // FS_ALIAS: [valueid, flags, valueid]
7372     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7373     // they expect all aliasee summaries to be available.
7374     case bitc::FS_ALIAS: {
7375       unsigned ValueID = Record[0];
7376       uint64_t RawFlags = Record[1];
7377       unsigned AliaseeID = Record[2];
7378       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7379       auto AS = std::make_unique<AliasSummary>(Flags);
7380       // The module path string ref set in the summary must be owned by the
7381       // index's module string table. Since we don't have a module path
7382       // string table section in the per-module index, we create a single
7383       // module path string table entry with an empty (0) ID to take
7384       // ownership.
7385       AS->setModulePath(getThisModule()->first());
7386 
7387       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7388       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7389       if (!AliaseeInModule)
7390         return error("Alias expects aliasee summary to be parsed");
7391       AS->setAliasee(AliaseeVI, AliaseeInModule);
7392 
7393       auto GUID = getValueInfoFromValueId(ValueID);
7394       AS->setOriginalName(std::get<1>(GUID));
7395       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
7396       break;
7397     }
7398     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7399     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
7400       unsigned ValueID = Record[0];
7401       uint64_t RawFlags = Record[1];
7402       unsigned RefArrayStart = 2;
7403       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7404                                       /* WriteOnly */ false,
7405                                       /* Constant */ false,
7406                                       GlobalObject::VCallVisibilityPublic);
7407       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7408       if (Version >= 5) {
7409         GVF = getDecodedGVarFlags(Record[2]);
7410         RefArrayStart = 3;
7411       }
7412       std::vector<ValueInfo> Refs =
7413           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7414       auto FS =
7415           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7416       FS->setModulePath(getThisModule()->first());
7417       auto GUID = getValueInfoFromValueId(ValueID);
7418       FS->setOriginalName(std::get<1>(GUID));
7419       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
7420       break;
7421     }
7422     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7423     //                        numrefs, numrefs x valueid,
7424     //                        n x (valueid, offset)]
7425     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
7426       unsigned ValueID = Record[0];
7427       uint64_t RawFlags = Record[1];
7428       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
7429       unsigned NumRefs = Record[3];
7430       unsigned RefListStartIndex = 4;
7431       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7432       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7433       std::vector<ValueInfo> Refs = makeRefList(
7434           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7435       VTableFuncList VTableFuncs;
7436       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7437         ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7438         uint64_t Offset = Record[++I];
7439         VTableFuncs.push_back({Callee, Offset});
7440       }
7441       auto VS =
7442           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7443       VS->setModulePath(getThisModule()->first());
7444       VS->setVTableFuncs(VTableFuncs);
7445       auto GUID = getValueInfoFromValueId(ValueID);
7446       VS->setOriginalName(std::get<1>(GUID));
7447       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
7448       break;
7449     }
7450     // FS_COMBINED is legacy and does not have support for the tail call flag.
7451     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7452     //               numrefs x valueid, n x (valueid)]
7453     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7454     //                       numrefs x valueid,
7455     //                       n x (valueid, hotness+tailcall flags)]
7456     case bitc::FS_COMBINED:
7457     case bitc::FS_COMBINED_PROFILE: {
7458       unsigned ValueID = Record[0];
7459       uint64_t ModuleId = Record[1];
7460       uint64_t RawFlags = Record[2];
7461       unsigned InstCount = Record[3];
7462       uint64_t RawFunFlags = 0;
7463       uint64_t EntryCount = 0;
7464       unsigned NumRefs = Record[4];
7465       unsigned NumRORefs = 0, NumWORefs = 0;
7466       int RefListStartIndex = 5;
7467 
7468       if (Version >= 4) {
7469         RawFunFlags = Record[4];
7470         RefListStartIndex = 6;
7471         size_t NumRefsIndex = 5;
7472         if (Version >= 5) {
7473           unsigned NumRORefsOffset = 1;
7474           RefListStartIndex = 7;
7475           if (Version >= 6) {
7476             NumRefsIndex = 6;
7477             EntryCount = Record[5];
7478             RefListStartIndex = 8;
7479             if (Version >= 7) {
7480               RefListStartIndex = 9;
7481               NumWORefs = Record[8];
7482               NumRORefsOffset = 2;
7483             }
7484           }
7485           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7486         }
7487         NumRefs = Record[NumRefsIndex];
7488       }
7489 
7490       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7491       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7492       assert(Record.size() >= RefListStartIndex + NumRefs &&
7493              "Record size inconsistent with number of references");
7494       std::vector<ValueInfo> Refs = makeRefList(
7495           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7496       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
7497       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
7498           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7499           IsOldProfileFormat, HasProfile, false);
7500       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7501       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7502       auto FS = std::make_unique<FunctionSummary>(
7503           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
7504           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
7505           std::move(PendingTypeTestAssumeVCalls),
7506           std::move(PendingTypeCheckedLoadVCalls),
7507           std::move(PendingTypeTestAssumeConstVCalls),
7508           std::move(PendingTypeCheckedLoadConstVCalls),
7509           std::move(PendingParamAccesses), std::move(PendingCallsites),
7510           std::move(PendingAllocs));
7511       LastSeenSummary = FS.get();
7512       LastSeenGUID = VI.getGUID();
7513       FS->setModulePath(ModuleIdMap[ModuleId]);
7514       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7515       break;
7516     }
7517     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7518     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7519     // they expect all aliasee summaries to be available.
7520     case bitc::FS_COMBINED_ALIAS: {
7521       unsigned ValueID = Record[0];
7522       uint64_t ModuleId = Record[1];
7523       uint64_t RawFlags = Record[2];
7524       unsigned AliaseeValueId = Record[3];
7525       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7526       auto AS = std::make_unique<AliasSummary>(Flags);
7527       LastSeenSummary = AS.get();
7528       AS->setModulePath(ModuleIdMap[ModuleId]);
7529 
7530       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7531       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
7532       AS->setAliasee(AliaseeVI, AliaseeInModule);
7533 
7534       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7535       LastSeenGUID = VI.getGUID();
7536       TheIndex.addGlobalValueSummary(VI, std::move(AS));
7537       break;
7538     }
7539     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7540     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
7541       unsigned ValueID = Record[0];
7542       uint64_t ModuleId = Record[1];
7543       uint64_t RawFlags = Record[2];
7544       unsigned RefArrayStart = 3;
7545       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7546                                       /* WriteOnly */ false,
7547                                       /* Constant */ false,
7548                                       GlobalObject::VCallVisibilityPublic);
7549       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7550       if (Version >= 5) {
7551         GVF = getDecodedGVarFlags(Record[3]);
7552         RefArrayStart = 4;
7553       }
7554       std::vector<ValueInfo> Refs =
7555           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7556       auto FS =
7557           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7558       LastSeenSummary = FS.get();
7559       FS->setModulePath(ModuleIdMap[ModuleId]);
7560       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7561       LastSeenGUID = VI.getGUID();
7562       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7563       break;
7564     }
7565     // FS_COMBINED_ORIGINAL_NAME: [original_name]
7566     case bitc::FS_COMBINED_ORIGINAL_NAME: {
7567       uint64_t OriginalName = Record[0];
7568       if (!LastSeenSummary)
7569         return error("Name attachment that does not follow a combined record");
7570       LastSeenSummary->setOriginalName(OriginalName);
7571       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
7572       // Reset the LastSeenSummary
7573       LastSeenSummary = nullptr;
7574       LastSeenGUID = 0;
7575       break;
7576     }
7577     case bitc::FS_TYPE_TESTS:
7578       assert(PendingTypeTests.empty());
7579       llvm::append_range(PendingTypeTests, Record);
7580       break;
7581 
7582     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
7583       assert(PendingTypeTestAssumeVCalls.empty());
7584       for (unsigned I = 0; I != Record.size(); I += 2)
7585         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
7586       break;
7587 
7588     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
7589       assert(PendingTypeCheckedLoadVCalls.empty());
7590       for (unsigned I = 0; I != Record.size(); I += 2)
7591         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
7592       break;
7593 
7594     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
7595       PendingTypeTestAssumeConstVCalls.push_back(
7596           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
7597       break;
7598 
7599     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
7600       PendingTypeCheckedLoadConstVCalls.push_back(
7601           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
7602       break;
7603 
7604     case bitc::FS_CFI_FUNCTION_DEFS: {
7605       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
7606       for (unsigned I = 0; I != Record.size(); I += 2)
7607         CfiFunctionDefs.insert(
7608             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
7609       break;
7610     }
7611 
7612     case bitc::FS_CFI_FUNCTION_DECLS: {
7613       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
7614       for (unsigned I = 0; I != Record.size(); I += 2)
7615         CfiFunctionDecls.insert(
7616             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
7617       break;
7618     }
7619 
7620     case bitc::FS_TYPE_ID:
7621       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
7622       break;
7623 
7624     case bitc::FS_TYPE_ID_METADATA:
7625       parseTypeIdCompatibleVtableSummaryRecord(Record);
7626       break;
7627 
7628     case bitc::FS_BLOCK_COUNT:
7629       TheIndex.addBlockCount(Record[0]);
7630       break;
7631 
7632     case bitc::FS_PARAM_ACCESS: {
7633       PendingParamAccesses = parseParamAccesses(Record);
7634       break;
7635     }
7636 
7637     case bitc::FS_STACK_IDS: { // [n x stackid]
7638       // Save stack ids in the reader to consult when adding stack ids from the
7639       // lists in the stack node and alloc node entries.
7640       StackIds = ArrayRef<uint64_t>(Record);
7641       break;
7642     }
7643 
7644     case bitc::FS_PERMODULE_CALLSITE_INFO: {
7645       unsigned ValueID = Record[0];
7646       SmallVector<unsigned> StackIdList;
7647       for (auto R = Record.begin() + 1; R != Record.end(); R++) {
7648         assert(*R < StackIds.size());
7649         StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
7650       }
7651       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7652       PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
7653       break;
7654     }
7655 
7656     case bitc::FS_COMBINED_CALLSITE_INFO: {
7657       auto RecordIter = Record.begin();
7658       unsigned ValueID = *RecordIter++;
7659       unsigned NumStackIds = *RecordIter++;
7660       unsigned NumVersions = *RecordIter++;
7661       assert(Record.size() == 3 + NumStackIds + NumVersions);
7662       SmallVector<unsigned> StackIdList;
7663       for (unsigned J = 0; J < NumStackIds; J++) {
7664         assert(*RecordIter < StackIds.size());
7665         StackIdList.push_back(
7666             TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
7667       }
7668       SmallVector<unsigned> Versions;
7669       for (unsigned J = 0; J < NumVersions; J++)
7670         Versions.push_back(*RecordIter++);
7671       ValueInfo VI = std::get<0>(
7672           getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
7673       PendingCallsites.push_back(
7674           CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
7675       break;
7676     }
7677 
7678     case bitc::FS_PERMODULE_ALLOC_INFO: {
7679       unsigned I = 0;
7680       std::vector<MIBInfo> MIBs;
7681       while (I < Record.size()) {
7682         assert(Record.size() - I >= 2);
7683         AllocationType AllocType = (AllocationType)Record[I++];
7684         unsigned NumStackEntries = Record[I++];
7685         assert(Record.size() - I >= NumStackEntries);
7686         SmallVector<unsigned> StackIdList;
7687         for (unsigned J = 0; J < NumStackEntries; J++) {
7688           assert(Record[I] < StackIds.size());
7689           StackIdList.push_back(
7690               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7691         }
7692         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7693       }
7694       PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
7695       break;
7696     }
7697 
7698     case bitc::FS_COMBINED_ALLOC_INFO: {
7699       unsigned I = 0;
7700       std::vector<MIBInfo> MIBs;
7701       unsigned NumMIBs = Record[I++];
7702       unsigned NumVersions = Record[I++];
7703       unsigned MIBsRead = 0;
7704       while (MIBsRead++ < NumMIBs) {
7705         assert(Record.size() - I >= 2);
7706         AllocationType AllocType = (AllocationType)Record[I++];
7707         unsigned NumStackEntries = Record[I++];
7708         assert(Record.size() - I >= NumStackEntries);
7709         SmallVector<unsigned> StackIdList;
7710         for (unsigned J = 0; J < NumStackEntries; J++) {
7711           assert(Record[I] < StackIds.size());
7712           StackIdList.push_back(
7713               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7714         }
7715         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7716       }
7717       assert(Record.size() - I >= NumVersions);
7718       SmallVector<uint8_t> Versions;
7719       for (unsigned J = 0; J < NumVersions; J++)
7720         Versions.push_back(Record[I++]);
7721       PendingAllocs.push_back(
7722           AllocInfo(std::move(Versions), std::move(MIBs)));
7723       break;
7724     }
7725     }
7726   }
7727   llvm_unreachable("Exit infinite loop");
7728 }
7729 
7730 // Parse the  module string table block into the Index.
7731 // This populates the ModulePathStringTable map in the index.
7732 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
7733   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
7734     return Err;
7735 
7736   SmallVector<uint64_t, 64> Record;
7737 
7738   SmallString<128> ModulePath;
7739   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
7740 
7741   while (true) {
7742     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7743     if (!MaybeEntry)
7744       return MaybeEntry.takeError();
7745     BitstreamEntry Entry = MaybeEntry.get();
7746 
7747     switch (Entry.Kind) {
7748     case BitstreamEntry::SubBlock: // Handled for us already.
7749     case BitstreamEntry::Error:
7750       return error("Malformed block");
7751     case BitstreamEntry::EndBlock:
7752       return Error::success();
7753     case BitstreamEntry::Record:
7754       // The interesting case.
7755       break;
7756     }
7757 
7758     Record.clear();
7759     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7760     if (!MaybeRecord)
7761       return MaybeRecord.takeError();
7762     switch (MaybeRecord.get()) {
7763     default: // Default behavior: ignore.
7764       break;
7765     case bitc::MST_CODE_ENTRY: {
7766       // MST_ENTRY: [modid, namechar x N]
7767       uint64_t ModuleId = Record[0];
7768 
7769       if (convertToString(Record, 1, ModulePath))
7770         return error("Invalid record");
7771 
7772       LastSeenModule = TheIndex.addModule(ModulePath);
7773       ModuleIdMap[ModuleId] = LastSeenModule->first();
7774 
7775       ModulePath.clear();
7776       break;
7777     }
7778     /// MST_CODE_HASH: [5*i32]
7779     case bitc::MST_CODE_HASH: {
7780       if (Record.size() != 5)
7781         return error("Invalid hash length " + Twine(Record.size()).str());
7782       if (!LastSeenModule)
7783         return error("Invalid hash that does not follow a module path");
7784       int Pos = 0;
7785       for (auto &Val : Record) {
7786         assert(!(Val >> 32) && "Unexpected high bits set");
7787         LastSeenModule->second[Pos++] = Val;
7788       }
7789       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
7790       LastSeenModule = nullptr;
7791       break;
7792     }
7793     }
7794   }
7795   llvm_unreachable("Exit infinite loop");
7796 }
7797 
7798 namespace {
7799 
7800 // FIXME: This class is only here to support the transition to llvm::Error. It
7801 // will be removed once this transition is complete. Clients should prefer to
7802 // deal with the Error value directly, rather than converting to error_code.
7803 class BitcodeErrorCategoryType : public std::error_category {
7804   const char *name() const noexcept override {
7805     return "llvm.bitcode";
7806   }
7807 
7808   std::string message(int IE) const override {
7809     BitcodeError E = static_cast<BitcodeError>(IE);
7810     switch (E) {
7811     case BitcodeError::CorruptedBitcode:
7812       return "Corrupted bitcode";
7813     }
7814     llvm_unreachable("Unknown error type!");
7815   }
7816 };
7817 
7818 } // end anonymous namespace
7819 
7820 const std::error_category &llvm::BitcodeErrorCategory() {
7821   static BitcodeErrorCategoryType ErrorCategory;
7822   return ErrorCategory;
7823 }
7824 
7825 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
7826                                             unsigned Block, unsigned RecordID) {
7827   if (Error Err = Stream.EnterSubBlock(Block))
7828     return std::move(Err);
7829 
7830   StringRef Strtab;
7831   while (true) {
7832     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7833     if (!MaybeEntry)
7834       return MaybeEntry.takeError();
7835     llvm::BitstreamEntry Entry = MaybeEntry.get();
7836 
7837     switch (Entry.Kind) {
7838     case BitstreamEntry::EndBlock:
7839       return Strtab;
7840 
7841     case BitstreamEntry::Error:
7842       return error("Malformed block");
7843 
7844     case BitstreamEntry::SubBlock:
7845       if (Error Err = Stream.SkipBlock())
7846         return std::move(Err);
7847       break;
7848 
7849     case BitstreamEntry::Record:
7850       StringRef Blob;
7851       SmallVector<uint64_t, 1> Record;
7852       Expected<unsigned> MaybeRecord =
7853           Stream.readRecord(Entry.ID, Record, &Blob);
7854       if (!MaybeRecord)
7855         return MaybeRecord.takeError();
7856       if (MaybeRecord.get() == RecordID)
7857         Strtab = Blob;
7858       break;
7859     }
7860   }
7861 }
7862 
7863 //===----------------------------------------------------------------------===//
7864 // External interface
7865 //===----------------------------------------------------------------------===//
7866 
7867 Expected<std::vector<BitcodeModule>>
7868 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
7869   auto FOrErr = getBitcodeFileContents(Buffer);
7870   if (!FOrErr)
7871     return FOrErr.takeError();
7872   return std::move(FOrErr->Mods);
7873 }
7874 
7875 Expected<BitcodeFileContents>
7876 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
7877   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7878   if (!StreamOrErr)
7879     return StreamOrErr.takeError();
7880   BitstreamCursor &Stream = *StreamOrErr;
7881 
7882   BitcodeFileContents F;
7883   while (true) {
7884     uint64_t BCBegin = Stream.getCurrentByteNo();
7885 
7886     // We may be consuming bitcode from a client that leaves garbage at the end
7887     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
7888     // the end that there cannot possibly be another module, stop looking.
7889     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
7890       return F;
7891 
7892     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7893     if (!MaybeEntry)
7894       return MaybeEntry.takeError();
7895     llvm::BitstreamEntry Entry = MaybeEntry.get();
7896 
7897     switch (Entry.Kind) {
7898     case BitstreamEntry::EndBlock:
7899     case BitstreamEntry::Error:
7900       return error("Malformed block");
7901 
7902     case BitstreamEntry::SubBlock: {
7903       uint64_t IdentificationBit = -1ull;
7904       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
7905         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7906         if (Error Err = Stream.SkipBlock())
7907           return std::move(Err);
7908 
7909         {
7910           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7911           if (!MaybeEntry)
7912             return MaybeEntry.takeError();
7913           Entry = MaybeEntry.get();
7914         }
7915 
7916         if (Entry.Kind != BitstreamEntry::SubBlock ||
7917             Entry.ID != bitc::MODULE_BLOCK_ID)
7918           return error("Malformed block");
7919       }
7920 
7921       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
7922         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7923         if (Error Err = Stream.SkipBlock())
7924           return std::move(Err);
7925 
7926         F.Mods.push_back({Stream.getBitcodeBytes().slice(
7927                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
7928                           Buffer.getBufferIdentifier(), IdentificationBit,
7929                           ModuleBit});
7930         continue;
7931       }
7932 
7933       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
7934         Expected<StringRef> Strtab =
7935             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
7936         if (!Strtab)
7937           return Strtab.takeError();
7938         // This string table is used by every preceding bitcode module that does
7939         // not have its own string table. A bitcode file may have multiple
7940         // string tables if it was created by binary concatenation, for example
7941         // with "llvm-cat -b".
7942         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
7943           if (!I.Strtab.empty())
7944             break;
7945           I.Strtab = *Strtab;
7946         }
7947         // Similarly, the string table is used by every preceding symbol table;
7948         // normally there will be just one unless the bitcode file was created
7949         // by binary concatenation.
7950         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
7951           F.StrtabForSymtab = *Strtab;
7952         continue;
7953       }
7954 
7955       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
7956         Expected<StringRef> SymtabOrErr =
7957             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
7958         if (!SymtabOrErr)
7959           return SymtabOrErr.takeError();
7960 
7961         // We can expect the bitcode file to have multiple symbol tables if it
7962         // was created by binary concatenation. In that case we silently
7963         // ignore any subsequent symbol tables, which is fine because this is a
7964         // low level function. The client is expected to notice that the number
7965         // of modules in the symbol table does not match the number of modules
7966         // in the input file and regenerate the symbol table.
7967         if (F.Symtab.empty())
7968           F.Symtab = *SymtabOrErr;
7969         continue;
7970       }
7971 
7972       if (Error Err = Stream.SkipBlock())
7973         return std::move(Err);
7974       continue;
7975     }
7976     case BitstreamEntry::Record:
7977       if (Error E = Stream.skipRecord(Entry.ID).takeError())
7978         return std::move(E);
7979       continue;
7980     }
7981   }
7982 }
7983 
7984 /// Get a lazy one-at-time loading module from bitcode.
7985 ///
7986 /// This isn't always used in a lazy context.  In particular, it's also used by
7987 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
7988 /// in forward-referenced functions from block address references.
7989 ///
7990 /// \param[in] MaterializeAll Set to \c true if we should materialize
7991 /// everything.
7992 Expected<std::unique_ptr<Module>>
7993 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
7994                              bool ShouldLazyLoadMetadata, bool IsImporting,
7995                              ParserCallbacks Callbacks) {
7996   BitstreamCursor Stream(Buffer);
7997 
7998   std::string ProducerIdentification;
7999   if (IdentificationBit != -1ull) {
8000     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8001       return std::move(JumpFailed);
8002     if (Error E =
8003             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8004       return std::move(E);
8005   }
8006 
8007   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8008     return std::move(JumpFailed);
8009   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8010                               Context);
8011 
8012   std::unique_ptr<Module> M =
8013       std::make_unique<Module>(ModuleIdentifier, Context);
8014   M->setMaterializer(R);
8015 
8016   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8017   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8018                                       IsImporting, Callbacks))
8019     return std::move(Err);
8020 
8021   if (MaterializeAll) {
8022     // Read in the entire module, and destroy the BitcodeReader.
8023     if (Error Err = M->materializeAll())
8024       return std::move(Err);
8025   } else {
8026     // Resolve forward references from blockaddresses.
8027     if (Error Err = R->materializeForwardReferencedFunctions())
8028       return std::move(Err);
8029   }
8030   return std::move(M);
8031 }
8032 
8033 Expected<std::unique_ptr<Module>>
8034 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8035                              bool IsImporting, ParserCallbacks Callbacks) {
8036   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8037                        Callbacks);
8038 }
8039 
8040 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
8041 // We don't use ModuleIdentifier here because the client may need to control the
8042 // module path used in the combined summary (e.g. when reading summaries for
8043 // regular LTO modules).
8044 Error BitcodeModule::readSummary(
8045     ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8046     std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8047   BitstreamCursor Stream(Buffer);
8048   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8049     return JumpFailed;
8050 
8051   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8052                                     ModulePath, IsPrevailing);
8053   return R.parseModule();
8054 }
8055 
8056 // Parse the specified bitcode buffer, returning the function info index.
8057 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
8058   BitstreamCursor Stream(Buffer);
8059   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8060     return std::move(JumpFailed);
8061 
8062   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
8063   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8064                                     ModuleIdentifier, 0);
8065 
8066   if (Error Err = R.parseModule())
8067     return std::move(Err);
8068 
8069   return std::move(Index);
8070 }
8071 
8072 static Expected<std::pair<bool, bool>>
8073 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream,
8074                                                  unsigned ID,
8075                                                  BitcodeLTOInfo &LTOInfo) {
8076   if (Error Err = Stream.EnterSubBlock(ID))
8077     return std::move(Err);
8078   SmallVector<uint64_t, 64> Record;
8079 
8080   while (true) {
8081     BitstreamEntry Entry;
8082     std::pair<bool, bool> Result = {false,false};
8083     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8084       return std::move(E);
8085 
8086     switch (Entry.Kind) {
8087     case BitstreamEntry::SubBlock: // Handled for us already.
8088     case BitstreamEntry::Error:
8089       return error("Malformed block");
8090     case BitstreamEntry::EndBlock: {
8091       // If no flags record found, set both flags to false.
8092       return Result;
8093     }
8094     case BitstreamEntry::Record:
8095       // The interesting case.
8096       break;
8097     }
8098 
8099     // Look for the FS_FLAGS record.
8100     Record.clear();
8101     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
8102     if (!MaybeBitCode)
8103       return MaybeBitCode.takeError();
8104     switch (MaybeBitCode.get()) {
8105     default: // Default behavior: ignore.
8106       break;
8107     case bitc::FS_FLAGS: { // [flags]
8108       uint64_t Flags = Record[0];
8109       // Scan flags.
8110       assert(Flags <= 0x2ff && "Unexpected bits in flag");
8111 
8112       bool EnableSplitLTOUnit = Flags & 0x8;
8113       bool UnifiedLTO = Flags & 0x200;
8114       Result = {EnableSplitLTOUnit, UnifiedLTO};
8115 
8116       return Result;
8117     }
8118     }
8119   }
8120   llvm_unreachable("Exit infinite loop");
8121 }
8122 
8123 // Check if the given bitcode buffer contains a global value summary block.
8124 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
8125   BitstreamCursor Stream(Buffer);
8126   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8127     return std::move(JumpFailed);
8128 
8129   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
8130     return std::move(Err);
8131 
8132   while (true) {
8133     llvm::BitstreamEntry Entry;
8134     if (Error E = Stream.advance().moveInto(Entry))
8135       return std::move(E);
8136 
8137     switch (Entry.Kind) {
8138     case BitstreamEntry::Error:
8139       return error("Malformed block");
8140     case BitstreamEntry::EndBlock:
8141       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8142                             /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8143 
8144     case BitstreamEntry::SubBlock:
8145       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
8146         BitcodeLTOInfo LTOInfo;
8147         Expected<std::pair<bool, bool>> Flags =
8148             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8149         if (!Flags)
8150           return Flags.takeError();
8151         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8152         LTOInfo.IsThinLTO = true;
8153         LTOInfo.HasSummary = true;
8154         return LTOInfo;
8155       }
8156 
8157       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
8158         BitcodeLTOInfo LTOInfo;
8159         Expected<std::pair<bool, bool>> Flags =
8160             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8161         if (!Flags)
8162           return Flags.takeError();
8163         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8164         LTOInfo.IsThinLTO = false;
8165         LTOInfo.HasSummary = true;
8166         return LTOInfo;
8167       }
8168 
8169       // Ignore other sub-blocks.
8170       if (Error Err = Stream.SkipBlock())
8171         return std::move(Err);
8172       continue;
8173 
8174     case BitstreamEntry::Record:
8175       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
8176         continue;
8177       else
8178         return StreamFailed.takeError();
8179     }
8180   }
8181 }
8182 
8183 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
8184   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
8185   if (!MsOrErr)
8186     return MsOrErr.takeError();
8187 
8188   if (MsOrErr->size() != 1)
8189     return error("Expected a single module");
8190 
8191   return (*MsOrErr)[0];
8192 }
8193 
8194 Expected<std::unique_ptr<Module>>
8195 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8196                            bool ShouldLazyLoadMetadata, bool IsImporting,
8197                            ParserCallbacks Callbacks) {
8198   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8199   if (!BM)
8200     return BM.takeError();
8201 
8202   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8203                            Callbacks);
8204 }
8205 
8206 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
8207     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8208     bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8209   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8210                                      IsImporting, Callbacks);
8211   if (MOrErr)
8212     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8213   return MOrErr;
8214 }
8215 
8216 Expected<std::unique_ptr<Module>>
8217 BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8218   return getModuleImpl(Context, true, false, false, Callbacks);
8219   // TODO: Restore the use-lists to the in-memory state when the bitcode was
8220   // written.  We must defer until the Module has been fully materialized.
8221 }
8222 
8223 Expected<std::unique_ptr<Module>>
8224 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8225                        ParserCallbacks Callbacks) {
8226   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8227   if (!BM)
8228     return BM.takeError();
8229 
8230   return BM->parseModule(Context, Callbacks);
8231 }
8232 
8233 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
8234   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8235   if (!StreamOrErr)
8236     return StreamOrErr.takeError();
8237 
8238   return readTriple(*StreamOrErr);
8239 }
8240 
8241 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
8242   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8243   if (!StreamOrErr)
8244     return StreamOrErr.takeError();
8245 
8246   return hasObjCCategory(*StreamOrErr);
8247 }
8248 
8249 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
8250   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8251   if (!StreamOrErr)
8252     return StreamOrErr.takeError();
8253 
8254   return readIdentificationCode(*StreamOrErr);
8255 }
8256 
8257 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
8258                                    ModuleSummaryIndex &CombinedIndex) {
8259   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8260   if (!BM)
8261     return BM.takeError();
8262 
8263   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8264 }
8265 
8266 Expected<std::unique_ptr<ModuleSummaryIndex>>
8267 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
8268   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8269   if (!BM)
8270     return BM.takeError();
8271 
8272   return BM->getSummary();
8273 }
8274 
8275 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
8276   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8277   if (!BM)
8278     return BM.takeError();
8279 
8280   return BM->getLTOInfo();
8281 }
8282 
8283 Expected<std::unique_ptr<ModuleSummaryIndex>>
8284 llvm::getModuleSummaryIndexForFile(StringRef Path,
8285                                    bool IgnoreEmptyThinLTOIndexFile) {
8286   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
8287       MemoryBuffer::getFileOrSTDIN(Path);
8288   if (!FileOrErr)
8289     return errorCodeToError(FileOrErr.getError());
8290   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8291     return nullptr;
8292   return getModuleSummaryIndex(**FileOrErr);
8293 }
8294