xref: /llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision b68afd7b51769796cf920d7926bad3067c7092a1)
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   }
2102 }
2103 
2104 Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
2105                                          MaybeAlign &Alignment) {
2106   // Note: Alignment in bitcode files is incremented by 1, so that zero
2107   // can be used for default alignment.
2108   if (Exponent > Value::MaxAlignmentExponent + 1)
2109     return error("Invalid alignment value");
2110   Alignment = decodeMaybeAlign(Exponent);
2111   return Error::success();
2112 }
2113 
2114 Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
2115   *Kind = getAttrFromCode(Code);
2116   if (*Kind == Attribute::None)
2117     return error("Unknown attribute kind (" + Twine(Code) + ")");
2118   return Error::success();
2119 }
2120 
2121 static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
2122   switch (EncodedKind) {
2123   case bitc::ATTR_KIND_READ_NONE:
2124     ME &= MemoryEffects::none();
2125     return true;
2126   case bitc::ATTR_KIND_READ_ONLY:
2127     ME &= MemoryEffects::readOnly();
2128     return true;
2129   case bitc::ATTR_KIND_WRITEONLY:
2130     ME &= MemoryEffects::writeOnly();
2131     return true;
2132   case bitc::ATTR_KIND_ARGMEMONLY:
2133     ME &= MemoryEffects::argMemOnly();
2134     return true;
2135   case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
2136     ME &= MemoryEffects::inaccessibleMemOnly();
2137     return true;
2138   case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
2139     ME &= MemoryEffects::inaccessibleOrArgMemOnly();
2140     return true;
2141   default:
2142     return false;
2143   }
2144 }
2145 
2146 Error BitcodeReader::parseAttributeGroupBlock() {
2147   if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
2148     return Err;
2149 
2150   if (!MAttributeGroups.empty())
2151     return error("Invalid multiple blocks");
2152 
2153   SmallVector<uint64_t, 64> Record;
2154 
2155   // Read all the records.
2156   while (true) {
2157     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2158     if (!MaybeEntry)
2159       return MaybeEntry.takeError();
2160     BitstreamEntry Entry = MaybeEntry.get();
2161 
2162     switch (Entry.Kind) {
2163     case BitstreamEntry::SubBlock: // Handled for us already.
2164     case BitstreamEntry::Error:
2165       return error("Malformed block");
2166     case BitstreamEntry::EndBlock:
2167       return Error::success();
2168     case BitstreamEntry::Record:
2169       // The interesting case.
2170       break;
2171     }
2172 
2173     // Read a record.
2174     Record.clear();
2175     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2176     if (!MaybeRecord)
2177       return MaybeRecord.takeError();
2178     switch (MaybeRecord.get()) {
2179     default:  // Default behavior: ignore.
2180       break;
2181     case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
2182       if (Record.size() < 3)
2183         return error("Invalid grp record");
2184 
2185       uint64_t GrpID = Record[0];
2186       uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
2187 
2188       AttrBuilder B(Context);
2189       MemoryEffects ME = MemoryEffects::unknown();
2190       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2191         if (Record[i] == 0) {        // Enum attribute
2192           Attribute::AttrKind Kind;
2193           uint64_t EncodedKind = Record[++i];
2194           if (Idx == AttributeList::FunctionIndex &&
2195               upgradeOldMemoryAttribute(ME, EncodedKind))
2196             continue;
2197 
2198           if (Error Err = parseAttrKind(EncodedKind, &Kind))
2199             return Err;
2200 
2201           // Upgrade old-style byval attribute to one with a type, even if it's
2202           // nullptr. We will have to insert the real type when we associate
2203           // this AttributeList with a function.
2204           if (Kind == Attribute::ByVal)
2205             B.addByValAttr(nullptr);
2206           else if (Kind == Attribute::StructRet)
2207             B.addStructRetAttr(nullptr);
2208           else if (Kind == Attribute::InAlloca)
2209             B.addInAllocaAttr(nullptr);
2210           else if (Kind == Attribute::UWTable)
2211             B.addUWTableAttr(UWTableKind::Default);
2212           else if (Attribute::isEnumAttrKind(Kind))
2213             B.addAttribute(Kind);
2214           else
2215             return error("Not an enum attribute");
2216         } else if (Record[i] == 1) { // Integer attribute
2217           Attribute::AttrKind Kind;
2218           if (Error Err = parseAttrKind(Record[++i], &Kind))
2219             return Err;
2220           if (!Attribute::isIntAttrKind(Kind))
2221             return error("Not an int attribute");
2222           if (Kind == Attribute::Alignment)
2223             B.addAlignmentAttr(Record[++i]);
2224           else if (Kind == Attribute::StackAlignment)
2225             B.addStackAlignmentAttr(Record[++i]);
2226           else if (Kind == Attribute::Dereferenceable)
2227             B.addDereferenceableAttr(Record[++i]);
2228           else if (Kind == Attribute::DereferenceableOrNull)
2229             B.addDereferenceableOrNullAttr(Record[++i]);
2230           else if (Kind == Attribute::AllocSize)
2231             B.addAllocSizeAttrFromRawRepr(Record[++i]);
2232           else if (Kind == Attribute::VScaleRange)
2233             B.addVScaleRangeAttrFromRawRepr(Record[++i]);
2234           else if (Kind == Attribute::UWTable)
2235             B.addUWTableAttr(UWTableKind(Record[++i]));
2236           else if (Kind == Attribute::AllocKind)
2237             B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
2238           else if (Kind == Attribute::Memory)
2239             B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i]));
2240           else if (Kind == Attribute::NoFPClass)
2241             B.addNoFPClassAttr(
2242                 static_cast<FPClassTest>(Record[++i] & fcAllFlags));
2243         } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
2244           bool HasValue = (Record[i++] == 4);
2245           SmallString<64> KindStr;
2246           SmallString<64> ValStr;
2247 
2248           while (Record[i] != 0 && i != e)
2249             KindStr += Record[i++];
2250           assert(Record[i] == 0 && "Kind string not null terminated");
2251 
2252           if (HasValue) {
2253             // Has a value associated with it.
2254             ++i; // Skip the '0' that terminates the "kind" string.
2255             while (Record[i] != 0 && i != e)
2256               ValStr += Record[i++];
2257             assert(Record[i] == 0 && "Value string not null terminated");
2258           }
2259 
2260           B.addAttribute(KindStr.str(), ValStr.str());
2261         } else if (Record[i] == 5 || Record[i] == 6) {
2262           bool HasType = Record[i] == 6;
2263           Attribute::AttrKind Kind;
2264           if (Error Err = parseAttrKind(Record[++i], &Kind))
2265             return Err;
2266           if (!Attribute::isTypeAttrKind(Kind))
2267             return error("Not a type attribute");
2268 
2269           B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
2270         } else {
2271           return error("Invalid attribute group entry");
2272         }
2273       }
2274 
2275       if (ME != MemoryEffects::unknown())
2276         B.addMemoryAttr(ME);
2277 
2278       UpgradeAttributes(B);
2279       MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
2280       break;
2281     }
2282     }
2283   }
2284 }
2285 
2286 Error BitcodeReader::parseTypeTable() {
2287   if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
2288     return Err;
2289 
2290   return parseTypeTableBody();
2291 }
2292 
2293 Error BitcodeReader::parseTypeTableBody() {
2294   if (!TypeList.empty())
2295     return error("Invalid multiple blocks");
2296 
2297   SmallVector<uint64_t, 64> Record;
2298   unsigned NumRecords = 0;
2299 
2300   SmallString<64> TypeName;
2301 
2302   // Read all the records for this type table.
2303   while (true) {
2304     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2305     if (!MaybeEntry)
2306       return MaybeEntry.takeError();
2307     BitstreamEntry Entry = MaybeEntry.get();
2308 
2309     switch (Entry.Kind) {
2310     case BitstreamEntry::SubBlock: // Handled for us already.
2311     case BitstreamEntry::Error:
2312       return error("Malformed block");
2313     case BitstreamEntry::EndBlock:
2314       if (NumRecords != TypeList.size())
2315         return error("Malformed block");
2316       return Error::success();
2317     case BitstreamEntry::Record:
2318       // The interesting case.
2319       break;
2320     }
2321 
2322     // Read a record.
2323     Record.clear();
2324     Type *ResultTy = nullptr;
2325     SmallVector<unsigned> ContainedIDs;
2326     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2327     if (!MaybeRecord)
2328       return MaybeRecord.takeError();
2329     switch (MaybeRecord.get()) {
2330     default:
2331       return error("Invalid value");
2332     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
2333       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
2334       // type list.  This allows us to reserve space.
2335       if (Record.empty())
2336         return error("Invalid numentry record");
2337       TypeList.resize(Record[0]);
2338       continue;
2339     case bitc::TYPE_CODE_VOID:      // VOID
2340       ResultTy = Type::getVoidTy(Context);
2341       break;
2342     case bitc::TYPE_CODE_HALF:     // HALF
2343       ResultTy = Type::getHalfTy(Context);
2344       break;
2345     case bitc::TYPE_CODE_BFLOAT:    // BFLOAT
2346       ResultTy = Type::getBFloatTy(Context);
2347       break;
2348     case bitc::TYPE_CODE_FLOAT:     // FLOAT
2349       ResultTy = Type::getFloatTy(Context);
2350       break;
2351     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
2352       ResultTy = Type::getDoubleTy(Context);
2353       break;
2354     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
2355       ResultTy = Type::getX86_FP80Ty(Context);
2356       break;
2357     case bitc::TYPE_CODE_FP128:     // FP128
2358       ResultTy = Type::getFP128Ty(Context);
2359       break;
2360     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
2361       ResultTy = Type::getPPC_FP128Ty(Context);
2362       break;
2363     case bitc::TYPE_CODE_LABEL:     // LABEL
2364       ResultTy = Type::getLabelTy(Context);
2365       break;
2366     case bitc::TYPE_CODE_METADATA:  // METADATA
2367       ResultTy = Type::getMetadataTy(Context);
2368       break;
2369     case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
2370       ResultTy = Type::getX86_MMXTy(Context);
2371       break;
2372     case bitc::TYPE_CODE_X86_AMX:   // X86_AMX
2373       ResultTy = Type::getX86_AMXTy(Context);
2374       break;
2375     case bitc::TYPE_CODE_TOKEN:     // TOKEN
2376       ResultTy = Type::getTokenTy(Context);
2377       break;
2378     case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
2379       if (Record.empty())
2380         return error("Invalid integer record");
2381 
2382       uint64_t NumBits = Record[0];
2383       if (NumBits < IntegerType::MIN_INT_BITS ||
2384           NumBits > IntegerType::MAX_INT_BITS)
2385         return error("Bitwidth for integer type out of range");
2386       ResultTy = IntegerType::get(Context, NumBits);
2387       break;
2388     }
2389     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
2390                                     //          [pointee type, address space]
2391       if (Record.empty())
2392         return error("Invalid pointer record");
2393       unsigned AddressSpace = 0;
2394       if (Record.size() == 2)
2395         AddressSpace = Record[1];
2396       ResultTy = getTypeByID(Record[0]);
2397       if (!ResultTy ||
2398           !PointerType::isValidElementType(ResultTy))
2399         return error("Invalid type");
2400       ContainedIDs.push_back(Record[0]);
2401       ResultTy = PointerType::get(ResultTy, AddressSpace);
2402       break;
2403     }
2404     case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
2405       if (Record.size() != 1)
2406         return error("Invalid opaque pointer record");
2407       unsigned AddressSpace = Record[0];
2408       ResultTy = PointerType::get(Context, AddressSpace);
2409       break;
2410     }
2411     case bitc::TYPE_CODE_FUNCTION_OLD: {
2412       // Deprecated, but still needed to read old bitcode files.
2413       // FUNCTION: [vararg, attrid, retty, paramty x N]
2414       if (Record.size() < 3)
2415         return error("Invalid function record");
2416       SmallVector<Type*, 8> ArgTys;
2417       for (unsigned i = 3, e = Record.size(); i != e; ++i) {
2418         if (Type *T = getTypeByID(Record[i]))
2419           ArgTys.push_back(T);
2420         else
2421           break;
2422       }
2423 
2424       ResultTy = getTypeByID(Record[2]);
2425       if (!ResultTy || ArgTys.size() < Record.size()-3)
2426         return error("Invalid type");
2427 
2428       ContainedIDs.append(Record.begin() + 2, Record.end());
2429       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2430       break;
2431     }
2432     case bitc::TYPE_CODE_FUNCTION: {
2433       // FUNCTION: [vararg, retty, paramty x N]
2434       if (Record.size() < 2)
2435         return error("Invalid function record");
2436       SmallVector<Type*, 8> ArgTys;
2437       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
2438         if (Type *T = getTypeByID(Record[i])) {
2439           if (!FunctionType::isValidArgumentType(T))
2440             return error("Invalid function argument type");
2441           ArgTys.push_back(T);
2442         }
2443         else
2444           break;
2445       }
2446 
2447       ResultTy = getTypeByID(Record[1]);
2448       if (!ResultTy || ArgTys.size() < Record.size()-2)
2449         return error("Invalid type");
2450 
2451       ContainedIDs.append(Record.begin() + 1, Record.end());
2452       ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
2453       break;
2454     }
2455     case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
2456       if (Record.empty())
2457         return error("Invalid anon struct record");
2458       SmallVector<Type*, 8> EltTys;
2459       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2460         if (Type *T = getTypeByID(Record[i]))
2461           EltTys.push_back(T);
2462         else
2463           break;
2464       }
2465       if (EltTys.size() != Record.size()-1)
2466         return error("Invalid type");
2467       ContainedIDs.append(Record.begin() + 1, Record.end());
2468       ResultTy = StructType::get(Context, EltTys, Record[0]);
2469       break;
2470     }
2471     case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
2472       if (convertToString(Record, 0, TypeName))
2473         return error("Invalid struct name record");
2474       continue;
2475 
2476     case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
2477       if (Record.empty())
2478         return error("Invalid named struct record");
2479 
2480       if (NumRecords >= TypeList.size())
2481         return error("Invalid TYPE table");
2482 
2483       // Check to see if this was forward referenced, if so fill in the temp.
2484       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2485       if (Res) {
2486         Res->setName(TypeName);
2487         TypeList[NumRecords] = nullptr;
2488       } else  // Otherwise, create a new struct.
2489         Res = createIdentifiedStructType(Context, TypeName);
2490       TypeName.clear();
2491 
2492       SmallVector<Type*, 8> EltTys;
2493       for (unsigned i = 1, e = Record.size(); i != e; ++i) {
2494         if (Type *T = getTypeByID(Record[i]))
2495           EltTys.push_back(T);
2496         else
2497           break;
2498       }
2499       if (EltTys.size() != Record.size()-1)
2500         return error("Invalid named struct record");
2501       Res->setBody(EltTys, Record[0]);
2502       ContainedIDs.append(Record.begin() + 1, Record.end());
2503       ResultTy = Res;
2504       break;
2505     }
2506     case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
2507       if (Record.size() != 1)
2508         return error("Invalid opaque type record");
2509 
2510       if (NumRecords >= TypeList.size())
2511         return error("Invalid TYPE table");
2512 
2513       // Check to see if this was forward referenced, if so fill in the temp.
2514       StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
2515       if (Res) {
2516         Res->setName(TypeName);
2517         TypeList[NumRecords] = nullptr;
2518       } else  // Otherwise, create a new struct with no body.
2519         Res = createIdentifiedStructType(Context, TypeName);
2520       TypeName.clear();
2521       ResultTy = Res;
2522       break;
2523     }
2524     case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
2525       if (Record.size() < 1)
2526         return error("Invalid target extension type record");
2527 
2528       if (NumRecords >= TypeList.size())
2529         return error("Invalid TYPE table");
2530 
2531       if (Record[0] >= Record.size())
2532         return error("Too many type parameters");
2533 
2534       unsigned NumTys = Record[0];
2535       SmallVector<Type *, 4> TypeParams;
2536       SmallVector<unsigned, 8> IntParams;
2537       for (unsigned i = 0; i < NumTys; i++) {
2538         if (Type *T = getTypeByID(Record[i + 1]))
2539           TypeParams.push_back(T);
2540         else
2541           return error("Invalid type");
2542       }
2543 
2544       for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
2545         if (Record[i] > UINT_MAX)
2546           return error("Integer parameter too large");
2547         IntParams.push_back(Record[i]);
2548       }
2549       ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
2550       TypeName.clear();
2551       break;
2552     }
2553     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
2554       if (Record.size() < 2)
2555         return error("Invalid array type record");
2556       ResultTy = getTypeByID(Record[1]);
2557       if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
2558         return error("Invalid type");
2559       ContainedIDs.push_back(Record[1]);
2560       ResultTy = ArrayType::get(ResultTy, Record[0]);
2561       break;
2562     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty] or
2563                                     //         [numelts, eltty, scalable]
2564       if (Record.size() < 2)
2565         return error("Invalid vector type record");
2566       if (Record[0] == 0)
2567         return error("Invalid vector length");
2568       ResultTy = getTypeByID(Record[1]);
2569       if (!ResultTy || !VectorType::isValidElementType(ResultTy))
2570         return error("Invalid type");
2571       bool Scalable = Record.size() > 2 ? Record[2] : false;
2572       ContainedIDs.push_back(Record[1]);
2573       ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
2574       break;
2575     }
2576 
2577     if (NumRecords >= TypeList.size())
2578       return error("Invalid TYPE table");
2579     if (TypeList[NumRecords])
2580       return error(
2581           "Invalid TYPE table: Only named structs can be forward referenced");
2582     assert(ResultTy && "Didn't read a type?");
2583     TypeList[NumRecords] = ResultTy;
2584     if (!ContainedIDs.empty())
2585       ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
2586     ++NumRecords;
2587   }
2588 }
2589 
2590 Error BitcodeReader::parseOperandBundleTags() {
2591   if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
2592     return Err;
2593 
2594   if (!BundleTags.empty())
2595     return error("Invalid multiple blocks");
2596 
2597   SmallVector<uint64_t, 64> Record;
2598 
2599   while (true) {
2600     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2601     if (!MaybeEntry)
2602       return MaybeEntry.takeError();
2603     BitstreamEntry Entry = MaybeEntry.get();
2604 
2605     switch (Entry.Kind) {
2606     case BitstreamEntry::SubBlock: // Handled for us already.
2607     case BitstreamEntry::Error:
2608       return error("Malformed block");
2609     case BitstreamEntry::EndBlock:
2610       return Error::success();
2611     case BitstreamEntry::Record:
2612       // The interesting case.
2613       break;
2614     }
2615 
2616     // Tags are implicitly mapped to integers by their order.
2617 
2618     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2619     if (!MaybeRecord)
2620       return MaybeRecord.takeError();
2621     if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
2622       return error("Invalid operand bundle record");
2623 
2624     // OPERAND_BUNDLE_TAG: [strchr x N]
2625     BundleTags.emplace_back();
2626     if (convertToString(Record, 0, BundleTags.back()))
2627       return error("Invalid operand bundle record");
2628     Record.clear();
2629   }
2630 }
2631 
2632 Error BitcodeReader::parseSyncScopeNames() {
2633   if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
2634     return Err;
2635 
2636   if (!SSIDs.empty())
2637     return error("Invalid multiple synchronization scope names blocks");
2638 
2639   SmallVector<uint64_t, 64> Record;
2640   while (true) {
2641     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2642     if (!MaybeEntry)
2643       return MaybeEntry.takeError();
2644     BitstreamEntry Entry = MaybeEntry.get();
2645 
2646     switch (Entry.Kind) {
2647     case BitstreamEntry::SubBlock: // Handled for us already.
2648     case BitstreamEntry::Error:
2649       return error("Malformed block");
2650     case BitstreamEntry::EndBlock:
2651       if (SSIDs.empty())
2652         return error("Invalid empty synchronization scope names block");
2653       return Error::success();
2654     case BitstreamEntry::Record:
2655       // The interesting case.
2656       break;
2657     }
2658 
2659     // Synchronization scope names are implicitly mapped to synchronization
2660     // scope IDs by their order.
2661 
2662     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2663     if (!MaybeRecord)
2664       return MaybeRecord.takeError();
2665     if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
2666       return error("Invalid sync scope record");
2667 
2668     SmallString<16> SSN;
2669     if (convertToString(Record, 0, SSN))
2670       return error("Invalid sync scope record");
2671 
2672     SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
2673     Record.clear();
2674   }
2675 }
2676 
2677 /// Associate a value with its name from the given index in the provided record.
2678 Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
2679                                              unsigned NameIndex, Triple &TT) {
2680   SmallString<128> ValueName;
2681   if (convertToString(Record, NameIndex, ValueName))
2682     return error("Invalid record");
2683   unsigned ValueID = Record[0];
2684   if (ValueID >= ValueList.size() || !ValueList[ValueID])
2685     return error("Invalid record");
2686   Value *V = ValueList[ValueID];
2687 
2688   StringRef NameStr(ValueName.data(), ValueName.size());
2689   if (NameStr.contains(0))
2690     return error("Invalid value name");
2691   V->setName(NameStr);
2692   auto *GO = dyn_cast<GlobalObject>(V);
2693   if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
2694     GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
2695   return V;
2696 }
2697 
2698 /// Helper to note and return the current location, and jump to the given
2699 /// offset.
2700 static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
2701                                                  BitstreamCursor &Stream) {
2702   // Save the current parsing location so we can jump back at the end
2703   // of the VST read.
2704   uint64_t CurrentBit = Stream.GetCurrentBitNo();
2705   if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
2706     return std::move(JumpFailed);
2707   Expected<BitstreamEntry> MaybeEntry = Stream.advance();
2708   if (!MaybeEntry)
2709     return MaybeEntry.takeError();
2710   if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
2711       MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
2712     return error("Expected value symbol table subblock");
2713   return CurrentBit;
2714 }
2715 
2716 void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
2717                                             Function *F,
2718                                             ArrayRef<uint64_t> Record) {
2719   // Note that we subtract 1 here because the offset is relative to one word
2720   // before the start of the identification or module block, which was
2721   // historically always the start of the regular bitcode header.
2722   uint64_t FuncWordOffset = Record[1] - 1;
2723   uint64_t FuncBitOffset = FuncWordOffset * 32;
2724   DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
2725   // Set the LastFunctionBlockBit to point to the last function block.
2726   // Later when parsing is resumed after function materialization,
2727   // we can simply skip that last function block.
2728   if (FuncBitOffset > LastFunctionBlockBit)
2729     LastFunctionBlockBit = FuncBitOffset;
2730 }
2731 
2732 /// Read a new-style GlobalValue symbol table.
2733 Error BitcodeReader::parseGlobalValueSymbolTable() {
2734   unsigned FuncBitcodeOffsetDelta =
2735       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2736 
2737   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2738     return Err;
2739 
2740   SmallVector<uint64_t, 64> Record;
2741   while (true) {
2742     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2743     if (!MaybeEntry)
2744       return MaybeEntry.takeError();
2745     BitstreamEntry Entry = MaybeEntry.get();
2746 
2747     switch (Entry.Kind) {
2748     case BitstreamEntry::SubBlock:
2749     case BitstreamEntry::Error:
2750       return error("Malformed block");
2751     case BitstreamEntry::EndBlock:
2752       return Error::success();
2753     case BitstreamEntry::Record:
2754       break;
2755     }
2756 
2757     Record.clear();
2758     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2759     if (!MaybeRecord)
2760       return MaybeRecord.takeError();
2761     switch (MaybeRecord.get()) {
2762     case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
2763       unsigned ValueID = Record[0];
2764       if (ValueID >= ValueList.size() || !ValueList[ValueID])
2765         return error("Invalid value reference in symbol table");
2766       setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
2767                               cast<Function>(ValueList[ValueID]), Record);
2768       break;
2769     }
2770     }
2771   }
2772 }
2773 
2774 /// Parse the value symbol table at either the current parsing location or
2775 /// at the given bit offset if provided.
2776 Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
2777   uint64_t CurrentBit;
2778   // Pass in the Offset to distinguish between calling for the module-level
2779   // VST (where we want to jump to the VST offset) and the function-level
2780   // VST (where we don't).
2781   if (Offset > 0) {
2782     Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
2783     if (!MaybeCurrentBit)
2784       return MaybeCurrentBit.takeError();
2785     CurrentBit = MaybeCurrentBit.get();
2786     // If this module uses a string table, read this as a module-level VST.
2787     if (UseStrtab) {
2788       if (Error Err = parseGlobalValueSymbolTable())
2789         return Err;
2790       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2791         return JumpFailed;
2792       return Error::success();
2793     }
2794     // Otherwise, the VST will be in a similar format to a function-level VST,
2795     // and will contain symbol names.
2796   }
2797 
2798   // Compute the delta between the bitcode indices in the VST (the word offset
2799   // to the word-aligned ENTER_SUBBLOCK for the function block, and that
2800   // expected by the lazy reader. The reader's EnterSubBlock expects to have
2801   // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
2802   // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
2803   // just before entering the VST subblock because: 1) the EnterSubBlock
2804   // changes the AbbrevID width; 2) the VST block is nested within the same
2805   // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
2806   // AbbrevID width before calling EnterSubBlock; and 3) when we want to
2807   // jump to the FUNCTION_BLOCK using this offset later, we don't want
2808   // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
2809   unsigned FuncBitcodeOffsetDelta =
2810       Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
2811 
2812   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
2813     return Err;
2814 
2815   SmallVector<uint64_t, 64> Record;
2816 
2817   Triple TT(TheModule->getTargetTriple());
2818 
2819   // Read all the records for this value table.
2820   SmallString<128> ValueName;
2821 
2822   while (true) {
2823     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
2824     if (!MaybeEntry)
2825       return MaybeEntry.takeError();
2826     BitstreamEntry Entry = MaybeEntry.get();
2827 
2828     switch (Entry.Kind) {
2829     case BitstreamEntry::SubBlock: // Handled for us already.
2830     case BitstreamEntry::Error:
2831       return error("Malformed block");
2832     case BitstreamEntry::EndBlock:
2833       if (Offset > 0)
2834         if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
2835           return JumpFailed;
2836       return Error::success();
2837     case BitstreamEntry::Record:
2838       // The interesting case.
2839       break;
2840     }
2841 
2842     // Read a record.
2843     Record.clear();
2844     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
2845     if (!MaybeRecord)
2846       return MaybeRecord.takeError();
2847     switch (MaybeRecord.get()) {
2848     default:  // Default behavior: unknown type.
2849       break;
2850     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
2851       Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
2852       if (Error Err = ValOrErr.takeError())
2853         return Err;
2854       ValOrErr.get();
2855       break;
2856     }
2857     case bitc::VST_CODE_FNENTRY: {
2858       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
2859       Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
2860       if (Error Err = ValOrErr.takeError())
2861         return Err;
2862       Value *V = ValOrErr.get();
2863 
2864       // Ignore function offsets emitted for aliases of functions in older
2865       // versions of LLVM.
2866       if (auto *F = dyn_cast<Function>(V))
2867         setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
2868       break;
2869     }
2870     case bitc::VST_CODE_BBENTRY: {
2871       if (convertToString(Record, 1, ValueName))
2872         return error("Invalid bbentry record");
2873       BasicBlock *BB = getBasicBlock(Record[0]);
2874       if (!BB)
2875         return error("Invalid bbentry record");
2876 
2877       BB->setName(StringRef(ValueName.data(), ValueName.size()));
2878       ValueName.clear();
2879       break;
2880     }
2881     }
2882   }
2883 }
2884 
2885 /// Decode a signed value stored with the sign bit in the LSB for dense VBR
2886 /// encoding.
2887 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
2888   if ((V & 1) == 0)
2889     return V >> 1;
2890   if (V != 1)
2891     return -(V >> 1);
2892   // There is no such thing as -0 with integers.  "-0" really means MININT.
2893   return 1ULL << 63;
2894 }
2895 
2896 /// Resolve all of the initializers for global values and aliases that we can.
2897 Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
2898   std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
2899   std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
2900   std::vector<FunctionOperandInfo> FunctionOperandWorklist;
2901 
2902   GlobalInitWorklist.swap(GlobalInits);
2903   IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
2904   FunctionOperandWorklist.swap(FunctionOperands);
2905 
2906   while (!GlobalInitWorklist.empty()) {
2907     unsigned ValID = GlobalInitWorklist.back().second;
2908     if (ValID >= ValueList.size()) {
2909       // Not ready to resolve this yet, it requires something later in the file.
2910       GlobalInits.push_back(GlobalInitWorklist.back());
2911     } else {
2912       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2913       if (!MaybeC)
2914         return MaybeC.takeError();
2915       GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
2916     }
2917     GlobalInitWorklist.pop_back();
2918   }
2919 
2920   while (!IndirectSymbolInitWorklist.empty()) {
2921     unsigned ValID = IndirectSymbolInitWorklist.back().second;
2922     if (ValID >= ValueList.size()) {
2923       IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
2924     } else {
2925       Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2926       if (!MaybeC)
2927         return MaybeC.takeError();
2928       Constant *C = MaybeC.get();
2929       GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
2930       if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
2931         if (C->getType() != GV->getType())
2932           return error("Alias and aliasee types don't match");
2933         GA->setAliasee(C);
2934       } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
2935         GI->setResolver(C);
2936       } else {
2937         return error("Expected an alias or an ifunc");
2938       }
2939     }
2940     IndirectSymbolInitWorklist.pop_back();
2941   }
2942 
2943   while (!FunctionOperandWorklist.empty()) {
2944     FunctionOperandInfo &Info = FunctionOperandWorklist.back();
2945     if (Info.PersonalityFn) {
2946       unsigned ValID = Info.PersonalityFn - 1;
2947       if (ValID < ValueList.size()) {
2948         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2949         if (!MaybeC)
2950           return MaybeC.takeError();
2951         Info.F->setPersonalityFn(MaybeC.get());
2952         Info.PersonalityFn = 0;
2953       }
2954     }
2955     if (Info.Prefix) {
2956       unsigned ValID = Info.Prefix - 1;
2957       if (ValID < ValueList.size()) {
2958         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2959         if (!MaybeC)
2960           return MaybeC.takeError();
2961         Info.F->setPrefixData(MaybeC.get());
2962         Info.Prefix = 0;
2963       }
2964     }
2965     if (Info.Prologue) {
2966       unsigned ValID = Info.Prologue - 1;
2967       if (ValID < ValueList.size()) {
2968         Expected<Constant *> MaybeC = getValueForInitializer(ValID);
2969         if (!MaybeC)
2970           return MaybeC.takeError();
2971         Info.F->setPrologueData(MaybeC.get());
2972         Info.Prologue = 0;
2973       }
2974     }
2975     if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
2976       FunctionOperands.push_back(Info);
2977     FunctionOperandWorklist.pop_back();
2978   }
2979 
2980   return Error::success();
2981 }
2982 
2983 APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
2984   SmallVector<uint64_t, 8> Words(Vals.size());
2985   transform(Vals, Words.begin(),
2986                  BitcodeReader::decodeSignRotatedValue);
2987 
2988   return APInt(TypeBits, Words);
2989 }
2990 
2991 Error BitcodeReader::parseConstants() {
2992   if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
2993     return Err;
2994 
2995   SmallVector<uint64_t, 64> Record;
2996 
2997   // Read all the records for this value table.
2998   Type *CurTy = Type::getInt32Ty(Context);
2999   unsigned Int32TyID = getVirtualTypeID(CurTy);
3000   unsigned CurTyID = Int32TyID;
3001   Type *CurElemTy = nullptr;
3002   unsigned NextCstNo = ValueList.size();
3003 
3004   while (true) {
3005     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3006     if (!MaybeEntry)
3007       return MaybeEntry.takeError();
3008     BitstreamEntry Entry = MaybeEntry.get();
3009 
3010     switch (Entry.Kind) {
3011     case BitstreamEntry::SubBlock: // Handled for us already.
3012     case BitstreamEntry::Error:
3013       return error("Malformed block");
3014     case BitstreamEntry::EndBlock:
3015       if (NextCstNo != ValueList.size())
3016         return error("Invalid constant reference");
3017       return Error::success();
3018     case BitstreamEntry::Record:
3019       // The interesting case.
3020       break;
3021     }
3022 
3023     // Read a record.
3024     Record.clear();
3025     Type *VoidType = Type::getVoidTy(Context);
3026     Value *V = nullptr;
3027     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
3028     if (!MaybeBitCode)
3029       return MaybeBitCode.takeError();
3030     switch (unsigned BitCode = MaybeBitCode.get()) {
3031     default:  // Default behavior: unknown constant
3032     case bitc::CST_CODE_UNDEF:     // UNDEF
3033       V = UndefValue::get(CurTy);
3034       break;
3035     case bitc::CST_CODE_POISON:    // POISON
3036       V = PoisonValue::get(CurTy);
3037       break;
3038     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
3039       if (Record.empty())
3040         return error("Invalid settype record");
3041       if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
3042         return error("Invalid settype record");
3043       if (TypeList[Record[0]] == VoidType)
3044         return error("Invalid constant type");
3045       CurTyID = Record[0];
3046       CurTy = TypeList[CurTyID];
3047       CurElemTy = getPtrElementTypeByID(CurTyID);
3048       continue;  // Skip the ValueList manipulation.
3049     case bitc::CST_CODE_NULL:      // NULL
3050       if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
3051         return error("Invalid type for a constant null value");
3052       if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
3053         if (!TETy->hasProperty(TargetExtType::HasZeroInit))
3054           return error("Invalid type for a constant null value");
3055       V = Constant::getNullValue(CurTy);
3056       break;
3057     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
3058       if (!CurTy->isIntegerTy() || Record.empty())
3059         return error("Invalid integer const record");
3060       V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
3061       break;
3062     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
3063       if (!CurTy->isIntegerTy() || Record.empty())
3064         return error("Invalid wide integer const record");
3065 
3066       APInt VInt =
3067           readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
3068       V = ConstantInt::get(Context, VInt);
3069 
3070       break;
3071     }
3072     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
3073       if (Record.empty())
3074         return error("Invalid float const record");
3075       if (CurTy->isHalfTy())
3076         V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
3077                                              APInt(16, (uint16_t)Record[0])));
3078       else if (CurTy->isBFloatTy())
3079         V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
3080                                              APInt(16, (uint32_t)Record[0])));
3081       else if (CurTy->isFloatTy())
3082         V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
3083                                              APInt(32, (uint32_t)Record[0])));
3084       else if (CurTy->isDoubleTy())
3085         V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
3086                                              APInt(64, Record[0])));
3087       else if (CurTy->isX86_FP80Ty()) {
3088         // Bits are not stored the same way as a normal i80 APInt, compensate.
3089         uint64_t Rearrange[2];
3090         Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
3091         Rearrange[1] = Record[0] >> 48;
3092         V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
3093                                              APInt(80, Rearrange)));
3094       } else if (CurTy->isFP128Ty())
3095         V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
3096                                              APInt(128, Record)));
3097       else if (CurTy->isPPC_FP128Ty())
3098         V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
3099                                              APInt(128, Record)));
3100       else
3101         V = UndefValue::get(CurTy);
3102       break;
3103     }
3104 
3105     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
3106       if (Record.empty())
3107         return error("Invalid aggregate record");
3108 
3109       unsigned Size = Record.size();
3110       SmallVector<unsigned, 16> Elts;
3111       for (unsigned i = 0; i != Size; ++i)
3112         Elts.push_back(Record[i]);
3113 
3114       if (isa<StructType>(CurTy)) {
3115         V = BitcodeConstant::create(
3116             Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
3117       } else if (isa<ArrayType>(CurTy)) {
3118         V = BitcodeConstant::create(Alloc, CurTy,
3119                                     BitcodeConstant::ConstantArrayOpcode, Elts);
3120       } else if (isa<VectorType>(CurTy)) {
3121         V = BitcodeConstant::create(
3122             Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
3123       } else {
3124         V = UndefValue::get(CurTy);
3125       }
3126       break;
3127     }
3128     case bitc::CST_CODE_STRING:    // STRING: [values]
3129     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
3130       if (Record.empty())
3131         return error("Invalid string record");
3132 
3133       SmallString<16> Elts(Record.begin(), Record.end());
3134       V = ConstantDataArray::getString(Context, Elts,
3135                                        BitCode == bitc::CST_CODE_CSTRING);
3136       break;
3137     }
3138     case bitc::CST_CODE_DATA: {// DATA: [n x value]
3139       if (Record.empty())
3140         return error("Invalid data record");
3141 
3142       Type *EltTy;
3143       if (auto *Array = dyn_cast<ArrayType>(CurTy))
3144         EltTy = Array->getElementType();
3145       else
3146         EltTy = cast<VectorType>(CurTy)->getElementType();
3147       if (EltTy->isIntegerTy(8)) {
3148         SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
3149         if (isa<VectorType>(CurTy))
3150           V = ConstantDataVector::get(Context, Elts);
3151         else
3152           V = ConstantDataArray::get(Context, Elts);
3153       } else if (EltTy->isIntegerTy(16)) {
3154         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3155         if (isa<VectorType>(CurTy))
3156           V = ConstantDataVector::get(Context, Elts);
3157         else
3158           V = ConstantDataArray::get(Context, Elts);
3159       } else if (EltTy->isIntegerTy(32)) {
3160         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3161         if (isa<VectorType>(CurTy))
3162           V = ConstantDataVector::get(Context, Elts);
3163         else
3164           V = ConstantDataArray::get(Context, Elts);
3165       } else if (EltTy->isIntegerTy(64)) {
3166         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3167         if (isa<VectorType>(CurTy))
3168           V = ConstantDataVector::get(Context, Elts);
3169         else
3170           V = ConstantDataArray::get(Context, Elts);
3171       } else if (EltTy->isHalfTy()) {
3172         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3173         if (isa<VectorType>(CurTy))
3174           V = ConstantDataVector::getFP(EltTy, Elts);
3175         else
3176           V = ConstantDataArray::getFP(EltTy, Elts);
3177       } else if (EltTy->isBFloatTy()) {
3178         SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
3179         if (isa<VectorType>(CurTy))
3180           V = ConstantDataVector::getFP(EltTy, Elts);
3181         else
3182           V = ConstantDataArray::getFP(EltTy, Elts);
3183       } else if (EltTy->isFloatTy()) {
3184         SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
3185         if (isa<VectorType>(CurTy))
3186           V = ConstantDataVector::getFP(EltTy, Elts);
3187         else
3188           V = ConstantDataArray::getFP(EltTy, Elts);
3189       } else if (EltTy->isDoubleTy()) {
3190         SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
3191         if (isa<VectorType>(CurTy))
3192           V = ConstantDataVector::getFP(EltTy, Elts);
3193         else
3194           V = ConstantDataArray::getFP(EltTy, Elts);
3195       } else {
3196         return error("Invalid type for value");
3197       }
3198       break;
3199     }
3200     case bitc::CST_CODE_CE_UNOP: {  // CE_UNOP: [opcode, opval]
3201       if (Record.size() < 2)
3202         return error("Invalid unary op constexpr record");
3203       int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
3204       if (Opc < 0) {
3205         V = UndefValue::get(CurTy);  // Unknown unop.
3206       } else {
3207         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
3208       }
3209       break;
3210     }
3211     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
3212       if (Record.size() < 3)
3213         return error("Invalid binary op constexpr record");
3214       int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
3215       if (Opc < 0) {
3216         V = UndefValue::get(CurTy);  // Unknown binop.
3217       } else {
3218         uint8_t Flags = 0;
3219         if (Record.size() >= 4) {
3220           if (Opc == Instruction::Add ||
3221               Opc == Instruction::Sub ||
3222               Opc == Instruction::Mul ||
3223               Opc == Instruction::Shl) {
3224             if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
3225               Flags |= OverflowingBinaryOperator::NoSignedWrap;
3226             if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
3227               Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
3228           } else if (Opc == Instruction::SDiv ||
3229                      Opc == Instruction::UDiv ||
3230                      Opc == Instruction::LShr ||
3231                      Opc == Instruction::AShr) {
3232             if (Record[3] & (1 << bitc::PEO_EXACT))
3233               Flags |= PossiblyExactOperator::IsExact;
3234           }
3235         }
3236         V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
3237                                     {(unsigned)Record[1], (unsigned)Record[2]});
3238       }
3239       break;
3240     }
3241     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
3242       if (Record.size() < 3)
3243         return error("Invalid cast constexpr record");
3244       int Opc = getDecodedCastOpcode(Record[0]);
3245       if (Opc < 0) {
3246         V = UndefValue::get(CurTy);  // Unknown cast.
3247       } else {
3248         unsigned OpTyID = Record[1];
3249         Type *OpTy = getTypeByID(OpTyID);
3250         if (!OpTy)
3251           return error("Invalid cast constexpr record");
3252         V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
3253       }
3254       break;
3255     }
3256     case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
3257     case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
3258     case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
3259                                                      // operands]
3260       if (Record.size() < 2)
3261         return error("Constant GEP record must have at least two elements");
3262       unsigned OpNum = 0;
3263       Type *PointeeType = nullptr;
3264       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
3265           Record.size() % 2)
3266         PointeeType = getTypeByID(Record[OpNum++]);
3267 
3268       bool InBounds = false;
3269       std::optional<unsigned> InRangeIndex;
3270       if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
3271         uint64_t Op = Record[OpNum++];
3272         InBounds = Op & 1;
3273         InRangeIndex = Op >> 1;
3274       } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
3275         InBounds = true;
3276 
3277       SmallVector<unsigned, 16> Elts;
3278       unsigned BaseTypeID = Record[OpNum];
3279       while (OpNum != Record.size()) {
3280         unsigned ElTyID = Record[OpNum++];
3281         Type *ElTy = getTypeByID(ElTyID);
3282         if (!ElTy)
3283           return error("Invalid getelementptr constexpr record");
3284         Elts.push_back(Record[OpNum++]);
3285       }
3286 
3287       if (Elts.size() < 1)
3288         return error("Invalid gep with no operands");
3289 
3290       Type *BaseType = getTypeByID(BaseTypeID);
3291       if (isa<VectorType>(BaseType)) {
3292         BaseTypeID = getContainedTypeID(BaseTypeID, 0);
3293         BaseType = getTypeByID(BaseTypeID);
3294       }
3295 
3296       PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
3297       if (!OrigPtrTy)
3298         return error("GEP base operand must be pointer or vector of pointer");
3299 
3300       if (!PointeeType) {
3301         PointeeType = getPtrElementTypeByID(BaseTypeID);
3302         if (!PointeeType)
3303           return error("Missing element type for old-style constant GEP");
3304       }
3305 
3306       V = BitcodeConstant::create(Alloc, CurTy,
3307                                   {Instruction::GetElementPtr, InBounds,
3308                                    InRangeIndex.value_or(-1), PointeeType},
3309                                   Elts);
3310       break;
3311     }
3312     case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
3313       if (Record.size() < 3)
3314         return error("Invalid select constexpr record");
3315 
3316       V = BitcodeConstant::create(
3317           Alloc, CurTy, Instruction::Select,
3318           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3319       break;
3320     }
3321     case bitc::CST_CODE_CE_EXTRACTELT
3322         : { // CE_EXTRACTELT: [opty, opval, opty, opval]
3323       if (Record.size() < 3)
3324         return error("Invalid extractelement constexpr record");
3325       unsigned OpTyID = Record[0];
3326       VectorType *OpTy =
3327         dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
3328       if (!OpTy)
3329         return error("Invalid extractelement constexpr record");
3330       unsigned IdxRecord;
3331       if (Record.size() == 4) {
3332         unsigned IdxTyID = Record[2];
3333         Type *IdxTy = getTypeByID(IdxTyID);
3334         if (!IdxTy)
3335           return error("Invalid extractelement constexpr record");
3336         IdxRecord = Record[3];
3337       } else {
3338         // Deprecated, but still needed to read old bitcode files.
3339         IdxRecord = Record[2];
3340       }
3341       V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
3342                                   {(unsigned)Record[1], IdxRecord});
3343       break;
3344     }
3345     case bitc::CST_CODE_CE_INSERTELT
3346         : { // CE_INSERTELT: [opval, opval, opty, opval]
3347       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3348       if (Record.size() < 3 || !OpTy)
3349         return error("Invalid insertelement constexpr record");
3350       unsigned IdxRecord;
3351       if (Record.size() == 4) {
3352         unsigned IdxTyID = Record[2];
3353         Type *IdxTy = getTypeByID(IdxTyID);
3354         if (!IdxTy)
3355           return error("Invalid insertelement constexpr record");
3356         IdxRecord = Record[3];
3357       } else {
3358         // Deprecated, but still needed to read old bitcode files.
3359         IdxRecord = Record[2];
3360       }
3361       V = BitcodeConstant::create(
3362           Alloc, CurTy, Instruction::InsertElement,
3363           {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
3364       break;
3365     }
3366     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
3367       VectorType *OpTy = dyn_cast<VectorType>(CurTy);
3368       if (Record.size() < 3 || !OpTy)
3369         return error("Invalid shufflevector constexpr record");
3370       V = BitcodeConstant::create(
3371           Alloc, CurTy, Instruction::ShuffleVector,
3372           {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
3373       break;
3374     }
3375     case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
3376       VectorType *RTy = dyn_cast<VectorType>(CurTy);
3377       VectorType *OpTy =
3378         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
3379       if (Record.size() < 4 || !RTy || !OpTy)
3380         return error("Invalid shufflevector constexpr record");
3381       V = BitcodeConstant::create(
3382           Alloc, CurTy, Instruction::ShuffleVector,
3383           {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
3384       break;
3385     }
3386     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
3387       if (Record.size() < 4)
3388         return error("Invalid cmp constexpt record");
3389       unsigned OpTyID = Record[0];
3390       Type *OpTy = getTypeByID(OpTyID);
3391       if (!OpTy)
3392         return error("Invalid cmp constexpr record");
3393       V = BitcodeConstant::create(
3394           Alloc, CurTy,
3395           {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
3396                                               : Instruction::ICmp),
3397            (uint8_t)Record[3]},
3398           {(unsigned)Record[1], (unsigned)Record[2]});
3399       break;
3400     }
3401     // This maintains backward compatibility, pre-asm dialect keywords.
3402     // Deprecated, but still needed to read old bitcode files.
3403     case bitc::CST_CODE_INLINEASM_OLD: {
3404       if (Record.size() < 2)
3405         return error("Invalid inlineasm record");
3406       std::string AsmStr, ConstrStr;
3407       bool HasSideEffects = Record[0] & 1;
3408       bool IsAlignStack = Record[0] >> 1;
3409       unsigned AsmStrSize = Record[1];
3410       if (2+AsmStrSize >= Record.size())
3411         return error("Invalid inlineasm record");
3412       unsigned ConstStrSize = Record[2+AsmStrSize];
3413       if (3+AsmStrSize+ConstStrSize > Record.size())
3414         return error("Invalid inlineasm record");
3415 
3416       for (unsigned i = 0; i != AsmStrSize; ++i)
3417         AsmStr += (char)Record[2+i];
3418       for (unsigned i = 0; i != ConstStrSize; ++i)
3419         ConstrStr += (char)Record[3+AsmStrSize+i];
3420       UpgradeInlineAsmString(&AsmStr);
3421       if (!CurElemTy)
3422         return error("Missing element type for old-style inlineasm");
3423       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3424                          HasSideEffects, IsAlignStack);
3425       break;
3426     }
3427     // This version adds support for the asm dialect keywords (e.g.,
3428     // inteldialect).
3429     case bitc::CST_CODE_INLINEASM_OLD2: {
3430       if (Record.size() < 2)
3431         return error("Invalid inlineasm record");
3432       std::string AsmStr, ConstrStr;
3433       bool HasSideEffects = Record[0] & 1;
3434       bool IsAlignStack = (Record[0] >> 1) & 1;
3435       unsigned AsmDialect = Record[0] >> 2;
3436       unsigned AsmStrSize = Record[1];
3437       if (2+AsmStrSize >= Record.size())
3438         return error("Invalid inlineasm record");
3439       unsigned ConstStrSize = Record[2+AsmStrSize];
3440       if (3+AsmStrSize+ConstStrSize > Record.size())
3441         return error("Invalid inlineasm record");
3442 
3443       for (unsigned i = 0; i != AsmStrSize; ++i)
3444         AsmStr += (char)Record[2+i];
3445       for (unsigned i = 0; i != ConstStrSize; ++i)
3446         ConstrStr += (char)Record[3+AsmStrSize+i];
3447       UpgradeInlineAsmString(&AsmStr);
3448       if (!CurElemTy)
3449         return error("Missing element type for old-style inlineasm");
3450       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3451                          HasSideEffects, IsAlignStack,
3452                          InlineAsm::AsmDialect(AsmDialect));
3453       break;
3454     }
3455     // This version adds support for the unwind keyword.
3456     case bitc::CST_CODE_INLINEASM_OLD3: {
3457       if (Record.size() < 2)
3458         return error("Invalid inlineasm record");
3459       unsigned OpNum = 0;
3460       std::string AsmStr, ConstrStr;
3461       bool HasSideEffects = Record[OpNum] & 1;
3462       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3463       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3464       bool CanThrow = (Record[OpNum] >> 3) & 1;
3465       ++OpNum;
3466       unsigned AsmStrSize = Record[OpNum];
3467       ++OpNum;
3468       if (OpNum + AsmStrSize >= Record.size())
3469         return error("Invalid inlineasm record");
3470       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3471       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3472         return error("Invalid inlineasm record");
3473 
3474       for (unsigned i = 0; i != AsmStrSize; ++i)
3475         AsmStr += (char)Record[OpNum + i];
3476       ++OpNum;
3477       for (unsigned i = 0; i != ConstStrSize; ++i)
3478         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3479       UpgradeInlineAsmString(&AsmStr);
3480       if (!CurElemTy)
3481         return error("Missing element type for old-style inlineasm");
3482       V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
3483                          HasSideEffects, IsAlignStack,
3484                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
3485       break;
3486     }
3487     // This version adds explicit function type.
3488     case bitc::CST_CODE_INLINEASM: {
3489       if (Record.size() < 3)
3490         return error("Invalid inlineasm record");
3491       unsigned OpNum = 0;
3492       auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
3493       ++OpNum;
3494       if (!FnTy)
3495         return error("Invalid inlineasm record");
3496       std::string AsmStr, ConstrStr;
3497       bool HasSideEffects = Record[OpNum] & 1;
3498       bool IsAlignStack = (Record[OpNum] >> 1) & 1;
3499       unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
3500       bool CanThrow = (Record[OpNum] >> 3) & 1;
3501       ++OpNum;
3502       unsigned AsmStrSize = Record[OpNum];
3503       ++OpNum;
3504       if (OpNum + AsmStrSize >= Record.size())
3505         return error("Invalid inlineasm record");
3506       unsigned ConstStrSize = Record[OpNum + AsmStrSize];
3507       if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
3508         return error("Invalid inlineasm record");
3509 
3510       for (unsigned i = 0; i != AsmStrSize; ++i)
3511         AsmStr += (char)Record[OpNum + i];
3512       ++OpNum;
3513       for (unsigned i = 0; i != ConstStrSize; ++i)
3514         ConstrStr += (char)Record[OpNum + AsmStrSize + i];
3515       UpgradeInlineAsmString(&AsmStr);
3516       V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
3517                          InlineAsm::AsmDialect(AsmDialect), CanThrow);
3518       break;
3519     }
3520     case bitc::CST_CODE_BLOCKADDRESS:{
3521       if (Record.size() < 3)
3522         return error("Invalid blockaddress record");
3523       unsigned FnTyID = Record[0];
3524       Type *FnTy = getTypeByID(FnTyID);
3525       if (!FnTy)
3526         return error("Invalid blockaddress record");
3527       V = BitcodeConstant::create(
3528           Alloc, CurTy,
3529           {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
3530           Record[1]);
3531       break;
3532     }
3533     case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
3534       if (Record.size() < 2)
3535         return error("Invalid dso_local record");
3536       unsigned GVTyID = Record[0];
3537       Type *GVTy = getTypeByID(GVTyID);
3538       if (!GVTy)
3539         return error("Invalid dso_local record");
3540       V = BitcodeConstant::create(
3541           Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
3542       break;
3543     }
3544     case bitc::CST_CODE_NO_CFI_VALUE: {
3545       if (Record.size() < 2)
3546         return error("Invalid no_cfi record");
3547       unsigned GVTyID = Record[0];
3548       Type *GVTy = getTypeByID(GVTyID);
3549       if (!GVTy)
3550         return error("Invalid no_cfi record");
3551       V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
3552                                   Record[1]);
3553       break;
3554     }
3555     }
3556 
3557     assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
3558     if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
3559       return Err;
3560     ++NextCstNo;
3561   }
3562 }
3563 
3564 Error BitcodeReader::parseUseLists() {
3565   if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
3566     return Err;
3567 
3568   // Read all the records.
3569   SmallVector<uint64_t, 64> Record;
3570 
3571   while (true) {
3572     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
3573     if (!MaybeEntry)
3574       return MaybeEntry.takeError();
3575     BitstreamEntry Entry = MaybeEntry.get();
3576 
3577     switch (Entry.Kind) {
3578     case BitstreamEntry::SubBlock: // Handled for us already.
3579     case BitstreamEntry::Error:
3580       return error("Malformed block");
3581     case BitstreamEntry::EndBlock:
3582       return Error::success();
3583     case BitstreamEntry::Record:
3584       // The interesting case.
3585       break;
3586     }
3587 
3588     // Read a use list record.
3589     Record.clear();
3590     bool IsBB = false;
3591     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
3592     if (!MaybeRecord)
3593       return MaybeRecord.takeError();
3594     switch (MaybeRecord.get()) {
3595     default:  // Default behavior: unknown type.
3596       break;
3597     case bitc::USELIST_CODE_BB:
3598       IsBB = true;
3599       [[fallthrough]];
3600     case bitc::USELIST_CODE_DEFAULT: {
3601       unsigned RecordLength = Record.size();
3602       if (RecordLength < 3)
3603         // Records should have at least an ID and two indexes.
3604         return error("Invalid record");
3605       unsigned ID = Record.pop_back_val();
3606 
3607       Value *V;
3608       if (IsBB) {
3609         assert(ID < FunctionBBs.size() && "Basic block not found");
3610         V = FunctionBBs[ID];
3611       } else
3612         V = ValueList[ID];
3613       unsigned NumUses = 0;
3614       SmallDenseMap<const Use *, unsigned, 16> Order;
3615       for (const Use &U : V->materialized_uses()) {
3616         if (++NumUses > Record.size())
3617           break;
3618         Order[&U] = Record[NumUses - 1];
3619       }
3620       if (Order.size() != Record.size() || NumUses > Record.size())
3621         // Mismatches can happen if the functions are being materialized lazily
3622         // (out-of-order), or a value has been upgraded.
3623         break;
3624 
3625       V->sortUseList([&](const Use &L, const Use &R) {
3626         return Order.lookup(&L) < Order.lookup(&R);
3627       });
3628       break;
3629     }
3630     }
3631   }
3632 }
3633 
3634 /// When we see the block for metadata, remember where it is and then skip it.
3635 /// This lets us lazily deserialize the metadata.
3636 Error BitcodeReader::rememberAndSkipMetadata() {
3637   // Save the current stream state.
3638   uint64_t CurBit = Stream.GetCurrentBitNo();
3639   DeferredMetadataInfo.push_back(CurBit);
3640 
3641   // Skip over the block for now.
3642   if (Error Err = Stream.SkipBlock())
3643     return Err;
3644   return Error::success();
3645 }
3646 
3647 Error BitcodeReader::materializeMetadata() {
3648   for (uint64_t BitPos : DeferredMetadataInfo) {
3649     // Move the bit stream to the saved position.
3650     if (Error JumpFailed = Stream.JumpToBit(BitPos))
3651       return JumpFailed;
3652     if (Error Err = MDLoader->parseModuleMetadata())
3653       return Err;
3654   }
3655 
3656   // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
3657   // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
3658   // multiple times.
3659   if (!TheModule->getNamedMetadata("llvm.linker.options")) {
3660     if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
3661       NamedMDNode *LinkerOpts =
3662           TheModule->getOrInsertNamedMetadata("llvm.linker.options");
3663       for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
3664         LinkerOpts->addOperand(cast<MDNode>(MDOptions));
3665     }
3666   }
3667 
3668   DeferredMetadataInfo.clear();
3669   return Error::success();
3670 }
3671 
3672 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
3673 
3674 /// When we see the block for a function body, remember where it is and then
3675 /// skip it.  This lets us lazily deserialize the functions.
3676 Error BitcodeReader::rememberAndSkipFunctionBody() {
3677   // Get the function we are talking about.
3678   if (FunctionsWithBodies.empty())
3679     return error("Insufficient function protos");
3680 
3681   Function *Fn = FunctionsWithBodies.back();
3682   FunctionsWithBodies.pop_back();
3683 
3684   // Save the current stream state.
3685   uint64_t CurBit = Stream.GetCurrentBitNo();
3686   assert(
3687       (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3688       "Mismatch between VST and scanned function offsets");
3689   DeferredFunctionInfo[Fn] = CurBit;
3690 
3691   // Skip over the function block for now.
3692   if (Error Err = Stream.SkipBlock())
3693     return Err;
3694   return Error::success();
3695 }
3696 
3697 Error BitcodeReader::globalCleanup() {
3698   // Patch the initializers for globals and aliases up.
3699   if (Error Err = resolveGlobalAndIndirectSymbolInits())
3700     return Err;
3701   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
3702     return error("Malformed global initializer set");
3703 
3704   // Look for intrinsic functions which need to be upgraded at some point
3705   // and functions that need to have their function attributes upgraded.
3706   for (Function &F : *TheModule) {
3707     MDLoader->upgradeDebugIntrinsics(F);
3708     Function *NewFn;
3709     if (UpgradeIntrinsicFunction(&F, NewFn))
3710       UpgradedIntrinsics[&F] = NewFn;
3711     // Look for functions that rely on old function attribute behavior.
3712     UpgradeFunctionAttributes(F);
3713   }
3714 
3715   // Look for global variables which need to be renamed.
3716   std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
3717   for (GlobalVariable &GV : TheModule->globals())
3718     if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
3719       UpgradedVariables.emplace_back(&GV, Upgraded);
3720   for (auto &Pair : UpgradedVariables) {
3721     Pair.first->eraseFromParent();
3722     TheModule->insertGlobalVariable(Pair.second);
3723   }
3724 
3725   // Force deallocation of memory for these vectors to favor the client that
3726   // want lazy deserialization.
3727   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
3728   std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
3729   return Error::success();
3730 }
3731 
3732 /// Support for lazy parsing of function bodies. This is required if we
3733 /// either have an old bitcode file without a VST forward declaration record,
3734 /// or if we have an anonymous function being materialized, since anonymous
3735 /// functions do not have a name and are therefore not in the VST.
3736 Error BitcodeReader::rememberAndSkipFunctionBodies() {
3737   if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
3738     return JumpFailed;
3739 
3740   if (Stream.AtEndOfStream())
3741     return error("Could not find function in stream");
3742 
3743   if (!SeenFirstFunctionBody)
3744     return error("Trying to materialize functions before seeing function blocks");
3745 
3746   // An old bitcode file with the symbol table at the end would have
3747   // finished the parse greedily.
3748   assert(SeenValueSymbolTable);
3749 
3750   SmallVector<uint64_t, 64> Record;
3751 
3752   while (true) {
3753     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
3754     if (!MaybeEntry)
3755       return MaybeEntry.takeError();
3756     llvm::BitstreamEntry Entry = MaybeEntry.get();
3757 
3758     switch (Entry.Kind) {
3759     default:
3760       return error("Expect SubBlock");
3761     case BitstreamEntry::SubBlock:
3762       switch (Entry.ID) {
3763       default:
3764         return error("Expect function block");
3765       case bitc::FUNCTION_BLOCK_ID:
3766         if (Error Err = rememberAndSkipFunctionBody())
3767           return Err;
3768         NextUnreadBit = Stream.GetCurrentBitNo();
3769         return Error::success();
3770       }
3771     }
3772   }
3773 }
3774 
3775 Error BitcodeReaderBase::readBlockInfo() {
3776   Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
3777       Stream.ReadBlockInfoBlock();
3778   if (!MaybeNewBlockInfo)
3779     return MaybeNewBlockInfo.takeError();
3780   std::optional<BitstreamBlockInfo> NewBlockInfo =
3781       std::move(MaybeNewBlockInfo.get());
3782   if (!NewBlockInfo)
3783     return error("Malformed block");
3784   BlockInfo = std::move(*NewBlockInfo);
3785   return Error::success();
3786 }
3787 
3788 Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
3789   // v1: [selection_kind, name]
3790   // v2: [strtab_offset, strtab_size, selection_kind]
3791   StringRef Name;
3792   std::tie(Name, Record) = readNameFromStrtab(Record);
3793 
3794   if (Record.empty())
3795     return error("Invalid record");
3796   Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3797   std::string OldFormatName;
3798   if (!UseStrtab) {
3799     if (Record.size() < 2)
3800       return error("Invalid record");
3801     unsigned ComdatNameSize = Record[1];
3802     if (ComdatNameSize > Record.size() - 2)
3803       return error("Comdat name size too large");
3804     OldFormatName.reserve(ComdatNameSize);
3805     for (unsigned i = 0; i != ComdatNameSize; ++i)
3806       OldFormatName += (char)Record[2 + i];
3807     Name = OldFormatName;
3808   }
3809   Comdat *C = TheModule->getOrInsertComdat(Name);
3810   C->setSelectionKind(SK);
3811   ComdatList.push_back(C);
3812   return Error::success();
3813 }
3814 
3815 static void inferDSOLocal(GlobalValue *GV) {
3816   // infer dso_local from linkage and visibility if it is not encoded.
3817   if (GV->hasLocalLinkage() ||
3818       (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
3819     GV->setDSOLocal(true);
3820 }
3821 
3822 GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
3823   GlobalValue::SanitizerMetadata Meta;
3824   if (V & (1 << 0))
3825     Meta.NoAddress = true;
3826   if (V & (1 << 1))
3827     Meta.NoHWAddress = true;
3828   if (V & (1 << 2))
3829     Meta.Memtag = true;
3830   if (V & (1 << 3))
3831     Meta.IsDynInit = true;
3832   return Meta;
3833 }
3834 
3835 Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
3836   // v1: [pointer type, isconst, initid, linkage, alignment, section,
3837   // visibility, threadlocal, unnamed_addr, externally_initialized,
3838   // dllstorageclass, comdat, attributes, preemption specifier,
3839   // partition strtab offset, partition strtab size] (name in VST)
3840   // v2: [strtab_offset, strtab_size, v1]
3841   // v3: [v2, code_model]
3842   StringRef Name;
3843   std::tie(Name, Record) = readNameFromStrtab(Record);
3844 
3845   if (Record.size() < 6)
3846     return error("Invalid record");
3847   unsigned TyID = Record[0];
3848   Type *Ty = getTypeByID(TyID);
3849   if (!Ty)
3850     return error("Invalid record");
3851   bool isConstant = Record[1] & 1;
3852   bool explicitType = Record[1] & 2;
3853   unsigned AddressSpace;
3854   if (explicitType) {
3855     AddressSpace = Record[1] >> 2;
3856   } else {
3857     if (!Ty->isPointerTy())
3858       return error("Invalid type for value");
3859     AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3860     TyID = getContainedTypeID(TyID);
3861     Ty = getTypeByID(TyID);
3862     if (!Ty)
3863       return error("Missing element type for old-style global");
3864   }
3865 
3866   uint64_t RawLinkage = Record[3];
3867   GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
3868   MaybeAlign Alignment;
3869   if (Error Err = parseAlignmentValue(Record[4], Alignment))
3870     return Err;
3871   std::string Section;
3872   if (Record[5]) {
3873     if (Record[5] - 1 >= SectionTable.size())
3874       return error("Invalid ID");
3875     Section = SectionTable[Record[5] - 1];
3876   }
3877   GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
3878   // Local linkage must have default visibility.
3879   // auto-upgrade `hidden` and `protected` for old bitcode.
3880   if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3881     Visibility = getDecodedVisibility(Record[6]);
3882 
3883   GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
3884   if (Record.size() > 7)
3885     TLM = getDecodedThreadLocalMode(Record[7]);
3886 
3887   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
3888   if (Record.size() > 8)
3889     UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
3890 
3891   bool ExternallyInitialized = false;
3892   if (Record.size() > 9)
3893     ExternallyInitialized = Record[9];
3894 
3895   GlobalVariable *NewGV =
3896       new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
3897                          nullptr, TLM, AddressSpace, ExternallyInitialized);
3898   if (Alignment)
3899     NewGV->setAlignment(*Alignment);
3900   if (!Section.empty())
3901     NewGV->setSection(Section);
3902   NewGV->setVisibility(Visibility);
3903   NewGV->setUnnamedAddr(UnnamedAddr);
3904 
3905   if (Record.size() > 10) {
3906     // A GlobalValue with local linkage cannot have a DLL storage class.
3907     if (!NewGV->hasLocalLinkage()) {
3908       NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
3909     }
3910   } else {
3911     upgradeDLLImportExportLinkage(NewGV, RawLinkage);
3912   }
3913 
3914   ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
3915 
3916   // Remember which value to use for the global initializer.
3917   if (unsigned InitID = Record[2])
3918     GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
3919 
3920   if (Record.size() > 11) {
3921     if (unsigned ComdatID = Record[11]) {
3922       if (ComdatID > ComdatList.size())
3923         return error("Invalid global variable comdat ID");
3924       NewGV->setComdat(ComdatList[ComdatID - 1]);
3925     }
3926   } else if (hasImplicitComdat(RawLinkage)) {
3927     ImplicitComdatObjects.insert(NewGV);
3928   }
3929 
3930   if (Record.size() > 12) {
3931     auto AS = getAttributes(Record[12]).getFnAttrs();
3932     NewGV->setAttributes(AS);
3933   }
3934 
3935   if (Record.size() > 13) {
3936     NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
3937   }
3938   inferDSOLocal(NewGV);
3939 
3940   // Check whether we have enough values to read a partition name.
3941   if (Record.size() > 15)
3942     NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
3943 
3944   if (Record.size() > 16 && Record[16]) {
3945     llvm::GlobalValue::SanitizerMetadata Meta =
3946         deserializeSanitizerMetadata(Record[16]);
3947     NewGV->setSanitizerMetadata(Meta);
3948   }
3949 
3950   if (Record.size() > 17 && Record[17]) {
3951     if (auto CM = getDecodedCodeModel(Record[17]))
3952       NewGV->setCodeModel(*CM);
3953     else
3954       return error("Invalid global variable code model");
3955   }
3956 
3957   return Error::success();
3958 }
3959 
3960 void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
3961   if (ValueTypeCallback) {
3962     (*ValueTypeCallback)(
3963         F, TypeID, [this](unsigned I) { return getTypeByID(I); },
3964         [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
3965   }
3966 }
3967 
3968 Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
3969   // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
3970   // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
3971   // prefixdata,  personalityfn, preemption specifier, addrspace] (name in VST)
3972   // v2: [strtab_offset, strtab_size, v1]
3973   StringRef Name;
3974   std::tie(Name, Record) = readNameFromStrtab(Record);
3975 
3976   if (Record.size() < 8)
3977     return error("Invalid record");
3978   unsigned FTyID = Record[0];
3979   Type *FTy = getTypeByID(FTyID);
3980   if (!FTy)
3981     return error("Invalid record");
3982   if (isa<PointerType>(FTy)) {
3983     FTyID = getContainedTypeID(FTyID, 0);
3984     FTy = getTypeByID(FTyID);
3985     if (!FTy)
3986       return error("Missing element type for old-style function");
3987   }
3988 
3989   if (!isa<FunctionType>(FTy))
3990     return error("Invalid type for value");
3991   auto CC = static_cast<CallingConv::ID>(Record[1]);
3992   if (CC & ~CallingConv::MaxID)
3993     return error("Invalid calling convention ID");
3994 
3995   unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
3996   if (Record.size() > 16)
3997     AddrSpace = Record[16];
3998 
3999   Function *Func =
4000       Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
4001                        AddrSpace, Name, TheModule);
4002 
4003   assert(Func->getFunctionType() == FTy &&
4004          "Incorrect fully specified type provided for function");
4005   FunctionTypeIDs[Func] = FTyID;
4006 
4007   Func->setCallingConv(CC);
4008   bool isProto = Record[2];
4009   uint64_t RawLinkage = Record[3];
4010   Func->setLinkage(getDecodedLinkage(RawLinkage));
4011   Func->setAttributes(getAttributes(Record[4]));
4012   callValueTypeCallback(Func, FTyID);
4013 
4014   // Upgrade any old-style byval or sret without a type by propagating the
4015   // argument's pointee type. There should be no opaque pointers where the byval
4016   // type is implicit.
4017   for (unsigned i = 0; i != Func->arg_size(); ++i) {
4018     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4019                                      Attribute::InAlloca}) {
4020       if (!Func->hasParamAttribute(i, Kind))
4021         continue;
4022 
4023       if (Func->getParamAttribute(i, Kind).getValueAsType())
4024         continue;
4025 
4026       Func->removeParamAttr(i, Kind);
4027 
4028       unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
4029       Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
4030       if (!PtrEltTy)
4031         return error("Missing param element type for attribute upgrade");
4032 
4033       Attribute NewAttr;
4034       switch (Kind) {
4035       case Attribute::ByVal:
4036         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4037         break;
4038       case Attribute::StructRet:
4039         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4040         break;
4041       case Attribute::InAlloca:
4042         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4043         break;
4044       default:
4045         llvm_unreachable("not an upgraded type attribute");
4046       }
4047 
4048       Func->addParamAttr(i, NewAttr);
4049     }
4050   }
4051 
4052   if (Func->getCallingConv() == CallingConv::X86_INTR &&
4053       !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
4054     unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
4055     Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
4056     if (!ByValTy)
4057       return error("Missing param element type for x86_intrcc upgrade");
4058     Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
4059     Func->addParamAttr(0, NewAttr);
4060   }
4061 
4062   MaybeAlign Alignment;
4063   if (Error Err = parseAlignmentValue(Record[5], Alignment))
4064     return Err;
4065   if (Alignment)
4066     Func->setAlignment(*Alignment);
4067   if (Record[6]) {
4068     if (Record[6] - 1 >= SectionTable.size())
4069       return error("Invalid ID");
4070     Func->setSection(SectionTable[Record[6] - 1]);
4071   }
4072   // Local linkage must have default visibility.
4073   // auto-upgrade `hidden` and `protected` for old bitcode.
4074   if (!Func->hasLocalLinkage())
4075     Func->setVisibility(getDecodedVisibility(Record[7]));
4076   if (Record.size() > 8 && Record[8]) {
4077     if (Record[8] - 1 >= GCTable.size())
4078       return error("Invalid ID");
4079     Func->setGC(GCTable[Record[8] - 1]);
4080   }
4081   GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
4082   if (Record.size() > 9)
4083     UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
4084   Func->setUnnamedAddr(UnnamedAddr);
4085 
4086   FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
4087   if (Record.size() > 10)
4088     OperandInfo.Prologue = Record[10];
4089 
4090   if (Record.size() > 11) {
4091     // A GlobalValue with local linkage cannot have a DLL storage class.
4092     if (!Func->hasLocalLinkage()) {
4093       Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
4094     }
4095   } else {
4096     upgradeDLLImportExportLinkage(Func, RawLinkage);
4097   }
4098 
4099   if (Record.size() > 12) {
4100     if (unsigned ComdatID = Record[12]) {
4101       if (ComdatID > ComdatList.size())
4102         return error("Invalid function comdat ID");
4103       Func->setComdat(ComdatList[ComdatID - 1]);
4104     }
4105   } else if (hasImplicitComdat(RawLinkage)) {
4106     ImplicitComdatObjects.insert(Func);
4107   }
4108 
4109   if (Record.size() > 13)
4110     OperandInfo.Prefix = Record[13];
4111 
4112   if (Record.size() > 14)
4113     OperandInfo.PersonalityFn = Record[14];
4114 
4115   if (Record.size() > 15) {
4116     Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
4117   }
4118   inferDSOLocal(Func);
4119 
4120   // Record[16] is the address space number.
4121 
4122   // Check whether we have enough values to read a partition name. Also make
4123   // sure Strtab has enough values.
4124   if (Record.size() > 18 && Strtab.data() &&
4125       Record[17] + Record[18] <= Strtab.size()) {
4126     Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
4127   }
4128 
4129   ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
4130 
4131   if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
4132     FunctionOperands.push_back(OperandInfo);
4133 
4134   // If this is a function with a body, remember the prototype we are
4135   // creating now, so that we can match up the body with them later.
4136   if (!isProto) {
4137     Func->setIsMaterializable(true);
4138     FunctionsWithBodies.push_back(Func);
4139     DeferredFunctionInfo[Func] = 0;
4140   }
4141   return Error::success();
4142 }
4143 
4144 Error BitcodeReader::parseGlobalIndirectSymbolRecord(
4145     unsigned BitCode, ArrayRef<uint64_t> Record) {
4146   // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
4147   // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
4148   // dllstorageclass, threadlocal, unnamed_addr,
4149   // preemption specifier] (name in VST)
4150   // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
4151   // visibility, dllstorageclass, threadlocal, unnamed_addr,
4152   // preemption specifier] (name in VST)
4153   // v2: [strtab_offset, strtab_size, v1]
4154   StringRef Name;
4155   std::tie(Name, Record) = readNameFromStrtab(Record);
4156 
4157   bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
4158   if (Record.size() < (3 + (unsigned)NewRecord))
4159     return error("Invalid record");
4160   unsigned OpNum = 0;
4161   unsigned TypeID = Record[OpNum++];
4162   Type *Ty = getTypeByID(TypeID);
4163   if (!Ty)
4164     return error("Invalid record");
4165 
4166   unsigned AddrSpace;
4167   if (!NewRecord) {
4168     auto *PTy = dyn_cast<PointerType>(Ty);
4169     if (!PTy)
4170       return error("Invalid type for value");
4171     AddrSpace = PTy->getAddressSpace();
4172     TypeID = getContainedTypeID(TypeID);
4173     Ty = getTypeByID(TypeID);
4174     if (!Ty)
4175       return error("Missing element type for old-style indirect symbol");
4176   } else {
4177     AddrSpace = Record[OpNum++];
4178   }
4179 
4180   auto Val = Record[OpNum++];
4181   auto Linkage = Record[OpNum++];
4182   GlobalValue *NewGA;
4183   if (BitCode == bitc::MODULE_CODE_ALIAS ||
4184       BitCode == bitc::MODULE_CODE_ALIAS_OLD)
4185     NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4186                                 TheModule);
4187   else
4188     NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
4189                                 nullptr, TheModule);
4190 
4191   // Local linkage must have default visibility.
4192   // auto-upgrade `hidden` and `protected` for old bitcode.
4193   if (OpNum != Record.size()) {
4194     auto VisInd = OpNum++;
4195     if (!NewGA->hasLocalLinkage())
4196       NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
4197   }
4198   if (BitCode == bitc::MODULE_CODE_ALIAS ||
4199       BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
4200     if (OpNum != Record.size()) {
4201       auto S = Record[OpNum++];
4202       // A GlobalValue with local linkage cannot have a DLL storage class.
4203       if (!NewGA->hasLocalLinkage())
4204         NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S));
4205     }
4206     else
4207       upgradeDLLImportExportLinkage(NewGA, Linkage);
4208     if (OpNum != Record.size())
4209       NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
4210     if (OpNum != Record.size())
4211       NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
4212   }
4213   if (OpNum != Record.size())
4214     NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
4215   inferDSOLocal(NewGA);
4216 
4217   // Check whether we have enough values to read a partition name.
4218   if (OpNum + 1 < Record.size()) {
4219     NewGA->setPartition(
4220         StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
4221     OpNum += 2;
4222   }
4223 
4224   ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
4225   IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
4226   return Error::success();
4227 }
4228 
4229 Error BitcodeReader::parseModule(uint64_t ResumeBit,
4230                                  bool ShouldLazyLoadMetadata,
4231                                  ParserCallbacks Callbacks) {
4232   this->ValueTypeCallback = std::move(Callbacks.ValueType);
4233   if (ResumeBit) {
4234     if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
4235       return JumpFailed;
4236   } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
4237     return Err;
4238 
4239   SmallVector<uint64_t, 64> Record;
4240 
4241   // Parts of bitcode parsing depend on the datalayout.  Make sure we
4242   // finalize the datalayout before we run any of that code.
4243   bool ResolvedDataLayout = false;
4244   // In order to support importing modules with illegal data layout strings,
4245   // delay parsing the data layout string until after upgrades and overrides
4246   // have been applied, allowing to fix illegal data layout strings.
4247   // Initialize to the current module's layout string in case none is specified.
4248   std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
4249 
4250   auto ResolveDataLayout = [&]() -> Error {
4251     if (ResolvedDataLayout)
4252       return Error::success();
4253 
4254     // Datalayout and triple can't be parsed after this point.
4255     ResolvedDataLayout = true;
4256 
4257     // Auto-upgrade the layout string
4258     TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
4259         TentativeDataLayoutStr, TheModule->getTargetTriple());
4260 
4261     // Apply override
4262     if (Callbacks.DataLayout) {
4263       if (auto LayoutOverride = (*Callbacks.DataLayout)(
4264               TheModule->getTargetTriple(), TentativeDataLayoutStr))
4265         TentativeDataLayoutStr = *LayoutOverride;
4266     }
4267 
4268     // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
4269     Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
4270     if (!MaybeDL)
4271       return MaybeDL.takeError();
4272 
4273     TheModule->setDataLayout(MaybeDL.get());
4274     return Error::success();
4275   };
4276 
4277   // Read all the records for this module.
4278   while (true) {
4279     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4280     if (!MaybeEntry)
4281       return MaybeEntry.takeError();
4282     llvm::BitstreamEntry Entry = MaybeEntry.get();
4283 
4284     switch (Entry.Kind) {
4285     case BitstreamEntry::Error:
4286       return error("Malformed block");
4287     case BitstreamEntry::EndBlock:
4288       if (Error Err = ResolveDataLayout())
4289         return Err;
4290       return globalCleanup();
4291 
4292     case BitstreamEntry::SubBlock:
4293       switch (Entry.ID) {
4294       default:  // Skip unknown content.
4295         if (Error Err = Stream.SkipBlock())
4296           return Err;
4297         break;
4298       case bitc::BLOCKINFO_BLOCK_ID:
4299         if (Error Err = readBlockInfo())
4300           return Err;
4301         break;
4302       case bitc::PARAMATTR_BLOCK_ID:
4303         if (Error Err = parseAttributeBlock())
4304           return Err;
4305         break;
4306       case bitc::PARAMATTR_GROUP_BLOCK_ID:
4307         if (Error Err = parseAttributeGroupBlock())
4308           return Err;
4309         break;
4310       case bitc::TYPE_BLOCK_ID_NEW:
4311         if (Error Err = parseTypeTable())
4312           return Err;
4313         break;
4314       case bitc::VALUE_SYMTAB_BLOCK_ID:
4315         if (!SeenValueSymbolTable) {
4316           // Either this is an old form VST without function index and an
4317           // associated VST forward declaration record (which would have caused
4318           // the VST to be jumped to and parsed before it was encountered
4319           // normally in the stream), or there were no function blocks to
4320           // trigger an earlier parsing of the VST.
4321           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
4322           if (Error Err = parseValueSymbolTable())
4323             return Err;
4324           SeenValueSymbolTable = true;
4325         } else {
4326           // We must have had a VST forward declaration record, which caused
4327           // the parser to jump to and parse the VST earlier.
4328           assert(VSTOffset > 0);
4329           if (Error Err = Stream.SkipBlock())
4330             return Err;
4331         }
4332         break;
4333       case bitc::CONSTANTS_BLOCK_ID:
4334         if (Error Err = parseConstants())
4335           return Err;
4336         if (Error Err = resolveGlobalAndIndirectSymbolInits())
4337           return Err;
4338         break;
4339       case bitc::METADATA_BLOCK_ID:
4340         if (ShouldLazyLoadMetadata) {
4341           if (Error Err = rememberAndSkipMetadata())
4342             return Err;
4343           break;
4344         }
4345         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
4346         if (Error Err = MDLoader->parseModuleMetadata())
4347           return Err;
4348         break;
4349       case bitc::METADATA_KIND_BLOCK_ID:
4350         if (Error Err = MDLoader->parseMetadataKinds())
4351           return Err;
4352         break;
4353       case bitc::FUNCTION_BLOCK_ID:
4354         if (Error Err = ResolveDataLayout())
4355           return Err;
4356 
4357         // If this is the first function body we've seen, reverse the
4358         // FunctionsWithBodies list.
4359         if (!SeenFirstFunctionBody) {
4360           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
4361           if (Error Err = globalCleanup())
4362             return Err;
4363           SeenFirstFunctionBody = true;
4364         }
4365 
4366         if (VSTOffset > 0) {
4367           // If we have a VST forward declaration record, make sure we
4368           // parse the VST now if we haven't already. It is needed to
4369           // set up the DeferredFunctionInfo vector for lazy reading.
4370           if (!SeenValueSymbolTable) {
4371             if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
4372               return Err;
4373             SeenValueSymbolTable = true;
4374             // Fall through so that we record the NextUnreadBit below.
4375             // This is necessary in case we have an anonymous function that
4376             // is later materialized. Since it will not have a VST entry we
4377             // need to fall back to the lazy parse to find its offset.
4378           } else {
4379             // If we have a VST forward declaration record, but have already
4380             // parsed the VST (just above, when the first function body was
4381             // encountered here), then we are resuming the parse after
4382             // materializing functions. The ResumeBit points to the
4383             // start of the last function block recorded in the
4384             // DeferredFunctionInfo map. Skip it.
4385             if (Error Err = Stream.SkipBlock())
4386               return Err;
4387             continue;
4388           }
4389         }
4390 
4391         // Support older bitcode files that did not have the function
4392         // index in the VST, nor a VST forward declaration record, as
4393         // well as anonymous functions that do not have VST entries.
4394         // Build the DeferredFunctionInfo vector on the fly.
4395         if (Error Err = rememberAndSkipFunctionBody())
4396           return Err;
4397 
4398         // Suspend parsing when we reach the function bodies. Subsequent
4399         // materialization calls will resume it when necessary. If the bitcode
4400         // file is old, the symbol table will be at the end instead and will not
4401         // have been seen yet. In this case, just finish the parse now.
4402         if (SeenValueSymbolTable) {
4403           NextUnreadBit = Stream.GetCurrentBitNo();
4404           // After the VST has been parsed, we need to make sure intrinsic name
4405           // are auto-upgraded.
4406           return globalCleanup();
4407         }
4408         break;
4409       case bitc::USELIST_BLOCK_ID:
4410         if (Error Err = parseUseLists())
4411           return Err;
4412         break;
4413       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
4414         if (Error Err = parseOperandBundleTags())
4415           return Err;
4416         break;
4417       case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
4418         if (Error Err = parseSyncScopeNames())
4419           return Err;
4420         break;
4421       }
4422       continue;
4423 
4424     case BitstreamEntry::Record:
4425       // The interesting case.
4426       break;
4427     }
4428 
4429     // Read a record.
4430     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4431     if (!MaybeBitCode)
4432       return MaybeBitCode.takeError();
4433     switch (unsigned BitCode = MaybeBitCode.get()) {
4434     default: break;  // Default behavior, ignore unknown content.
4435     case bitc::MODULE_CODE_VERSION: {
4436       Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
4437       if (!VersionOrErr)
4438         return VersionOrErr.takeError();
4439       UseRelativeIDs = *VersionOrErr >= 1;
4440       break;
4441     }
4442     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
4443       if (ResolvedDataLayout)
4444         return error("target triple too late in module");
4445       std::string S;
4446       if (convertToString(Record, 0, S))
4447         return error("Invalid record");
4448       TheModule->setTargetTriple(S);
4449       break;
4450     }
4451     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
4452       if (ResolvedDataLayout)
4453         return error("datalayout too late in module");
4454       if (convertToString(Record, 0, TentativeDataLayoutStr))
4455         return error("Invalid record");
4456       break;
4457     }
4458     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
4459       std::string S;
4460       if (convertToString(Record, 0, S))
4461         return error("Invalid record");
4462       TheModule->setModuleInlineAsm(S);
4463       break;
4464     }
4465     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
4466       // Deprecated, but still needed to read old bitcode files.
4467       std::string S;
4468       if (convertToString(Record, 0, S))
4469         return error("Invalid record");
4470       // Ignore value.
4471       break;
4472     }
4473     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
4474       std::string S;
4475       if (convertToString(Record, 0, S))
4476         return error("Invalid record");
4477       SectionTable.push_back(S);
4478       break;
4479     }
4480     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
4481       std::string S;
4482       if (convertToString(Record, 0, S))
4483         return error("Invalid record");
4484       GCTable.push_back(S);
4485       break;
4486     }
4487     case bitc::MODULE_CODE_COMDAT:
4488       if (Error Err = parseComdatRecord(Record))
4489         return Err;
4490       break;
4491     // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
4492     // written by ThinLinkBitcodeWriter. See
4493     // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
4494     // record
4495     // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
4496     case bitc::MODULE_CODE_GLOBALVAR:
4497       if (Error Err = parseGlobalVarRecord(Record))
4498         return Err;
4499       break;
4500     case bitc::MODULE_CODE_FUNCTION:
4501       if (Error Err = ResolveDataLayout())
4502         return Err;
4503       if (Error Err = parseFunctionRecord(Record))
4504         return Err;
4505       break;
4506     case bitc::MODULE_CODE_IFUNC:
4507     case bitc::MODULE_CODE_ALIAS:
4508     case bitc::MODULE_CODE_ALIAS_OLD:
4509       if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
4510         return Err;
4511       break;
4512     /// MODULE_CODE_VSTOFFSET: [offset]
4513     case bitc::MODULE_CODE_VSTOFFSET:
4514       if (Record.empty())
4515         return error("Invalid record");
4516       // Note that we subtract 1 here because the offset is relative to one word
4517       // before the start of the identification or module block, which was
4518       // historically always the start of the regular bitcode header.
4519       VSTOffset = Record[0] - 1;
4520       break;
4521     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
4522     case bitc::MODULE_CODE_SOURCE_FILENAME:
4523       SmallString<128> ValueName;
4524       if (convertToString(Record, 0, ValueName))
4525         return error("Invalid record");
4526       TheModule->setSourceFileName(ValueName);
4527       break;
4528     }
4529     Record.clear();
4530   }
4531   this->ValueTypeCallback = std::nullopt;
4532   return Error::success();
4533 }
4534 
4535 Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
4536                                       bool IsImporting,
4537                                       ParserCallbacks Callbacks) {
4538   TheModule = M;
4539   MetadataLoaderCallbacks MDCallbacks;
4540   MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
4541   MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
4542     return getContainedTypeID(I, J);
4543   };
4544   MDCallbacks.MDType = Callbacks.MDType;
4545   MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
4546   return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
4547 }
4548 
4549 Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
4550   if (!isa<PointerType>(PtrType))
4551     return error("Load/Store operand is not a pointer type");
4552   if (!PointerType::isLoadableOrStorableType(ValType))
4553     return error("Cannot load/store from pointer");
4554   return Error::success();
4555 }
4556 
4557 Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
4558                                              ArrayRef<unsigned> ArgTyIDs) {
4559   AttributeList Attrs = CB->getAttributes();
4560   for (unsigned i = 0; i != CB->arg_size(); ++i) {
4561     for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
4562                                      Attribute::InAlloca}) {
4563       if (!Attrs.hasParamAttr(i, Kind) ||
4564           Attrs.getParamAttr(i, Kind).getValueAsType())
4565         continue;
4566 
4567       Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
4568       if (!PtrEltTy)
4569         return error("Missing element type for typed attribute upgrade");
4570 
4571       Attribute NewAttr;
4572       switch (Kind) {
4573       case Attribute::ByVal:
4574         NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
4575         break;
4576       case Attribute::StructRet:
4577         NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
4578         break;
4579       case Attribute::InAlloca:
4580         NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
4581         break;
4582       default:
4583         llvm_unreachable("not an upgraded type attribute");
4584       }
4585 
4586       Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
4587     }
4588   }
4589 
4590   if (CB->isInlineAsm()) {
4591     const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
4592     unsigned ArgNo = 0;
4593     for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4594       if (!CI.hasArg())
4595         continue;
4596 
4597       if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
4598         Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4599         if (!ElemTy)
4600           return error("Missing element type for inline asm upgrade");
4601         Attrs = Attrs.addParamAttribute(
4602             Context, ArgNo,
4603             Attribute::get(Context, Attribute::ElementType, ElemTy));
4604       }
4605 
4606       ArgNo++;
4607     }
4608   }
4609 
4610   switch (CB->getIntrinsicID()) {
4611   case Intrinsic::preserve_array_access_index:
4612   case Intrinsic::preserve_struct_access_index:
4613   case Intrinsic::aarch64_ldaxr:
4614   case Intrinsic::aarch64_ldxr:
4615   case Intrinsic::aarch64_stlxr:
4616   case Intrinsic::aarch64_stxr:
4617   case Intrinsic::arm_ldaex:
4618   case Intrinsic::arm_ldrex:
4619   case Intrinsic::arm_stlex:
4620   case Intrinsic::arm_strex: {
4621     unsigned ArgNo;
4622     switch (CB->getIntrinsicID()) {
4623     case Intrinsic::aarch64_stlxr:
4624     case Intrinsic::aarch64_stxr:
4625     case Intrinsic::arm_stlex:
4626     case Intrinsic::arm_strex:
4627       ArgNo = 1;
4628       break;
4629     default:
4630       ArgNo = 0;
4631       break;
4632     }
4633     if (!Attrs.getParamElementType(ArgNo)) {
4634       Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
4635       if (!ElTy)
4636         return error("Missing element type for elementtype upgrade");
4637       Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
4638       Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
4639     }
4640     break;
4641   }
4642   default:
4643     break;
4644   }
4645 
4646   CB->setAttributes(Attrs);
4647   return Error::success();
4648 }
4649 
4650 /// Lazily parse the specified function body block.
4651 Error BitcodeReader::parseFunctionBody(Function *F) {
4652   if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
4653     return Err;
4654 
4655   // Unexpected unresolved metadata when parsing function.
4656   if (MDLoader->hasFwdRefs())
4657     return error("Invalid function metadata: incoming forward references");
4658 
4659   InstructionList.clear();
4660   unsigned ModuleValueListSize = ValueList.size();
4661   unsigned ModuleMDLoaderSize = MDLoader->size();
4662 
4663   // Add all the function arguments to the value table.
4664   unsigned ArgNo = 0;
4665   unsigned FTyID = FunctionTypeIDs[F];
4666   for (Argument &I : F->args()) {
4667     unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
4668     assert(I.getType() == getTypeByID(ArgTyID) &&
4669            "Incorrect fully specified type for Function Argument");
4670     ValueList.push_back(&I, ArgTyID);
4671     ++ArgNo;
4672   }
4673   unsigned NextValueNo = ValueList.size();
4674   BasicBlock *CurBB = nullptr;
4675   unsigned CurBBNo = 0;
4676   // Block into which constant expressions from phi nodes are materialized.
4677   BasicBlock *PhiConstExprBB = nullptr;
4678   // Edge blocks for phi nodes into which constant expressions have been
4679   // expanded.
4680   SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
4681     ConstExprEdgeBBs;
4682 
4683   DebugLoc LastLoc;
4684   auto getLastInstruction = [&]() -> Instruction * {
4685     if (CurBB && !CurBB->empty())
4686       return &CurBB->back();
4687     else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4688              !FunctionBBs[CurBBNo - 1]->empty())
4689       return &FunctionBBs[CurBBNo - 1]->back();
4690     return nullptr;
4691   };
4692 
4693   std::vector<OperandBundleDef> OperandBundles;
4694 
4695   // Read all the records.
4696   SmallVector<uint64_t, 64> Record;
4697 
4698   while (true) {
4699     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
4700     if (!MaybeEntry)
4701       return MaybeEntry.takeError();
4702     llvm::BitstreamEntry Entry = MaybeEntry.get();
4703 
4704     switch (Entry.Kind) {
4705     case BitstreamEntry::Error:
4706       return error("Malformed block");
4707     case BitstreamEntry::EndBlock:
4708       goto OutOfRecordLoop;
4709 
4710     case BitstreamEntry::SubBlock:
4711       switch (Entry.ID) {
4712       default:  // Skip unknown content.
4713         if (Error Err = Stream.SkipBlock())
4714           return Err;
4715         break;
4716       case bitc::CONSTANTS_BLOCK_ID:
4717         if (Error Err = parseConstants())
4718           return Err;
4719         NextValueNo = ValueList.size();
4720         break;
4721       case bitc::VALUE_SYMTAB_BLOCK_ID:
4722         if (Error Err = parseValueSymbolTable())
4723           return Err;
4724         break;
4725       case bitc::METADATA_ATTACHMENT_ID:
4726         if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
4727           return Err;
4728         break;
4729       case bitc::METADATA_BLOCK_ID:
4730         assert(DeferredMetadataInfo.empty() &&
4731                "Must read all module-level metadata before function-level");
4732         if (Error Err = MDLoader->parseFunctionMetadata())
4733           return Err;
4734         break;
4735       case bitc::USELIST_BLOCK_ID:
4736         if (Error Err = parseUseLists())
4737           return Err;
4738         break;
4739       }
4740       continue;
4741 
4742     case BitstreamEntry::Record:
4743       // The interesting case.
4744       break;
4745     }
4746 
4747     // Read a record.
4748     Record.clear();
4749     Instruction *I = nullptr;
4750     unsigned ResTypeID = InvalidTypeID;
4751     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
4752     if (!MaybeBitCode)
4753       return MaybeBitCode.takeError();
4754     switch (unsigned BitCode = MaybeBitCode.get()) {
4755     default: // Default behavior: reject
4756       return error("Invalid value");
4757     case bitc::FUNC_CODE_DECLAREBLOCKS: {   // DECLAREBLOCKS: [nblocks]
4758       if (Record.empty() || Record[0] == 0)
4759         return error("Invalid record");
4760       // Create all the basic blocks for the function.
4761       FunctionBBs.resize(Record[0]);
4762 
4763       // See if anything took the address of blocks in this function.
4764       auto BBFRI = BasicBlockFwdRefs.find(F);
4765       if (BBFRI == BasicBlockFwdRefs.end()) {
4766         for (BasicBlock *&BB : FunctionBBs)
4767           BB = BasicBlock::Create(Context, "", F);
4768       } else {
4769         auto &BBRefs = BBFRI->second;
4770         // Check for invalid basic block references.
4771         if (BBRefs.size() > FunctionBBs.size())
4772           return error("Invalid ID");
4773         assert(!BBRefs.empty() && "Unexpected empty array");
4774         assert(!BBRefs.front() && "Invalid reference to entry block");
4775         for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4776              ++I)
4777           if (I < RE && BBRefs[I]) {
4778             BBRefs[I]->insertInto(F);
4779             FunctionBBs[I] = BBRefs[I];
4780           } else {
4781             FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4782           }
4783 
4784         // Erase from the table.
4785         BasicBlockFwdRefs.erase(BBFRI);
4786       }
4787 
4788       CurBB = FunctionBBs[0];
4789       continue;
4790     }
4791 
4792     case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
4793       // The record should not be emitted if it's an empty list.
4794       if (Record.empty())
4795         return error("Invalid record");
4796       // When we have the RARE case of a BlockAddress Constant that is not
4797       // scoped to the Function it refers to, we need to conservatively
4798       // materialize the referred to Function, regardless of whether or not
4799       // that Function will ultimately be linked, otherwise users of
4800       // BitcodeReader might start splicing out Function bodies such that we
4801       // might no longer be able to materialize the BlockAddress since the
4802       // BasicBlock (and entire body of the Function) the BlockAddress refers
4803       // to may have been moved. In the case that the user of BitcodeReader
4804       // decides ultimately not to link the Function body, materializing here
4805       // could be considered wasteful, but it's better than a deserialization
4806       // failure as described. This keeps BitcodeReader unaware of complex
4807       // linkage policy decisions such as those use by LTO, leaving those
4808       // decisions "one layer up."
4809       for (uint64_t ValID : Record)
4810         if (auto *F = dyn_cast<Function>(ValueList[ValID]))
4811           BackwardRefFunctions.push_back(F);
4812         else
4813           return error("Invalid record");
4814 
4815       continue;
4816 
4817     case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
4818       // This record indicates that the last instruction is at the same
4819       // location as the previous instruction with a location.
4820       I = getLastInstruction();
4821 
4822       if (!I)
4823         return error("Invalid record");
4824       I->setDebugLoc(LastLoc);
4825       I = nullptr;
4826       continue;
4827 
4828     case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
4829       I = getLastInstruction();
4830       if (!I || Record.size() < 4)
4831         return error("Invalid record");
4832 
4833       unsigned Line = Record[0], Col = Record[1];
4834       unsigned ScopeID = Record[2], IAID = Record[3];
4835       bool isImplicitCode = Record.size() == 5 && Record[4];
4836 
4837       MDNode *Scope = nullptr, *IA = nullptr;
4838       if (ScopeID) {
4839         Scope = dyn_cast_or_null<MDNode>(
4840             MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
4841         if (!Scope)
4842           return error("Invalid record");
4843       }
4844       if (IAID) {
4845         IA = dyn_cast_or_null<MDNode>(
4846             MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
4847         if (!IA)
4848           return error("Invalid record");
4849       }
4850       LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
4851                                 isImplicitCode);
4852       I->setDebugLoc(LastLoc);
4853       I = nullptr;
4854       continue;
4855     }
4856     case bitc::FUNC_CODE_INST_UNOP: {    // UNOP: [opval, ty, opcode]
4857       unsigned OpNum = 0;
4858       Value *LHS;
4859       unsigned TypeID;
4860       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
4861           OpNum+1 > Record.size())
4862         return error("Invalid record");
4863 
4864       int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
4865       if (Opc == -1)
4866         return error("Invalid record");
4867       I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
4868       ResTypeID = TypeID;
4869       InstructionList.push_back(I);
4870       if (OpNum < Record.size()) {
4871         if (isa<FPMathOperator>(I)) {
4872           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4873           if (FMF.any())
4874             I->setFastMathFlags(FMF);
4875         }
4876       }
4877       break;
4878     }
4879     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
4880       unsigned OpNum = 0;
4881       Value *LHS, *RHS;
4882       unsigned TypeID;
4883       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
4884           popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
4885                    CurBB) ||
4886           OpNum+1 > Record.size())
4887         return error("Invalid record");
4888 
4889       int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
4890       if (Opc == -1)
4891         return error("Invalid record");
4892       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
4893       ResTypeID = TypeID;
4894       InstructionList.push_back(I);
4895       if (OpNum < Record.size()) {
4896         if (Opc == Instruction::Add ||
4897             Opc == Instruction::Sub ||
4898             Opc == Instruction::Mul ||
4899             Opc == Instruction::Shl) {
4900           if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
4901             cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
4902           if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
4903             cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
4904         } else if (Opc == Instruction::SDiv ||
4905                    Opc == Instruction::UDiv ||
4906                    Opc == Instruction::LShr ||
4907                    Opc == Instruction::AShr) {
4908           if (Record[OpNum] & (1 << bitc::PEO_EXACT))
4909             cast<BinaryOperator>(I)->setIsExact(true);
4910         } else if (Opc == Instruction::Or) {
4911           if (Record[OpNum] & (1 << bitc::PDI_DISJOINT))
4912             cast<PossiblyDisjointInst>(I)->setIsDisjoint(true);
4913         } else if (isa<FPMathOperator>(I)) {
4914           FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
4915           if (FMF.any())
4916             I->setFastMathFlags(FMF);
4917         }
4918       }
4919       break;
4920     }
4921     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
4922       unsigned OpNum = 0;
4923       Value *Op;
4924       unsigned OpTypeID;
4925       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
4926           OpNum + 1 > Record.size())
4927         return error("Invalid record");
4928 
4929       ResTypeID = Record[OpNum++];
4930       Type *ResTy = getTypeByID(ResTypeID);
4931       int Opc = getDecodedCastOpcode(Record[OpNum++]);
4932 
4933       if (Opc == -1 || !ResTy)
4934         return error("Invalid record");
4935       Instruction *Temp = nullptr;
4936       if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4937         if (Temp) {
4938           InstructionList.push_back(Temp);
4939           assert(CurBB && "No current BB?");
4940           Temp->insertInto(CurBB, CurBB->end());
4941         }
4942       } else {
4943         auto CastOp = (Instruction::CastOps)Opc;
4944         if (!CastInst::castIsValid(CastOp, Op, ResTy))
4945           return error("Invalid cast");
4946         I = CastInst::Create(CastOp, Op, ResTy);
4947       }
4948       if (OpNum < Record.size() && isa<PossiblyNonNegInst>(I) &&
4949           (Record[OpNum] & (1 << bitc::PNNI_NON_NEG)))
4950         I->setNonNeg(true);
4951       InstructionList.push_back(I);
4952       break;
4953     }
4954     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4955     case bitc::FUNC_CODE_INST_GEP_OLD:
4956     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
4957       unsigned OpNum = 0;
4958 
4959       unsigned TyID;
4960       Type *Ty;
4961       bool InBounds;
4962 
4963       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4964         InBounds = Record[OpNum++];
4965         TyID = Record[OpNum++];
4966         Ty = getTypeByID(TyID);
4967       } else {
4968         InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4969         TyID = InvalidTypeID;
4970         Ty = nullptr;
4971       }
4972 
4973       Value *BasePtr;
4974       unsigned BasePtrTypeID;
4975       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
4976                            CurBB))
4977         return error("Invalid record");
4978 
4979       if (!Ty) {
4980         TyID = getContainedTypeID(BasePtrTypeID);
4981         if (BasePtr->getType()->isVectorTy())
4982           TyID = getContainedTypeID(TyID);
4983         Ty = getTypeByID(TyID);
4984       }
4985 
4986       SmallVector<Value*, 16> GEPIdx;
4987       while (OpNum != Record.size()) {
4988         Value *Op;
4989         unsigned OpTypeID;
4990         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
4991           return error("Invalid record");
4992         GEPIdx.push_back(Op);
4993       }
4994 
4995       I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
4996 
4997       ResTypeID = TyID;
4998       if (cast<GEPOperator>(I)->getNumIndices() != 0) {
4999         auto GTI = std::next(gep_type_begin(I));
5000         for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
5001           unsigned SubType = 0;
5002           if (GTI.isStruct()) {
5003             ConstantInt *IdxC =
5004                 Idx->getType()->isVectorTy()
5005                     ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
5006                     : cast<ConstantInt>(Idx);
5007             SubType = IdxC->getZExtValue();
5008           }
5009           ResTypeID = getContainedTypeID(ResTypeID, SubType);
5010           ++GTI;
5011         }
5012       }
5013 
5014       // At this point ResTypeID is the result element type. We need a pointer
5015       // or vector of pointer to it.
5016       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
5017       if (I->getType()->isVectorTy())
5018         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5019 
5020       InstructionList.push_back(I);
5021       if (InBounds)
5022         cast<GetElementPtrInst>(I)->setIsInBounds(true);
5023       break;
5024     }
5025 
5026     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
5027                                        // EXTRACTVAL: [opty, opval, n x indices]
5028       unsigned OpNum = 0;
5029       Value *Agg;
5030       unsigned AggTypeID;
5031       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5032         return error("Invalid record");
5033       Type *Ty = Agg->getType();
5034 
5035       unsigned RecSize = Record.size();
5036       if (OpNum == RecSize)
5037         return error("EXTRACTVAL: Invalid instruction with 0 indices");
5038 
5039       SmallVector<unsigned, 4> EXTRACTVALIdx;
5040       ResTypeID = AggTypeID;
5041       for (; OpNum != RecSize; ++OpNum) {
5042         bool IsArray = Ty->isArrayTy();
5043         bool IsStruct = Ty->isStructTy();
5044         uint64_t Index = Record[OpNum];
5045 
5046         if (!IsStruct && !IsArray)
5047           return error("EXTRACTVAL: Invalid type");
5048         if ((unsigned)Index != Index)
5049           return error("Invalid value");
5050         if (IsStruct && Index >= Ty->getStructNumElements())
5051           return error("EXTRACTVAL: Invalid struct index");
5052         if (IsArray && Index >= Ty->getArrayNumElements())
5053           return error("EXTRACTVAL: Invalid array index");
5054         EXTRACTVALIdx.push_back((unsigned)Index);
5055 
5056         if (IsStruct) {
5057           Ty = Ty->getStructElementType(Index);
5058           ResTypeID = getContainedTypeID(ResTypeID, Index);
5059         } else {
5060           Ty = Ty->getArrayElementType();
5061           ResTypeID = getContainedTypeID(ResTypeID);
5062         }
5063       }
5064 
5065       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
5066       InstructionList.push_back(I);
5067       break;
5068     }
5069 
5070     case bitc::FUNC_CODE_INST_INSERTVAL: {
5071                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
5072       unsigned OpNum = 0;
5073       Value *Agg;
5074       unsigned AggTypeID;
5075       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5076         return error("Invalid record");
5077       Value *Val;
5078       unsigned ValTypeID;
5079       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5080         return error("Invalid record");
5081 
5082       unsigned RecSize = Record.size();
5083       if (OpNum == RecSize)
5084         return error("INSERTVAL: Invalid instruction with 0 indices");
5085 
5086       SmallVector<unsigned, 4> INSERTVALIdx;
5087       Type *CurTy = Agg->getType();
5088       for (; OpNum != RecSize; ++OpNum) {
5089         bool IsArray = CurTy->isArrayTy();
5090         bool IsStruct = CurTy->isStructTy();
5091         uint64_t Index = Record[OpNum];
5092 
5093         if (!IsStruct && !IsArray)
5094           return error("INSERTVAL: Invalid type");
5095         if ((unsigned)Index != Index)
5096           return error("Invalid value");
5097         if (IsStruct && Index >= CurTy->getStructNumElements())
5098           return error("INSERTVAL: Invalid struct index");
5099         if (IsArray && Index >= CurTy->getArrayNumElements())
5100           return error("INSERTVAL: Invalid array index");
5101 
5102         INSERTVALIdx.push_back((unsigned)Index);
5103         if (IsStruct)
5104           CurTy = CurTy->getStructElementType(Index);
5105         else
5106           CurTy = CurTy->getArrayElementType();
5107       }
5108 
5109       if (CurTy != Val->getType())
5110         return error("Inserted value type doesn't match aggregate type");
5111 
5112       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
5113       ResTypeID = AggTypeID;
5114       InstructionList.push_back(I);
5115       break;
5116     }
5117 
5118     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5119       // obsolete form of select
5120       // handles select i1 ... in old bitcode
5121       unsigned OpNum = 0;
5122       Value *TrueVal, *FalseVal, *Cond;
5123       unsigned TypeID;
5124       Type *CondType = Type::getInt1Ty(Context);
5125       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
5126                            CurBB) ||
5127           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
5128                    FalseVal, CurBB) ||
5129           popValue(Record, OpNum, NextValueNo, CondType,
5130                    getVirtualTypeID(CondType), Cond, CurBB))
5131         return error("Invalid record");
5132 
5133       I = SelectInst::Create(Cond, TrueVal, FalseVal);
5134       ResTypeID = TypeID;
5135       InstructionList.push_back(I);
5136       break;
5137     }
5138 
5139     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
5140       // new form of select
5141       // handles select i1 or select [N x i1]
5142       unsigned OpNum = 0;
5143       Value *TrueVal, *FalseVal, *Cond;
5144       unsigned ValTypeID, CondTypeID;
5145       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5146                            CurBB) ||
5147           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
5148                    FalseVal, CurBB) ||
5149           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
5150         return error("Invalid record");
5151 
5152       // select condition can be either i1 or [N x i1]
5153       if (VectorType* vector_type =
5154           dyn_cast<VectorType>(Cond->getType())) {
5155         // expect <n x i1>
5156         if (vector_type->getElementType() != Type::getInt1Ty(Context))
5157           return error("Invalid type for value");
5158       } else {
5159         // expect i1
5160         if (Cond->getType() != Type::getInt1Ty(Context))
5161           return error("Invalid type for value");
5162       }
5163 
5164       I = SelectInst::Create(Cond, TrueVal, FalseVal);
5165       ResTypeID = ValTypeID;
5166       InstructionList.push_back(I);
5167       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
5168         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5169         if (FMF.any())
5170           I->setFastMathFlags(FMF);
5171       }
5172       break;
5173     }
5174 
5175     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5176       unsigned OpNum = 0;
5177       Value *Vec, *Idx;
5178       unsigned VecTypeID, IdxTypeID;
5179       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5180           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5181         return error("Invalid record");
5182       if (!Vec->getType()->isVectorTy())
5183         return error("Invalid type for value");
5184       I = ExtractElementInst::Create(Vec, Idx);
5185       ResTypeID = getContainedTypeID(VecTypeID);
5186       InstructionList.push_back(I);
5187       break;
5188     }
5189 
5190     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5191       unsigned OpNum = 0;
5192       Value *Vec, *Elt, *Idx;
5193       unsigned VecTypeID, IdxTypeID;
5194       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5195         return error("Invalid record");
5196       if (!Vec->getType()->isVectorTy())
5197         return error("Invalid type for value");
5198       if (popValue(Record, OpNum, NextValueNo,
5199                    cast<VectorType>(Vec->getType())->getElementType(),
5200                    getContainedTypeID(VecTypeID), Elt, CurBB) ||
5201           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5202         return error("Invalid record");
5203       I = InsertElementInst::Create(Vec, Elt, Idx);
5204       ResTypeID = VecTypeID;
5205       InstructionList.push_back(I);
5206       break;
5207     }
5208 
5209     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5210       unsigned OpNum = 0;
5211       Value *Vec1, *Vec2, *Mask;
5212       unsigned Vec1TypeID;
5213       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5214                            CurBB) ||
5215           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5216                    Vec2, CurBB))
5217         return error("Invalid record");
5218 
5219       unsigned MaskTypeID;
5220       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5221         return error("Invalid record");
5222       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5223         return error("Invalid type for value");
5224 
5225       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5226       ResTypeID =
5227           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5228       InstructionList.push_back(I);
5229       break;
5230     }
5231 
5232     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
5233       // Old form of ICmp/FCmp returning bool
5234       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5235       // both legal on vectors but had different behaviour.
5236     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5237       // FCmp/ICmp returning bool or vector of bool
5238 
5239       unsigned OpNum = 0;
5240       Value *LHS, *RHS;
5241       unsigned LHSTypeID;
5242       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5243           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5244                    CurBB))
5245         return error("Invalid record");
5246 
5247       if (OpNum >= Record.size())
5248         return error(
5249             "Invalid record: operand number exceeded available operands");
5250 
5251       CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
5252       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5253       FastMathFlags FMF;
5254       if (IsFP && Record.size() > OpNum+1)
5255         FMF = getDecodedFastMathFlags(Record[++OpNum]);
5256 
5257       if (OpNum+1 != Record.size())
5258         return error("Invalid record");
5259 
5260       if (IsFP) {
5261         if (!CmpInst::isFPPredicate(PredVal))
5262           return error("Invalid fcmp predicate");
5263         I = new FCmpInst(PredVal, LHS, RHS);
5264       } else {
5265         if (!CmpInst::isIntPredicate(PredVal))
5266           return error("Invalid icmp predicate");
5267         I = new ICmpInst(PredVal, LHS, RHS);
5268       }
5269 
5270       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5271       if (LHS->getType()->isVectorTy())
5272         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5273 
5274       if (FMF.any())
5275         I->setFastMathFlags(FMF);
5276       InstructionList.push_back(I);
5277       break;
5278     }
5279 
5280     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5281       {
5282         unsigned Size = Record.size();
5283         if (Size == 0) {
5284           I = ReturnInst::Create(Context);
5285           InstructionList.push_back(I);
5286           break;
5287         }
5288 
5289         unsigned OpNum = 0;
5290         Value *Op = nullptr;
5291         unsigned OpTypeID;
5292         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5293           return error("Invalid record");
5294         if (OpNum != Record.size())
5295           return error("Invalid record");
5296 
5297         I = ReturnInst::Create(Context, Op);
5298         InstructionList.push_back(I);
5299         break;
5300       }
5301     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5302       if (Record.size() != 1 && Record.size() != 3)
5303         return error("Invalid record");
5304       BasicBlock *TrueDest = getBasicBlock(Record[0]);
5305       if (!TrueDest)
5306         return error("Invalid record");
5307 
5308       if (Record.size() == 1) {
5309         I = BranchInst::Create(TrueDest);
5310         InstructionList.push_back(I);
5311       }
5312       else {
5313         BasicBlock *FalseDest = getBasicBlock(Record[1]);
5314         Type *CondType = Type::getInt1Ty(Context);
5315         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
5316                                getVirtualTypeID(CondType), CurBB);
5317         if (!FalseDest || !Cond)
5318           return error("Invalid record");
5319         I = BranchInst::Create(TrueDest, FalseDest, Cond);
5320         InstructionList.push_back(I);
5321       }
5322       break;
5323     }
5324     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5325       if (Record.size() != 1 && Record.size() != 2)
5326         return error("Invalid record");
5327       unsigned Idx = 0;
5328       Type *TokenTy = Type::getTokenTy(Context);
5329       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5330                                    getVirtualTypeID(TokenTy), CurBB);
5331       if (!CleanupPad)
5332         return error("Invalid record");
5333       BasicBlock *UnwindDest = nullptr;
5334       if (Record.size() == 2) {
5335         UnwindDest = getBasicBlock(Record[Idx++]);
5336         if (!UnwindDest)
5337           return error("Invalid record");
5338       }
5339 
5340       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5341       InstructionList.push_back(I);
5342       break;
5343     }
5344     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5345       if (Record.size() != 2)
5346         return error("Invalid record");
5347       unsigned Idx = 0;
5348       Type *TokenTy = Type::getTokenTy(Context);
5349       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5350                                  getVirtualTypeID(TokenTy), CurBB);
5351       if (!CatchPad)
5352         return error("Invalid record");
5353       BasicBlock *BB = getBasicBlock(Record[Idx++]);
5354       if (!BB)
5355         return error("Invalid record");
5356 
5357       I = CatchReturnInst::Create(CatchPad, BB);
5358       InstructionList.push_back(I);
5359       break;
5360     }
5361     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5362       // We must have, at minimum, the outer scope and the number of arguments.
5363       if (Record.size() < 2)
5364         return error("Invalid record");
5365 
5366       unsigned Idx = 0;
5367 
5368       Type *TokenTy = Type::getTokenTy(Context);
5369       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5370                                   getVirtualTypeID(TokenTy), CurBB);
5371       if (!ParentPad)
5372         return error("Invalid record");
5373 
5374       unsigned NumHandlers = Record[Idx++];
5375 
5376       SmallVector<BasicBlock *, 2> Handlers;
5377       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5378         BasicBlock *BB = getBasicBlock(Record[Idx++]);
5379         if (!BB)
5380           return error("Invalid record");
5381         Handlers.push_back(BB);
5382       }
5383 
5384       BasicBlock *UnwindDest = nullptr;
5385       if (Idx + 1 == Record.size()) {
5386         UnwindDest = getBasicBlock(Record[Idx++]);
5387         if (!UnwindDest)
5388           return error("Invalid record");
5389       }
5390 
5391       if (Record.size() != Idx)
5392         return error("Invalid record");
5393 
5394       auto *CatchSwitch =
5395           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5396       for (BasicBlock *Handler : Handlers)
5397         CatchSwitch->addHandler(Handler);
5398       I = CatchSwitch;
5399       ResTypeID = getVirtualTypeID(I->getType());
5400       InstructionList.push_back(I);
5401       break;
5402     }
5403     case bitc::FUNC_CODE_INST_CATCHPAD:
5404     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5405       // We must have, at minimum, the outer scope and the number of arguments.
5406       if (Record.size() < 2)
5407         return error("Invalid record");
5408 
5409       unsigned Idx = 0;
5410 
5411       Type *TokenTy = Type::getTokenTy(Context);
5412       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5413                                   getVirtualTypeID(TokenTy), CurBB);
5414       if (!ParentPad)
5415         return error("Invald record");
5416 
5417       unsigned NumArgOperands = Record[Idx++];
5418 
5419       SmallVector<Value *, 2> Args;
5420       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5421         Value *Val;
5422         unsigned ValTypeID;
5423         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5424           return error("Invalid record");
5425         Args.push_back(Val);
5426       }
5427 
5428       if (Record.size() != Idx)
5429         return error("Invalid record");
5430 
5431       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5432         I = CleanupPadInst::Create(ParentPad, Args);
5433       else
5434         I = CatchPadInst::Create(ParentPad, Args);
5435       ResTypeID = getVirtualTypeID(I->getType());
5436       InstructionList.push_back(I);
5437       break;
5438     }
5439     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5440       // Check magic
5441       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5442         // "New" SwitchInst format with case ranges. The changes to write this
5443         // format were reverted but we still recognize bitcode that uses it.
5444         // Hopefully someday we will have support for case ranges and can use
5445         // this format again.
5446 
5447         unsigned OpTyID = Record[1];
5448         Type *OpTy = getTypeByID(OpTyID);
5449         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5450 
5451         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5452         BasicBlock *Default = getBasicBlock(Record[3]);
5453         if (!OpTy || !Cond || !Default)
5454           return error("Invalid record");
5455 
5456         unsigned NumCases = Record[4];
5457 
5458         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5459         InstructionList.push_back(SI);
5460 
5461         unsigned CurIdx = 5;
5462         for (unsigned i = 0; i != NumCases; ++i) {
5463           SmallVector<ConstantInt*, 1> CaseVals;
5464           unsigned NumItems = Record[CurIdx++];
5465           for (unsigned ci = 0; ci != NumItems; ++ci) {
5466             bool isSingleNumber = Record[CurIdx++];
5467 
5468             APInt Low;
5469             unsigned ActiveWords = 1;
5470             if (ValueBitWidth > 64)
5471               ActiveWords = Record[CurIdx++];
5472             Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5473                                 ValueBitWidth);
5474             CurIdx += ActiveWords;
5475 
5476             if (!isSingleNumber) {
5477               ActiveWords = 1;
5478               if (ValueBitWidth > 64)
5479                 ActiveWords = Record[CurIdx++];
5480               APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5481                                          ValueBitWidth);
5482               CurIdx += ActiveWords;
5483 
5484               // FIXME: It is not clear whether values in the range should be
5485               // compared as signed or unsigned values. The partially
5486               // implemented changes that used this format in the past used
5487               // unsigned comparisons.
5488               for ( ; Low.ule(High); ++Low)
5489                 CaseVals.push_back(ConstantInt::get(Context, Low));
5490             } else
5491               CaseVals.push_back(ConstantInt::get(Context, Low));
5492           }
5493           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5494           for (ConstantInt *Cst : CaseVals)
5495             SI->addCase(Cst, DestBB);
5496         }
5497         I = SI;
5498         break;
5499       }
5500 
5501       // Old SwitchInst format without case ranges.
5502 
5503       if (Record.size() < 3 || (Record.size() & 1) == 0)
5504         return error("Invalid record");
5505       unsigned OpTyID = Record[0];
5506       Type *OpTy = getTypeByID(OpTyID);
5507       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5508       BasicBlock *Default = getBasicBlock(Record[2]);
5509       if (!OpTy || !Cond || !Default)
5510         return error("Invalid record");
5511       unsigned NumCases = (Record.size()-3)/2;
5512       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5513       InstructionList.push_back(SI);
5514       for (unsigned i = 0, e = NumCases; i != e; ++i) {
5515         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5516             getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
5517         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5518         if (!CaseVal || !DestBB) {
5519           delete SI;
5520           return error("Invalid record");
5521         }
5522         SI->addCase(CaseVal, DestBB);
5523       }
5524       I = SI;
5525       break;
5526     }
5527     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5528       if (Record.size() < 2)
5529         return error("Invalid record");
5530       unsigned OpTyID = Record[0];
5531       Type *OpTy = getTypeByID(OpTyID);
5532       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5533       if (!OpTy || !Address)
5534         return error("Invalid record");
5535       unsigned NumDests = Record.size()-2;
5536       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5537       InstructionList.push_back(IBI);
5538       for (unsigned i = 0, e = NumDests; i != e; ++i) {
5539         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5540           IBI->addDestination(DestBB);
5541         } else {
5542           delete IBI;
5543           return error("Invalid record");
5544         }
5545       }
5546       I = IBI;
5547       break;
5548     }
5549 
5550     case bitc::FUNC_CODE_INST_INVOKE: {
5551       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5552       if (Record.size() < 4)
5553         return error("Invalid record");
5554       unsigned OpNum = 0;
5555       AttributeList PAL = getAttributes(Record[OpNum++]);
5556       unsigned CCInfo = Record[OpNum++];
5557       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5558       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5559 
5560       unsigned FTyID = InvalidTypeID;
5561       FunctionType *FTy = nullptr;
5562       if ((CCInfo >> 13) & 1) {
5563         FTyID = Record[OpNum++];
5564         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5565         if (!FTy)
5566           return error("Explicit invoke type is not a function type");
5567       }
5568 
5569       Value *Callee;
5570       unsigned CalleeTypeID;
5571       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5572                            CurBB))
5573         return error("Invalid record");
5574 
5575       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5576       if (!CalleeTy)
5577         return error("Callee is not a pointer");
5578       if (!FTy) {
5579         FTyID = getContainedTypeID(CalleeTypeID);
5580         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5581         if (!FTy)
5582           return error("Callee is not of pointer to function type");
5583       }
5584       if (Record.size() < FTy->getNumParams() + OpNum)
5585         return error("Insufficient operands to call");
5586 
5587       SmallVector<Value*, 16> Ops;
5588       SmallVector<unsigned, 16> ArgTyIDs;
5589       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5590         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5591         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5592                                ArgTyID, CurBB));
5593         ArgTyIDs.push_back(ArgTyID);
5594         if (!Ops.back())
5595           return error("Invalid record");
5596       }
5597 
5598       if (!FTy->isVarArg()) {
5599         if (Record.size() != OpNum)
5600           return error("Invalid record");
5601       } else {
5602         // Read type/value pairs for varargs params.
5603         while (OpNum != Record.size()) {
5604           Value *Op;
5605           unsigned OpTypeID;
5606           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5607             return error("Invalid record");
5608           Ops.push_back(Op);
5609           ArgTyIDs.push_back(OpTypeID);
5610         }
5611       }
5612 
5613       // Upgrade the bundles if needed.
5614       if (!OperandBundles.empty())
5615         UpgradeOperandBundles(OperandBundles);
5616 
5617       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5618                              OperandBundles);
5619       ResTypeID = getContainedTypeID(FTyID);
5620       OperandBundles.clear();
5621       InstructionList.push_back(I);
5622       cast<InvokeInst>(I)->setCallingConv(
5623           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5624       cast<InvokeInst>(I)->setAttributes(PAL);
5625       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5626         I->deleteValue();
5627         return Err;
5628       }
5629 
5630       break;
5631     }
5632     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5633       unsigned Idx = 0;
5634       Value *Val = nullptr;
5635       unsigned ValTypeID;
5636       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5637         return error("Invalid record");
5638       I = ResumeInst::Create(Val);
5639       InstructionList.push_back(I);
5640       break;
5641     }
5642     case bitc::FUNC_CODE_INST_CALLBR: {
5643       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5644       unsigned OpNum = 0;
5645       AttributeList PAL = getAttributes(Record[OpNum++]);
5646       unsigned CCInfo = Record[OpNum++];
5647 
5648       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5649       unsigned NumIndirectDests = Record[OpNum++];
5650       SmallVector<BasicBlock *, 16> IndirectDests;
5651       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
5652         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
5653 
5654       unsigned FTyID = InvalidTypeID;
5655       FunctionType *FTy = nullptr;
5656       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5657         FTyID = Record[OpNum++];
5658         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5659         if (!FTy)
5660           return error("Explicit call type is not a function type");
5661       }
5662 
5663       Value *Callee;
5664       unsigned CalleeTypeID;
5665       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5666                            CurBB))
5667         return error("Invalid record");
5668 
5669       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5670       if (!OpTy)
5671         return error("Callee is not a pointer type");
5672       if (!FTy) {
5673         FTyID = getContainedTypeID(CalleeTypeID);
5674         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5675         if (!FTy)
5676           return error("Callee is not of pointer to function type");
5677       }
5678       if (Record.size() < FTy->getNumParams() + OpNum)
5679         return error("Insufficient operands to call");
5680 
5681       SmallVector<Value*, 16> Args;
5682       SmallVector<unsigned, 16> ArgTyIDs;
5683       // Read the fixed params.
5684       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5685         Value *Arg;
5686         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5687         if (FTy->getParamType(i)->isLabelTy())
5688           Arg = getBasicBlock(Record[OpNum]);
5689         else
5690           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5691                          ArgTyID, CurBB);
5692         if (!Arg)
5693           return error("Invalid record");
5694         Args.push_back(Arg);
5695         ArgTyIDs.push_back(ArgTyID);
5696       }
5697 
5698       // Read type/value pairs for varargs params.
5699       if (!FTy->isVarArg()) {
5700         if (OpNum != Record.size())
5701           return error("Invalid record");
5702       } else {
5703         while (OpNum != Record.size()) {
5704           Value *Op;
5705           unsigned OpTypeID;
5706           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5707             return error("Invalid record");
5708           Args.push_back(Op);
5709           ArgTyIDs.push_back(OpTypeID);
5710         }
5711       }
5712 
5713       // Upgrade the bundles if needed.
5714       if (!OperandBundles.empty())
5715         UpgradeOperandBundles(OperandBundles);
5716 
5717       if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
5718         InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
5719         auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
5720           return CI.Type == InlineAsm::isLabel;
5721         };
5722         if (none_of(ConstraintInfo, IsLabelConstraint)) {
5723           // Upgrade explicit blockaddress arguments to label constraints.
5724           // Verify that the last arguments are blockaddress arguments that
5725           // match the indirect destinations. Clang always generates callbr
5726           // in this form. We could support reordering with more effort.
5727           unsigned FirstBlockArg = Args.size() - IndirectDests.size();
5728           for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
5729             unsigned LabelNo = ArgNo - FirstBlockArg;
5730             auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
5731             if (!BA || BA->getFunction() != F ||
5732                 LabelNo > IndirectDests.size() ||
5733                 BA->getBasicBlock() != IndirectDests[LabelNo])
5734               return error("callbr argument does not match indirect dest");
5735           }
5736 
5737           // Remove blockaddress arguments.
5738           Args.erase(Args.begin() + FirstBlockArg, Args.end());
5739           ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
5740 
5741           // Recreate the function type with less arguments.
5742           SmallVector<Type *> ArgTys;
5743           for (Value *Arg : Args)
5744             ArgTys.push_back(Arg->getType());
5745           FTy =
5746               FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
5747 
5748           // Update constraint string to use label constraints.
5749           std::string Constraints = IA->getConstraintString();
5750           unsigned ArgNo = 0;
5751           size_t Pos = 0;
5752           for (const auto &CI : ConstraintInfo) {
5753             if (CI.hasArg()) {
5754               if (ArgNo >= FirstBlockArg)
5755                 Constraints.insert(Pos, "!");
5756               ++ArgNo;
5757             }
5758 
5759             // Go to next constraint in string.
5760             Pos = Constraints.find(',', Pos);
5761             if (Pos == std::string::npos)
5762               break;
5763             ++Pos;
5764           }
5765 
5766           Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
5767                                   IA->hasSideEffects(), IA->isAlignStack(),
5768                                   IA->getDialect(), IA->canThrow());
5769         }
5770       }
5771 
5772       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
5773                              OperandBundles);
5774       ResTypeID = getContainedTypeID(FTyID);
5775       OperandBundles.clear();
5776       InstructionList.push_back(I);
5777       cast<CallBrInst>(I)->setCallingConv(
5778           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
5779       cast<CallBrInst>(I)->setAttributes(PAL);
5780       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5781         I->deleteValue();
5782         return Err;
5783       }
5784       break;
5785     }
5786     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
5787       I = new UnreachableInst(Context);
5788       InstructionList.push_back(I);
5789       break;
5790     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
5791       if (Record.empty())
5792         return error("Invalid phi record");
5793       // The first record specifies the type.
5794       unsigned TyID = Record[0];
5795       Type *Ty = getTypeByID(TyID);
5796       if (!Ty)
5797         return error("Invalid phi record");
5798 
5799       // Phi arguments are pairs of records of [value, basic block].
5800       // There is an optional final record for fast-math-flags if this phi has a
5801       // floating-point type.
5802       size_t NumArgs = (Record.size() - 1) / 2;
5803       PHINode *PN = PHINode::Create(Ty, NumArgs);
5804       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
5805         PN->deleteValue();
5806         return error("Invalid phi record");
5807       }
5808       InstructionList.push_back(PN);
5809 
5810       SmallDenseMap<BasicBlock *, Value *> Args;
5811       for (unsigned i = 0; i != NumArgs; i++) {
5812         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
5813         if (!BB) {
5814           PN->deleteValue();
5815           return error("Invalid phi BB");
5816         }
5817 
5818         // Phi nodes may contain the same predecessor multiple times, in which
5819         // case the incoming value must be identical. Directly reuse the already
5820         // seen value here, to avoid expanding a constant expression multiple
5821         // times.
5822         auto It = Args.find(BB);
5823         if (It != Args.end()) {
5824           PN->addIncoming(It->second, BB);
5825           continue;
5826         }
5827 
5828         // If there already is a block for this edge (from a different phi),
5829         // use it.
5830         BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
5831         if (!EdgeBB) {
5832           // Otherwise, use a temporary block (that we will discard if it
5833           // turns out to be unnecessary).
5834           if (!PhiConstExprBB)
5835             PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
5836           EdgeBB = PhiConstExprBB;
5837         }
5838 
5839         // With the new function encoding, it is possible that operands have
5840         // negative IDs (for forward references).  Use a signed VBR
5841         // representation to keep the encoding small.
5842         Value *V;
5843         if (UseRelativeIDs)
5844           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
5845         else
5846           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
5847         if (!V) {
5848           PN->deleteValue();
5849           PhiConstExprBB->eraseFromParent();
5850           return error("Invalid phi record");
5851         }
5852 
5853         if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
5854           ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
5855           PhiConstExprBB = nullptr;
5856         }
5857         PN->addIncoming(V, BB);
5858         Args.insert({BB, V});
5859       }
5860       I = PN;
5861       ResTypeID = TyID;
5862 
5863       // If there are an even number of records, the final record must be FMF.
5864       if (Record.size() % 2 == 0) {
5865         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
5866         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
5867         if (FMF.any())
5868           I->setFastMathFlags(FMF);
5869       }
5870 
5871       break;
5872     }
5873 
5874     case bitc::FUNC_CODE_INST_LANDINGPAD:
5875     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
5876       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
5877       unsigned Idx = 0;
5878       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
5879         if (Record.size() < 3)
5880           return error("Invalid record");
5881       } else {
5882         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
5883         if (Record.size() < 4)
5884           return error("Invalid record");
5885       }
5886       ResTypeID = Record[Idx++];
5887       Type *Ty = getTypeByID(ResTypeID);
5888       if (!Ty)
5889         return error("Invalid record");
5890       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
5891         Value *PersFn = nullptr;
5892         unsigned PersFnTypeID;
5893         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
5894                              nullptr))
5895           return error("Invalid record");
5896 
5897         if (!F->hasPersonalityFn())
5898           F->setPersonalityFn(cast<Constant>(PersFn));
5899         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
5900           return error("Personality function mismatch");
5901       }
5902 
5903       bool IsCleanup = !!Record[Idx++];
5904       unsigned NumClauses = Record[Idx++];
5905       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
5906       LP->setCleanup(IsCleanup);
5907       for (unsigned J = 0; J != NumClauses; ++J) {
5908         LandingPadInst::ClauseType CT =
5909           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
5910         Value *Val;
5911         unsigned ValTypeID;
5912 
5913         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
5914                              nullptr)) {
5915           delete LP;
5916           return error("Invalid record");
5917         }
5918 
5919         assert((CT != LandingPadInst::Catch ||
5920                 !isa<ArrayType>(Val->getType())) &&
5921                "Catch clause has a invalid type!");
5922         assert((CT != LandingPadInst::Filter ||
5923                 isa<ArrayType>(Val->getType())) &&
5924                "Filter clause has invalid type!");
5925         LP->addClause(cast<Constant>(Val));
5926       }
5927 
5928       I = LP;
5929       InstructionList.push_back(I);
5930       break;
5931     }
5932 
5933     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
5934       if (Record.size() != 4 && Record.size() != 5)
5935         return error("Invalid record");
5936       using APV = AllocaPackedValues;
5937       const uint64_t Rec = Record[3];
5938       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
5939       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
5940       unsigned TyID = Record[0];
5941       Type *Ty = getTypeByID(TyID);
5942       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
5943         TyID = getContainedTypeID(TyID);
5944         Ty = getTypeByID(TyID);
5945         if (!Ty)
5946           return error("Missing element type for old-style alloca");
5947       }
5948       unsigned OpTyID = Record[1];
5949       Type *OpTy = getTypeByID(OpTyID);
5950       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
5951       MaybeAlign Align;
5952       uint64_t AlignExp =
5953           Bitfield::get<APV::AlignLower>(Rec) |
5954           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
5955       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
5956         return Err;
5957       }
5958       if (!Ty || !Size)
5959         return error("Invalid record");
5960 
5961       const DataLayout &DL = TheModule->getDataLayout();
5962       unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
5963 
5964       SmallPtrSet<Type *, 4> Visited;
5965       if (!Align && !Ty->isSized(&Visited))
5966         return error("alloca of unsized type");
5967       if (!Align)
5968         Align = DL.getPrefTypeAlign(Ty);
5969 
5970       if (!Size->getType()->isIntegerTy())
5971         return error("alloca element count must have integer type");
5972 
5973       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
5974       AI->setUsedWithInAlloca(InAlloca);
5975       AI->setSwiftError(SwiftError);
5976       I = AI;
5977       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
5978       InstructionList.push_back(I);
5979       break;
5980     }
5981     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
5982       unsigned OpNum = 0;
5983       Value *Op;
5984       unsigned OpTypeID;
5985       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
5986           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
5987         return error("Invalid record");
5988 
5989       if (!isa<PointerType>(Op->getType()))
5990         return error("Load operand is not a pointer type");
5991 
5992       Type *Ty = nullptr;
5993       if (OpNum + 3 == Record.size()) {
5994         ResTypeID = Record[OpNum++];
5995         Ty = getTypeByID(ResTypeID);
5996       } else {
5997         ResTypeID = getContainedTypeID(OpTypeID);
5998         Ty = getTypeByID(ResTypeID);
5999       }
6000 
6001       if (!Ty)
6002         return error("Missing load type");
6003 
6004       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6005         return Err;
6006 
6007       MaybeAlign Align;
6008       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6009         return Err;
6010       SmallPtrSet<Type *, 4> Visited;
6011       if (!Align && !Ty->isSized(&Visited))
6012         return error("load of unsized type");
6013       if (!Align)
6014         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6015       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
6016       InstructionList.push_back(I);
6017       break;
6018     }
6019     case bitc::FUNC_CODE_INST_LOADATOMIC: {
6020        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6021       unsigned OpNum = 0;
6022       Value *Op;
6023       unsigned OpTypeID;
6024       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6025           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6026         return error("Invalid record");
6027 
6028       if (!isa<PointerType>(Op->getType()))
6029         return error("Load operand is not a pointer type");
6030 
6031       Type *Ty = nullptr;
6032       if (OpNum + 5 == Record.size()) {
6033         ResTypeID = Record[OpNum++];
6034         Ty = getTypeByID(ResTypeID);
6035       } else {
6036         ResTypeID = getContainedTypeID(OpTypeID);
6037         Ty = getTypeByID(ResTypeID);
6038       }
6039 
6040       if (!Ty)
6041         return error("Missing atomic load type");
6042 
6043       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6044         return Err;
6045 
6046       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6047       if (Ordering == AtomicOrdering::NotAtomic ||
6048           Ordering == AtomicOrdering::Release ||
6049           Ordering == AtomicOrdering::AcquireRelease)
6050         return error("Invalid record");
6051       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6052         return error("Invalid record");
6053       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6054 
6055       MaybeAlign Align;
6056       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6057         return Err;
6058       if (!Align)
6059         return error("Alignment missing from atomic load");
6060       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
6061       InstructionList.push_back(I);
6062       break;
6063     }
6064     case bitc::FUNC_CODE_INST_STORE:
6065     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6066       unsigned OpNum = 0;
6067       Value *Val, *Ptr;
6068       unsigned PtrTypeID, ValTypeID;
6069       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6070         return error("Invalid record");
6071 
6072       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6073         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6074           return error("Invalid record");
6075       } else {
6076         ValTypeID = getContainedTypeID(PtrTypeID);
6077         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6078                      ValTypeID, Val, CurBB))
6079           return error("Invalid record");
6080       }
6081 
6082       if (OpNum + 2 != Record.size())
6083         return error("Invalid record");
6084 
6085       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6086         return Err;
6087       MaybeAlign Align;
6088       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6089         return Err;
6090       SmallPtrSet<Type *, 4> Visited;
6091       if (!Align && !Val->getType()->isSized(&Visited))
6092         return error("store of unsized type");
6093       if (!Align)
6094         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
6095       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6096       InstructionList.push_back(I);
6097       break;
6098     }
6099     case bitc::FUNC_CODE_INST_STOREATOMIC:
6100     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
6101       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6102       unsigned OpNum = 0;
6103       Value *Val, *Ptr;
6104       unsigned PtrTypeID, ValTypeID;
6105       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6106           !isa<PointerType>(Ptr->getType()))
6107         return error("Invalid record");
6108       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
6109         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6110           return error("Invalid record");
6111       } else {
6112         ValTypeID = getContainedTypeID(PtrTypeID);
6113         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6114                      ValTypeID, Val, CurBB))
6115           return error("Invalid record");
6116       }
6117 
6118       if (OpNum + 4 != Record.size())
6119         return error("Invalid record");
6120 
6121       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6122         return Err;
6123       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6124       if (Ordering == AtomicOrdering::NotAtomic ||
6125           Ordering == AtomicOrdering::Acquire ||
6126           Ordering == AtomicOrdering::AcquireRelease)
6127         return error("Invalid record");
6128       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6129       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6130         return error("Invalid record");
6131 
6132       MaybeAlign Align;
6133       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6134         return Err;
6135       if (!Align)
6136         return error("Alignment missing from atomic store");
6137       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6138       InstructionList.push_back(I);
6139       break;
6140     }
6141     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6142       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6143       // failure_ordering?, weak?]
6144       const size_t NumRecords = Record.size();
6145       unsigned OpNum = 0;
6146       Value *Ptr = nullptr;
6147       unsigned PtrTypeID;
6148       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6149         return error("Invalid record");
6150 
6151       if (!isa<PointerType>(Ptr->getType()))
6152         return error("Cmpxchg operand is not a pointer type");
6153 
6154       Value *Cmp = nullptr;
6155       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6156       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6157                    CmpTypeID, Cmp, CurBB))
6158         return error("Invalid record");
6159 
6160       Value *New = nullptr;
6161       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
6162                    New, CurBB) ||
6163           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6164         return error("Invalid record");
6165 
6166       const AtomicOrdering SuccessOrdering =
6167           getDecodedOrdering(Record[OpNum + 1]);
6168       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6169           SuccessOrdering == AtomicOrdering::Unordered)
6170         return error("Invalid record");
6171 
6172       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6173 
6174       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6175         return Err;
6176 
6177       const AtomicOrdering FailureOrdering =
6178           NumRecords < 7
6179               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6180               : getDecodedOrdering(Record[OpNum + 3]);
6181 
6182       if (FailureOrdering == AtomicOrdering::NotAtomic ||
6183           FailureOrdering == AtomicOrdering::Unordered)
6184         return error("Invalid record");
6185 
6186       const Align Alignment(
6187           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6188 
6189       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6190                                 FailureOrdering, SSID);
6191       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
6192 
6193       if (NumRecords < 8) {
6194         // Before weak cmpxchgs existed, the instruction simply returned the
6195         // value loaded from memory, so bitcode files from that era will be
6196         // expecting the first component of a modern cmpxchg.
6197         I->insertInto(CurBB, CurBB->end());
6198         I = ExtractValueInst::Create(I, 0);
6199         ResTypeID = CmpTypeID;
6200       } else {
6201         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
6202         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6203         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6204       }
6205 
6206       InstructionList.push_back(I);
6207       break;
6208     }
6209     case bitc::FUNC_CODE_INST_CMPXCHG: {
6210       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6211       // failure_ordering, weak, align?]
6212       const size_t NumRecords = Record.size();
6213       unsigned OpNum = 0;
6214       Value *Ptr = nullptr;
6215       unsigned PtrTypeID;
6216       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6217         return error("Invalid record");
6218 
6219       if (!isa<PointerType>(Ptr->getType()))
6220         return error("Cmpxchg operand is not a pointer type");
6221 
6222       Value *Cmp = nullptr;
6223       unsigned CmpTypeID;
6224       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6225         return error("Invalid record");
6226 
6227       Value *Val = nullptr;
6228       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
6229                    CurBB))
6230         return error("Invalid record");
6231 
6232       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6233         return error("Invalid record");
6234 
6235       const bool IsVol = Record[OpNum];
6236 
6237       const AtomicOrdering SuccessOrdering =
6238           getDecodedOrdering(Record[OpNum + 1]);
6239       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6240         return error("Invalid cmpxchg success ordering");
6241 
6242       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6243 
6244       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6245         return Err;
6246 
6247       const AtomicOrdering FailureOrdering =
6248           getDecodedOrdering(Record[OpNum + 3]);
6249       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6250         return error("Invalid cmpxchg failure ordering");
6251 
6252       const bool IsWeak = Record[OpNum + 4];
6253 
6254       MaybeAlign Alignment;
6255 
6256       if (NumRecords == (OpNum + 6)) {
6257         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6258           return Err;
6259       }
6260       if (!Alignment)
6261         Alignment =
6262             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6263 
6264       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6265                                 FailureOrdering, SSID);
6266       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6267       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6268 
6269       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6270       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6271 
6272       InstructionList.push_back(I);
6273       break;
6274     }
6275     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
6276     case bitc::FUNC_CODE_INST_ATOMICRMW: {
6277       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6278       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6279       const size_t NumRecords = Record.size();
6280       unsigned OpNum = 0;
6281 
6282       Value *Ptr = nullptr;
6283       unsigned PtrTypeID;
6284       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6285         return error("Invalid record");
6286 
6287       if (!isa<PointerType>(Ptr->getType()))
6288         return error("Invalid record");
6289 
6290       Value *Val = nullptr;
6291       unsigned ValTypeID = InvalidTypeID;
6292       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
6293         ValTypeID = getContainedTypeID(PtrTypeID);
6294         if (popValue(Record, OpNum, NextValueNo,
6295                      getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6296           return error("Invalid record");
6297       } else {
6298         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6299           return error("Invalid record");
6300       }
6301 
6302       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6303         return error("Invalid record");
6304 
6305       const AtomicRMWInst::BinOp Operation =
6306           getDecodedRMWOperation(Record[OpNum]);
6307       if (Operation < AtomicRMWInst::FIRST_BINOP ||
6308           Operation > AtomicRMWInst::LAST_BINOP)
6309         return error("Invalid record");
6310 
6311       const bool IsVol = Record[OpNum + 1];
6312 
6313       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6314       if (Ordering == AtomicOrdering::NotAtomic ||
6315           Ordering == AtomicOrdering::Unordered)
6316         return error("Invalid record");
6317 
6318       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6319 
6320       MaybeAlign Alignment;
6321 
6322       if (NumRecords == (OpNum + 5)) {
6323         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6324           return Err;
6325       }
6326 
6327       if (!Alignment)
6328         Alignment =
6329             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6330 
6331       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
6332       ResTypeID = ValTypeID;
6333       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6334 
6335       InstructionList.push_back(I);
6336       break;
6337     }
6338     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6339       if (2 != Record.size())
6340         return error("Invalid record");
6341       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
6342       if (Ordering == AtomicOrdering::NotAtomic ||
6343           Ordering == AtomicOrdering::Unordered ||
6344           Ordering == AtomicOrdering::Monotonic)
6345         return error("Invalid record");
6346       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
6347       I = new FenceInst(Context, Ordering, SSID);
6348       InstructionList.push_back(I);
6349       break;
6350     }
6351     case bitc::FUNC_CODE_INST_CALL: {
6352       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6353       if (Record.size() < 3)
6354         return error("Invalid record");
6355 
6356       unsigned OpNum = 0;
6357       AttributeList PAL = getAttributes(Record[OpNum++]);
6358       unsigned CCInfo = Record[OpNum++];
6359 
6360       FastMathFlags FMF;
6361       if ((CCInfo >> bitc::CALL_FMF) & 1) {
6362         FMF = getDecodedFastMathFlags(Record[OpNum++]);
6363         if (!FMF.any())
6364           return error("Fast math flags indicator set for call with no FMF");
6365       }
6366 
6367       unsigned FTyID = InvalidTypeID;
6368       FunctionType *FTy = nullptr;
6369       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6370         FTyID = Record[OpNum++];
6371         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6372         if (!FTy)
6373           return error("Explicit call type is not a function type");
6374       }
6375 
6376       Value *Callee;
6377       unsigned CalleeTypeID;
6378       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6379                            CurBB))
6380         return error("Invalid record");
6381 
6382       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6383       if (!OpTy)
6384         return error("Callee is not a pointer type");
6385       if (!FTy) {
6386         FTyID = getContainedTypeID(CalleeTypeID);
6387         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6388         if (!FTy)
6389           return error("Callee is not of pointer to function type");
6390       }
6391       if (Record.size() < FTy->getNumParams() + OpNum)
6392         return error("Insufficient operands to call");
6393 
6394       SmallVector<Value*, 16> Args;
6395       SmallVector<unsigned, 16> ArgTyIDs;
6396       // Read the fixed params.
6397       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6398         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6399         if (FTy->getParamType(i)->isLabelTy())
6400           Args.push_back(getBasicBlock(Record[OpNum]));
6401         else
6402           Args.push_back(getValue(Record, OpNum, NextValueNo,
6403                                   FTy->getParamType(i), ArgTyID, CurBB));
6404         ArgTyIDs.push_back(ArgTyID);
6405         if (!Args.back())
6406           return error("Invalid record");
6407       }
6408 
6409       // Read type/value pairs for varargs params.
6410       if (!FTy->isVarArg()) {
6411         if (OpNum != Record.size())
6412           return error("Invalid record");
6413       } else {
6414         while (OpNum != Record.size()) {
6415           Value *Op;
6416           unsigned OpTypeID;
6417           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6418             return error("Invalid record");
6419           Args.push_back(Op);
6420           ArgTyIDs.push_back(OpTypeID);
6421         }
6422       }
6423 
6424       // Upgrade the bundles if needed.
6425       if (!OperandBundles.empty())
6426         UpgradeOperandBundles(OperandBundles);
6427 
6428       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
6429       ResTypeID = getContainedTypeID(FTyID);
6430       OperandBundles.clear();
6431       InstructionList.push_back(I);
6432       cast<CallInst>(I)->setCallingConv(
6433           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6434       CallInst::TailCallKind TCK = CallInst::TCK_None;
6435       if (CCInfo & (1 << bitc::CALL_TAIL))
6436         TCK = CallInst::TCK_Tail;
6437       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6438         TCK = CallInst::TCK_MustTail;
6439       if (CCInfo & (1 << bitc::CALL_NOTAIL))
6440         TCK = CallInst::TCK_NoTail;
6441       cast<CallInst>(I)->setTailCallKind(TCK);
6442       cast<CallInst>(I)->setAttributes(PAL);
6443       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6444         I->deleteValue();
6445         return Err;
6446       }
6447       if (FMF.any()) {
6448         if (!isa<FPMathOperator>(I))
6449           return error("Fast-math-flags specified for call without "
6450                        "floating-point scalar or vector return type");
6451         I->setFastMathFlags(FMF);
6452       }
6453       break;
6454     }
6455     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6456       if (Record.size() < 3)
6457         return error("Invalid record");
6458       unsigned OpTyID = Record[0];
6459       Type *OpTy = getTypeByID(OpTyID);
6460       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6461       ResTypeID = Record[2];
6462       Type *ResTy = getTypeByID(ResTypeID);
6463       if (!OpTy || !Op || !ResTy)
6464         return error("Invalid record");
6465       I = new VAArgInst(Op, ResTy);
6466       InstructionList.push_back(I);
6467       break;
6468     }
6469 
6470     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
6471       // A call or an invoke can be optionally prefixed with some variable
6472       // number of operand bundle blocks.  These blocks are read into
6473       // OperandBundles and consumed at the next call or invoke instruction.
6474 
6475       if (Record.empty() || Record[0] >= BundleTags.size())
6476         return error("Invalid record");
6477 
6478       std::vector<Value *> Inputs;
6479 
6480       unsigned OpNum = 1;
6481       while (OpNum != Record.size()) {
6482         Value *Op;
6483         unsigned OpTypeID;
6484         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6485           return error("Invalid record");
6486         Inputs.push_back(Op);
6487       }
6488 
6489       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6490       continue;
6491     }
6492 
6493     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6494       unsigned OpNum = 0;
6495       Value *Op = nullptr;
6496       unsigned OpTypeID;
6497       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6498         return error("Invalid record");
6499       if (OpNum != Record.size())
6500         return error("Invalid record");
6501 
6502       I = new FreezeInst(Op);
6503       ResTypeID = OpTypeID;
6504       InstructionList.push_back(I);
6505       break;
6506     }
6507     }
6508 
6509     // Add instruction to end of current BB.  If there is no current BB, reject
6510     // this file.
6511     if (!CurBB) {
6512       I->deleteValue();
6513       return error("Invalid instruction with no BB");
6514     }
6515     if (!OperandBundles.empty()) {
6516       I->deleteValue();
6517       return error("Operand bundles found with no consumer");
6518     }
6519     I->insertInto(CurBB, CurBB->end());
6520 
6521     // If this was a terminator instruction, move to the next block.
6522     if (I->isTerminator()) {
6523       ++CurBBNo;
6524       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6525     }
6526 
6527     // Non-void values get registered in the value table for future use.
6528     if (!I->getType()->isVoidTy()) {
6529       assert(I->getType() == getTypeByID(ResTypeID) &&
6530              "Incorrect result type ID");
6531       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
6532         return Err;
6533     }
6534   }
6535 
6536 OutOfRecordLoop:
6537 
6538   if (!OperandBundles.empty())
6539     return error("Operand bundles found with no consumer");
6540 
6541   // Check the function list for unresolved values.
6542   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
6543     if (!A->getParent()) {
6544       // We found at least one unresolved value.  Nuke them all to avoid leaks.
6545       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
6546         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6547           A->replaceAllUsesWith(PoisonValue::get(A->getType()));
6548           delete A;
6549         }
6550       }
6551       return error("Never resolved value found in function");
6552     }
6553   }
6554 
6555   // Unexpected unresolved metadata about to be dropped.
6556   if (MDLoader->hasFwdRefs())
6557     return error("Invalid function metadata: outgoing forward refs");
6558 
6559   if (PhiConstExprBB)
6560     PhiConstExprBB->eraseFromParent();
6561 
6562   for (const auto &Pair : ConstExprEdgeBBs) {
6563     BasicBlock *From = Pair.first.first;
6564     BasicBlock *To = Pair.first.second;
6565     BasicBlock *EdgeBB = Pair.second;
6566     BranchInst::Create(To, EdgeBB);
6567     From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
6568     To->replacePhiUsesWith(From, EdgeBB);
6569     EdgeBB->moveBefore(To);
6570   }
6571 
6572   // Trim the value list down to the size it was before we parsed this function.
6573   ValueList.shrinkTo(ModuleValueListSize);
6574   MDLoader->shrinkTo(ModuleMDLoaderSize);
6575   std::vector<BasicBlock*>().swap(FunctionBBs);
6576   return Error::success();
6577 }
6578 
6579 /// Find the function body in the bitcode stream
6580 Error BitcodeReader::findFunctionInStream(
6581     Function *F,
6582     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
6583   while (DeferredFunctionInfoIterator->second == 0) {
6584     // This is the fallback handling for the old format bitcode that
6585     // didn't contain the function index in the VST, or when we have
6586     // an anonymous function which would not have a VST entry.
6587     // Assert that we have one of those two cases.
6588     assert(VSTOffset == 0 || !F->hasName());
6589     // Parse the next body in the stream and set its position in the
6590     // DeferredFunctionInfo map.
6591     if (Error Err = rememberAndSkipFunctionBodies())
6592       return Err;
6593   }
6594   return Error::success();
6595 }
6596 
6597 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
6598   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
6599     return SyncScope::ID(Val);
6600   if (Val >= SSIDs.size())
6601     return SyncScope::System; // Map unknown synchronization scopes to system.
6602   return SSIDs[Val];
6603 }
6604 
6605 //===----------------------------------------------------------------------===//
6606 // GVMaterializer implementation
6607 //===----------------------------------------------------------------------===//
6608 
6609 Error BitcodeReader::materialize(GlobalValue *GV) {
6610   Function *F = dyn_cast<Function>(GV);
6611   // If it's not a function or is already material, ignore the request.
6612   if (!F || !F->isMaterializable())
6613     return Error::success();
6614 
6615   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
6616   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
6617   // If its position is recorded as 0, its body is somewhere in the stream
6618   // but we haven't seen it yet.
6619   if (DFII->second == 0)
6620     if (Error Err = findFunctionInStream(F, DFII))
6621       return Err;
6622 
6623   // Materialize metadata before parsing any function bodies.
6624   if (Error Err = materializeMetadata())
6625     return Err;
6626 
6627   // Move the bit stream to the saved position of the deferred function body.
6628   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
6629     return JumpFailed;
6630   if (Error Err = parseFunctionBody(F))
6631     return Err;
6632   F->setIsMaterializable(false);
6633 
6634   if (StripDebugInfo)
6635     stripDebugInfo(*F);
6636 
6637   // Upgrade any old intrinsic calls in the function.
6638   for (auto &I : UpgradedIntrinsics) {
6639     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
6640       if (CallInst *CI = dyn_cast<CallInst>(U))
6641         UpgradeIntrinsicCall(CI, I.second);
6642   }
6643 
6644   // Finish fn->subprogram upgrade for materialized functions.
6645   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
6646     F->setSubprogram(SP);
6647 
6648   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
6649   if (!MDLoader->isStrippingTBAA()) {
6650     for (auto &I : instructions(F)) {
6651       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
6652       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
6653         continue;
6654       MDLoader->setStripTBAA(true);
6655       stripTBAA(F->getParent());
6656     }
6657   }
6658 
6659   for (auto &I : instructions(F)) {
6660     // "Upgrade" older incorrect branch weights by dropping them.
6661     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
6662       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
6663         MDString *MDS = cast<MDString>(MD->getOperand(0));
6664         StringRef ProfName = MDS->getString();
6665         // Check consistency of !prof branch_weights metadata.
6666         if (!ProfName.equals("branch_weights"))
6667           continue;
6668         unsigned ExpectedNumOperands = 0;
6669         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
6670           ExpectedNumOperands = BI->getNumSuccessors();
6671         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
6672           ExpectedNumOperands = SI->getNumSuccessors();
6673         else if (isa<CallInst>(&I))
6674           ExpectedNumOperands = 1;
6675         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
6676           ExpectedNumOperands = IBI->getNumDestinations();
6677         else if (isa<SelectInst>(&I))
6678           ExpectedNumOperands = 2;
6679         else
6680           continue; // ignore and continue.
6681 
6682         // If branch weight doesn't match, just strip branch weight.
6683         if (MD->getNumOperands() != 1 + ExpectedNumOperands)
6684           I.setMetadata(LLVMContext::MD_prof, nullptr);
6685       }
6686     }
6687 
6688     // Remove incompatible attributes on function calls.
6689     if (auto *CI = dyn_cast<CallBase>(&I)) {
6690       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
6691           CI->getFunctionType()->getReturnType()));
6692 
6693       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
6694         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
6695                                         CI->getArgOperand(ArgNo)->getType()));
6696     }
6697   }
6698 
6699   // Look for functions that rely on old function attribute behavior.
6700   UpgradeFunctionAttributes(*F);
6701 
6702   // Bring in any functions that this function forward-referenced via
6703   // blockaddresses.
6704   return materializeForwardReferencedFunctions();
6705 }
6706 
6707 Error BitcodeReader::materializeModule() {
6708   if (Error Err = materializeMetadata())
6709     return Err;
6710 
6711   // Promise to materialize all forward references.
6712   WillMaterializeAllForwardRefs = true;
6713 
6714   // Iterate over the module, deserializing any functions that are still on
6715   // disk.
6716   for (Function &F : *TheModule) {
6717     if (Error Err = materialize(&F))
6718       return Err;
6719   }
6720   // At this point, if there are any function bodies, parse the rest of
6721   // the bits in the module past the last function block we have recorded
6722   // through either lazy scanning or the VST.
6723   if (LastFunctionBlockBit || NextUnreadBit)
6724     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
6725                                     ? LastFunctionBlockBit
6726                                     : NextUnreadBit))
6727       return Err;
6728 
6729   // Check that all block address forward references got resolved (as we
6730   // promised above).
6731   if (!BasicBlockFwdRefs.empty())
6732     return error("Never resolved function from blockaddress");
6733 
6734   // Upgrade any intrinsic calls that slipped through (should not happen!) and
6735   // delete the old functions to clean up. We can't do this unless the entire
6736   // module is materialized because there could always be another function body
6737   // with calls to the old function.
6738   for (auto &I : UpgradedIntrinsics) {
6739     for (auto *U : I.first->users()) {
6740       if (CallInst *CI = dyn_cast<CallInst>(U))
6741         UpgradeIntrinsicCall(CI, I.second);
6742     }
6743     if (!I.first->use_empty())
6744       I.first->replaceAllUsesWith(I.second);
6745     I.first->eraseFromParent();
6746   }
6747   UpgradedIntrinsics.clear();
6748 
6749   UpgradeDebugInfo(*TheModule);
6750 
6751   UpgradeModuleFlags(*TheModule);
6752 
6753   UpgradeARCRuntime(*TheModule);
6754 
6755   return Error::success();
6756 }
6757 
6758 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
6759   return IdentifiedStructTypes;
6760 }
6761 
6762 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
6763     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
6764     StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
6765     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
6766       ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
6767 
6768 void ModuleSummaryIndexBitcodeReader::addThisModule() {
6769   TheIndex.addModule(ModulePath);
6770 }
6771 
6772 ModuleSummaryIndex::ModuleInfo *
6773 ModuleSummaryIndexBitcodeReader::getThisModule() {
6774   return TheIndex.getModule(ModulePath);
6775 }
6776 
6777 template <bool AllowNullValueInfo>
6778 std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
6779 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
6780   auto VGI = ValueIdToValueInfoMap[ValueId];
6781   // We can have a null value info for memprof callsite info records in
6782   // distributed ThinLTO index files when the callee function summary is not
6783   // included in the index. The bitcode writer records 0 in that case,
6784   // and the caller of this helper will set AllowNullValueInfo to true.
6785   assert(AllowNullValueInfo || std::get<0>(VGI));
6786   return VGI;
6787 }
6788 
6789 void ModuleSummaryIndexBitcodeReader::setValueGUID(
6790     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
6791     StringRef SourceFileName) {
6792   std::string GlobalId =
6793       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
6794   auto ValueGUID = GlobalValue::getGUID(GlobalId);
6795   auto OriginalNameID = ValueGUID;
6796   if (GlobalValue::isLocalLinkage(Linkage))
6797     OriginalNameID = GlobalValue::getGUID(ValueName);
6798   if (PrintSummaryGUIDs)
6799     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
6800            << ValueName << "\n";
6801 
6802   // UseStrtab is false for legacy summary formats and value names are
6803   // created on stack. In that case we save the name in a string saver in
6804   // the index so that the value name can be recorded.
6805   ValueIdToValueInfoMap[ValueID] = std::make_tuple(
6806       TheIndex.getOrInsertValueInfo(
6807           ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
6808       OriginalNameID, ValueGUID);
6809 }
6810 
6811 // Specialized value symbol table parser used when reading module index
6812 // blocks where we don't actually create global values. The parsed information
6813 // is saved in the bitcode reader for use when later parsing summaries.
6814 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
6815     uint64_t Offset,
6816     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
6817   // With a strtab the VST is not required to parse the summary.
6818   if (UseStrtab)
6819     return Error::success();
6820 
6821   assert(Offset > 0 && "Expected non-zero VST offset");
6822   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
6823   if (!MaybeCurrentBit)
6824     return MaybeCurrentBit.takeError();
6825   uint64_t CurrentBit = MaybeCurrentBit.get();
6826 
6827   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
6828     return Err;
6829 
6830   SmallVector<uint64_t, 64> Record;
6831 
6832   // Read all the records for this value table.
6833   SmallString<128> ValueName;
6834 
6835   while (true) {
6836     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
6837     if (!MaybeEntry)
6838       return MaybeEntry.takeError();
6839     BitstreamEntry Entry = MaybeEntry.get();
6840 
6841     switch (Entry.Kind) {
6842     case BitstreamEntry::SubBlock: // Handled for us already.
6843     case BitstreamEntry::Error:
6844       return error("Malformed block");
6845     case BitstreamEntry::EndBlock:
6846       // Done parsing VST, jump back to wherever we came from.
6847       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
6848         return JumpFailed;
6849       return Error::success();
6850     case BitstreamEntry::Record:
6851       // The interesting case.
6852       break;
6853     }
6854 
6855     // Read a record.
6856     Record.clear();
6857     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
6858     if (!MaybeRecord)
6859       return MaybeRecord.takeError();
6860     switch (MaybeRecord.get()) {
6861     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
6862       break;
6863     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
6864       if (convertToString(Record, 1, ValueName))
6865         return error("Invalid record");
6866       unsigned ValueID = Record[0];
6867       assert(!SourceFileName.empty());
6868       auto VLI = ValueIdToLinkageMap.find(ValueID);
6869       assert(VLI != ValueIdToLinkageMap.end() &&
6870              "No linkage found for VST entry?");
6871       auto Linkage = VLI->second;
6872       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6873       ValueName.clear();
6874       break;
6875     }
6876     case bitc::VST_CODE_FNENTRY: {
6877       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
6878       if (convertToString(Record, 2, ValueName))
6879         return error("Invalid record");
6880       unsigned ValueID = Record[0];
6881       assert(!SourceFileName.empty());
6882       auto VLI = ValueIdToLinkageMap.find(ValueID);
6883       assert(VLI != ValueIdToLinkageMap.end() &&
6884              "No linkage found for VST entry?");
6885       auto Linkage = VLI->second;
6886       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
6887       ValueName.clear();
6888       break;
6889     }
6890     case bitc::VST_CODE_COMBINED_ENTRY: {
6891       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
6892       unsigned ValueID = Record[0];
6893       GlobalValue::GUID RefGUID = Record[1];
6894       // The "original name", which is the second value of the pair will be
6895       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
6896       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
6897           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
6898       break;
6899     }
6900     }
6901   }
6902 }
6903 
6904 // Parse just the blocks needed for building the index out of the module.
6905 // At the end of this routine the module Index is populated with a map
6906 // from global value id to GlobalValueSummary objects.
6907 Error ModuleSummaryIndexBitcodeReader::parseModule() {
6908   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
6909     return Err;
6910 
6911   SmallVector<uint64_t, 64> Record;
6912   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
6913   unsigned ValueId = 0;
6914 
6915   // Read the index for this module.
6916   while (true) {
6917     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
6918     if (!MaybeEntry)
6919       return MaybeEntry.takeError();
6920     llvm::BitstreamEntry Entry = MaybeEntry.get();
6921 
6922     switch (Entry.Kind) {
6923     case BitstreamEntry::Error:
6924       return error("Malformed block");
6925     case BitstreamEntry::EndBlock:
6926       return Error::success();
6927 
6928     case BitstreamEntry::SubBlock:
6929       switch (Entry.ID) {
6930       default: // Skip unknown content.
6931         if (Error Err = Stream.SkipBlock())
6932           return Err;
6933         break;
6934       case bitc::BLOCKINFO_BLOCK_ID:
6935         // Need to parse these to get abbrev ids (e.g. for VST)
6936         if (Error Err = readBlockInfo())
6937           return Err;
6938         break;
6939       case bitc::VALUE_SYMTAB_BLOCK_ID:
6940         // Should have been parsed earlier via VSTOffset, unless there
6941         // is no summary section.
6942         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
6943                 !SeenGlobalValSummary) &&
6944                "Expected early VST parse via VSTOffset record");
6945         if (Error Err = Stream.SkipBlock())
6946           return Err;
6947         break;
6948       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
6949       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
6950         // Add the module if it is a per-module index (has a source file name).
6951         if (!SourceFileName.empty())
6952           addThisModule();
6953         assert(!SeenValueSymbolTable &&
6954                "Already read VST when parsing summary block?");
6955         // We might not have a VST if there were no values in the
6956         // summary. An empty summary block generated when we are
6957         // performing ThinLTO compiles so we don't later invoke
6958         // the regular LTO process on them.
6959         if (VSTOffset > 0) {
6960           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
6961             return Err;
6962           SeenValueSymbolTable = true;
6963         }
6964         SeenGlobalValSummary = true;
6965         if (Error Err = parseEntireSummary(Entry.ID))
6966           return Err;
6967         break;
6968       case bitc::MODULE_STRTAB_BLOCK_ID:
6969         if (Error Err = parseModuleStringTable())
6970           return Err;
6971         break;
6972       }
6973       continue;
6974 
6975     case BitstreamEntry::Record: {
6976         Record.clear();
6977         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
6978         if (!MaybeBitCode)
6979           return MaybeBitCode.takeError();
6980         switch (MaybeBitCode.get()) {
6981         default:
6982           break; // Default behavior, ignore unknown content.
6983         case bitc::MODULE_CODE_VERSION: {
6984           if (Error Err = parseVersionRecord(Record).takeError())
6985             return Err;
6986           break;
6987         }
6988         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
6989         case bitc::MODULE_CODE_SOURCE_FILENAME: {
6990           SmallString<128> ValueName;
6991           if (convertToString(Record, 0, ValueName))
6992             return error("Invalid record");
6993           SourceFileName = ValueName.c_str();
6994           break;
6995         }
6996         /// MODULE_CODE_HASH: [5*i32]
6997         case bitc::MODULE_CODE_HASH: {
6998           if (Record.size() != 5)
6999             return error("Invalid hash length " + Twine(Record.size()).str());
7000           auto &Hash = getThisModule()->second;
7001           int Pos = 0;
7002           for (auto &Val : Record) {
7003             assert(!(Val >> 32) && "Unexpected high bits set");
7004             Hash[Pos++] = Val;
7005           }
7006           break;
7007         }
7008         /// MODULE_CODE_VSTOFFSET: [offset]
7009         case bitc::MODULE_CODE_VSTOFFSET:
7010           if (Record.empty())
7011             return error("Invalid record");
7012           // Note that we subtract 1 here because the offset is relative to one
7013           // word before the start of the identification or module block, which
7014           // was historically always the start of the regular bitcode header.
7015           VSTOffset = Record[0] - 1;
7016           break;
7017         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
7018         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
7019         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
7020         // v2: [strtab offset, strtab size, v1]
7021         case bitc::MODULE_CODE_GLOBALVAR:
7022         case bitc::MODULE_CODE_FUNCTION:
7023         case bitc::MODULE_CODE_ALIAS: {
7024           StringRef Name;
7025           ArrayRef<uint64_t> GVRecord;
7026           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7027           if (GVRecord.size() <= 3)
7028             return error("Invalid record");
7029           uint64_t RawLinkage = GVRecord[3];
7030           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
7031           if (!UseStrtab) {
7032             ValueIdToLinkageMap[ValueId++] = Linkage;
7033             break;
7034           }
7035 
7036           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
7037           break;
7038         }
7039         }
7040       }
7041       continue;
7042     }
7043   }
7044 }
7045 
7046 std::vector<ValueInfo>
7047 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7048   std::vector<ValueInfo> Ret;
7049   Ret.reserve(Record.size());
7050   for (uint64_t RefValueId : Record)
7051     Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7052   return Ret;
7053 }
7054 
7055 std::vector<FunctionSummary::EdgeTy>
7056 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7057                                               bool IsOldProfileFormat,
7058                                               bool HasProfile, bool HasRelBF) {
7059   std::vector<FunctionSummary::EdgeTy> Ret;
7060   Ret.reserve(Record.size());
7061   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7062     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7063     bool HasTailCall = false;
7064     uint64_t RelBF = 0;
7065     ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7066     if (IsOldProfileFormat) {
7067       I += 1; // Skip old callsitecount field
7068       if (HasProfile)
7069         I += 1; // Skip old profilecount field
7070     } else if (HasProfile)
7071       std::tie(Hotness, HasTailCall) =
7072           getDecodedHotnessCallEdgeInfo(Record[++I]);
7073     else if (HasRelBF)
7074       getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7075     Ret.push_back(FunctionSummary::EdgeTy{
7076         Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
7077   }
7078   return Ret;
7079 }
7080 
7081 static void
7082 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
7083                                        WholeProgramDevirtResolution &Wpd) {
7084   uint64_t ArgNum = Record[Slot++];
7085   WholeProgramDevirtResolution::ByArg &B =
7086       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7087   Slot += ArgNum;
7088 
7089   B.TheKind =
7090       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
7091   B.Info = Record[Slot++];
7092   B.Byte = Record[Slot++];
7093   B.Bit = Record[Slot++];
7094 }
7095 
7096 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
7097                                               StringRef Strtab, size_t &Slot,
7098                                               TypeIdSummary &TypeId) {
7099   uint64_t Id = Record[Slot++];
7100   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7101 
7102   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7103   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7104                         static_cast<size_t>(Record[Slot + 1])};
7105   Slot += 2;
7106 
7107   uint64_t ResByArgNum = Record[Slot++];
7108   for (uint64_t I = 0; I != ResByArgNum; ++I)
7109     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
7110 }
7111 
7112 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
7113                                      StringRef Strtab,
7114                                      ModuleSummaryIndex &TheIndex) {
7115   size_t Slot = 0;
7116   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7117       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7118   Slot += 2;
7119 
7120   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7121   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7122   TypeId.TTRes.AlignLog2 = Record[Slot++];
7123   TypeId.TTRes.SizeM1 = Record[Slot++];
7124   TypeId.TTRes.BitMask = Record[Slot++];
7125   TypeId.TTRes.InlineBits = Record[Slot++];
7126 
7127   while (Slot < Record.size())
7128     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7129 }
7130 
7131 std::vector<FunctionSummary::ParamAccess>
7132 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7133   auto ReadRange = [&]() {
7134     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
7135                 BitcodeReader::decodeSignRotatedValue(Record.front()));
7136     Record = Record.drop_front();
7137     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
7138                 BitcodeReader::decodeSignRotatedValue(Record.front()));
7139     Record = Record.drop_front();
7140     ConstantRange Range{Lower, Upper};
7141     assert(!Range.isFullSet());
7142     assert(!Range.isUpperSignWrapped());
7143     return Range;
7144   };
7145 
7146   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7147   while (!Record.empty()) {
7148     PendingParamAccesses.emplace_back();
7149     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7150     ParamAccess.ParamNo = Record.front();
7151     Record = Record.drop_front();
7152     ParamAccess.Use = ReadRange();
7153     ParamAccess.Calls.resize(Record.front());
7154     Record = Record.drop_front();
7155     for (auto &Call : ParamAccess.Calls) {
7156       Call.ParamNo = Record.front();
7157       Record = Record.drop_front();
7158       Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
7159       Record = Record.drop_front();
7160       Call.Offsets = ReadRange();
7161     }
7162   }
7163   return PendingParamAccesses;
7164 }
7165 
7166 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7167     ArrayRef<uint64_t> Record, size_t &Slot,
7168     TypeIdCompatibleVtableInfo &TypeId) {
7169   uint64_t Offset = Record[Slot++];
7170   ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7171   TypeId.push_back({Offset, Callee});
7172 }
7173 
7174 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7175     ArrayRef<uint64_t> Record) {
7176   size_t Slot = 0;
7177   TypeIdCompatibleVtableInfo &TypeId =
7178       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
7179           {Strtab.data() + Record[Slot],
7180            static_cast<size_t>(Record[Slot + 1])});
7181   Slot += 2;
7182 
7183   while (Slot < Record.size())
7184     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7185 }
7186 
7187 static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
7188                            unsigned WOCnt) {
7189   // Readonly and writeonly refs are in the end of the refs list.
7190   assert(ROCnt + WOCnt <= Refs.size());
7191   unsigned FirstWORef = Refs.size() - WOCnt;
7192   unsigned RefNo = FirstWORef - ROCnt;
7193   for (; RefNo < FirstWORef; ++RefNo)
7194     Refs[RefNo].setReadOnly();
7195   for (; RefNo < Refs.size(); ++RefNo)
7196     Refs[RefNo].setWriteOnly();
7197 }
7198 
7199 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
7200 // objects in the index.
7201 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7202   if (Error Err = Stream.EnterSubBlock(ID))
7203     return Err;
7204   SmallVector<uint64_t, 64> Record;
7205 
7206   // Parse version
7207   {
7208     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7209     if (!MaybeEntry)
7210       return MaybeEntry.takeError();
7211     BitstreamEntry Entry = MaybeEntry.get();
7212 
7213     if (Entry.Kind != BitstreamEntry::Record)
7214       return error("Invalid Summary Block: record for version expected");
7215     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7216     if (!MaybeRecord)
7217       return MaybeRecord.takeError();
7218     if (MaybeRecord.get() != bitc::FS_VERSION)
7219       return error("Invalid Summary Block: version expected");
7220   }
7221   const uint64_t Version = Record[0];
7222   const bool IsOldProfileFormat = Version == 1;
7223   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
7224     return error("Invalid summary version " + Twine(Version) +
7225                  ". Version should be in the range [1-" +
7226                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7227                  "].");
7228   Record.clear();
7229 
7230   // Keep around the last seen summary to be used when we see an optional
7231   // "OriginalName" attachement.
7232   GlobalValueSummary *LastSeenSummary = nullptr;
7233   GlobalValue::GUID LastSeenGUID = 0;
7234 
7235   // We can expect to see any number of type ID information records before
7236   // each function summary records; these variables store the information
7237   // collected so far so that it can be used to create the summary object.
7238   std::vector<GlobalValue::GUID> PendingTypeTests;
7239   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7240       PendingTypeCheckedLoadVCalls;
7241   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7242       PendingTypeCheckedLoadConstVCalls;
7243   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7244 
7245   std::vector<CallsiteInfo> PendingCallsites;
7246   std::vector<AllocInfo> PendingAllocs;
7247 
7248   while (true) {
7249     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7250     if (!MaybeEntry)
7251       return MaybeEntry.takeError();
7252     BitstreamEntry Entry = MaybeEntry.get();
7253 
7254     switch (Entry.Kind) {
7255     case BitstreamEntry::SubBlock: // Handled for us already.
7256     case BitstreamEntry::Error:
7257       return error("Malformed block");
7258     case BitstreamEntry::EndBlock:
7259       return Error::success();
7260     case BitstreamEntry::Record:
7261       // The interesting case.
7262       break;
7263     }
7264 
7265     // Read a record. The record format depends on whether this
7266     // is a per-module index or a combined index file. In the per-module
7267     // case the records contain the associated value's ID for correlation
7268     // with VST entries. In the combined index the correlation is done
7269     // via the bitcode offset of the summary records (which were saved
7270     // in the combined index VST entries). The records also contain
7271     // information used for ThinLTO renaming and importing.
7272     Record.clear();
7273     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7274     if (!MaybeBitCode)
7275       return MaybeBitCode.takeError();
7276     switch (unsigned BitCode = MaybeBitCode.get()) {
7277     default: // Default behavior: ignore.
7278       break;
7279     case bitc::FS_FLAGS: {  // [flags]
7280       TheIndex.setFlags(Record[0]);
7281       break;
7282     }
7283     case bitc::FS_VALUE_GUID: { // [valueid, refguid]
7284       uint64_t ValueID = Record[0];
7285       GlobalValue::GUID RefGUID = Record[1];
7286       ValueIdToValueInfoMap[ValueID] = std::make_tuple(
7287           TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
7288       break;
7289     }
7290     // FS_PERMODULE is legacy and does not have support for the tail call flag.
7291     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7292     //                numrefs x valueid, n x (valueid)]
7293     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7294     //                        numrefs x valueid,
7295     //                        n x (valueid, hotness+tailcall flags)]
7296     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7297     //                      numrefs x valueid,
7298     //                      n x (valueid, relblockfreq+tailcall)]
7299     case bitc::FS_PERMODULE:
7300     case bitc::FS_PERMODULE_RELBF:
7301     case bitc::FS_PERMODULE_PROFILE: {
7302       unsigned ValueID = Record[0];
7303       uint64_t RawFlags = Record[1];
7304       unsigned InstCount = Record[2];
7305       uint64_t RawFunFlags = 0;
7306       unsigned NumRefs = Record[3];
7307       unsigned NumRORefs = 0, NumWORefs = 0;
7308       int RefListStartIndex = 4;
7309       if (Version >= 4) {
7310         RawFunFlags = Record[3];
7311         NumRefs = Record[4];
7312         RefListStartIndex = 5;
7313         if (Version >= 5) {
7314           NumRORefs = Record[5];
7315           RefListStartIndex = 6;
7316           if (Version >= 7) {
7317             NumWORefs = Record[6];
7318             RefListStartIndex = 7;
7319           }
7320         }
7321       }
7322 
7323       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7324       // The module path string ref set in the summary must be owned by the
7325       // index's module string table. Since we don't have a module path
7326       // string table section in the per-module index, we create a single
7327       // module path string table entry with an empty (0) ID to take
7328       // ownership.
7329       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7330       assert(Record.size() >= RefListStartIndex + NumRefs &&
7331              "Record size inconsistent with number of references");
7332       std::vector<ValueInfo> Refs = makeRefList(
7333           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7334       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7335       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7336       std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
7337           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7338           IsOldProfileFormat, HasProfile, HasRelBF);
7339       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7340       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7341       // In order to save memory, only record the memprof summaries if this is
7342       // the prevailing copy of a symbol. The linker doesn't resolve local
7343       // linkage values so don't check whether those are prevailing.
7344       auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7345       if (IsPrevailing &&
7346           !GlobalValue::isLocalLinkage(LT) &&
7347           !IsPrevailing(std::get<2>(VIAndOriginalGUID))) {
7348         PendingCallsites.clear();
7349         PendingAllocs.clear();
7350       }
7351       auto FS = std::make_unique<FunctionSummary>(
7352           Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
7353           std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
7354           std::move(PendingTypeTestAssumeVCalls),
7355           std::move(PendingTypeCheckedLoadVCalls),
7356           std::move(PendingTypeTestAssumeConstVCalls),
7357           std::move(PendingTypeCheckedLoadConstVCalls),
7358           std::move(PendingParamAccesses), std::move(PendingCallsites),
7359           std::move(PendingAllocs));
7360       FS->setModulePath(getThisModule()->first());
7361       FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7362       TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7363                                      std::move(FS));
7364       break;
7365     }
7366     // FS_ALIAS: [valueid, flags, valueid]
7367     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7368     // they expect all aliasee summaries to be available.
7369     case bitc::FS_ALIAS: {
7370       unsigned ValueID = Record[0];
7371       uint64_t RawFlags = Record[1];
7372       unsigned AliaseeID = Record[2];
7373       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7374       auto AS = std::make_unique<AliasSummary>(Flags);
7375       // The module path string ref set in the summary must be owned by the
7376       // index's module string table. Since we don't have a module path
7377       // string table section in the per-module index, we create a single
7378       // module path string table entry with an empty (0) ID to take
7379       // ownership.
7380       AS->setModulePath(getThisModule()->first());
7381 
7382       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7383       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7384       if (!AliaseeInModule)
7385         return error("Alias expects aliasee summary to be parsed");
7386       AS->setAliasee(AliaseeVI, AliaseeInModule);
7387 
7388       auto GUID = getValueInfoFromValueId(ValueID);
7389       AS->setOriginalName(std::get<1>(GUID));
7390       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
7391       break;
7392     }
7393     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7394     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
7395       unsigned ValueID = Record[0];
7396       uint64_t RawFlags = Record[1];
7397       unsigned RefArrayStart = 2;
7398       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7399                                       /* WriteOnly */ false,
7400                                       /* Constant */ false,
7401                                       GlobalObject::VCallVisibilityPublic);
7402       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7403       if (Version >= 5) {
7404         GVF = getDecodedGVarFlags(Record[2]);
7405         RefArrayStart = 3;
7406       }
7407       std::vector<ValueInfo> Refs =
7408           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7409       auto FS =
7410           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7411       FS->setModulePath(getThisModule()->first());
7412       auto GUID = getValueInfoFromValueId(ValueID);
7413       FS->setOriginalName(std::get<1>(GUID));
7414       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
7415       break;
7416     }
7417     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7418     //                        numrefs, numrefs x valueid,
7419     //                        n x (valueid, offset)]
7420     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
7421       unsigned ValueID = Record[0];
7422       uint64_t RawFlags = Record[1];
7423       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
7424       unsigned NumRefs = Record[3];
7425       unsigned RefListStartIndex = 4;
7426       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7427       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7428       std::vector<ValueInfo> Refs = makeRefList(
7429           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7430       VTableFuncList VTableFuncs;
7431       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7432         ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7433         uint64_t Offset = Record[++I];
7434         VTableFuncs.push_back({Callee, Offset});
7435       }
7436       auto VS =
7437           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7438       VS->setModulePath(getThisModule()->first());
7439       VS->setVTableFuncs(VTableFuncs);
7440       auto GUID = getValueInfoFromValueId(ValueID);
7441       VS->setOriginalName(std::get<1>(GUID));
7442       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
7443       break;
7444     }
7445     // FS_COMBINED is legacy and does not have support for the tail call flag.
7446     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7447     //               numrefs x valueid, n x (valueid)]
7448     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7449     //                       numrefs x valueid,
7450     //                       n x (valueid, hotness+tailcall flags)]
7451     case bitc::FS_COMBINED:
7452     case bitc::FS_COMBINED_PROFILE: {
7453       unsigned ValueID = Record[0];
7454       uint64_t ModuleId = Record[1];
7455       uint64_t RawFlags = Record[2];
7456       unsigned InstCount = Record[3];
7457       uint64_t RawFunFlags = 0;
7458       uint64_t EntryCount = 0;
7459       unsigned NumRefs = Record[4];
7460       unsigned NumRORefs = 0, NumWORefs = 0;
7461       int RefListStartIndex = 5;
7462 
7463       if (Version >= 4) {
7464         RawFunFlags = Record[4];
7465         RefListStartIndex = 6;
7466         size_t NumRefsIndex = 5;
7467         if (Version >= 5) {
7468           unsigned NumRORefsOffset = 1;
7469           RefListStartIndex = 7;
7470           if (Version >= 6) {
7471             NumRefsIndex = 6;
7472             EntryCount = Record[5];
7473             RefListStartIndex = 8;
7474             if (Version >= 7) {
7475               RefListStartIndex = 9;
7476               NumWORefs = Record[8];
7477               NumRORefsOffset = 2;
7478             }
7479           }
7480           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7481         }
7482         NumRefs = Record[NumRefsIndex];
7483       }
7484 
7485       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7486       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7487       assert(Record.size() >= RefListStartIndex + NumRefs &&
7488              "Record size inconsistent with number of references");
7489       std::vector<ValueInfo> Refs = makeRefList(
7490           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7491       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
7492       std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
7493           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7494           IsOldProfileFormat, HasProfile, false);
7495       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7496       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7497       auto FS = std::make_unique<FunctionSummary>(
7498           Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
7499           std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
7500           std::move(PendingTypeTestAssumeVCalls),
7501           std::move(PendingTypeCheckedLoadVCalls),
7502           std::move(PendingTypeTestAssumeConstVCalls),
7503           std::move(PendingTypeCheckedLoadConstVCalls),
7504           std::move(PendingParamAccesses), std::move(PendingCallsites),
7505           std::move(PendingAllocs));
7506       LastSeenSummary = FS.get();
7507       LastSeenGUID = VI.getGUID();
7508       FS->setModulePath(ModuleIdMap[ModuleId]);
7509       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7510       break;
7511     }
7512     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7513     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7514     // they expect all aliasee summaries to be available.
7515     case bitc::FS_COMBINED_ALIAS: {
7516       unsigned ValueID = Record[0];
7517       uint64_t ModuleId = Record[1];
7518       uint64_t RawFlags = Record[2];
7519       unsigned AliaseeValueId = Record[3];
7520       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7521       auto AS = std::make_unique<AliasSummary>(Flags);
7522       LastSeenSummary = AS.get();
7523       AS->setModulePath(ModuleIdMap[ModuleId]);
7524 
7525       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7526       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
7527       AS->setAliasee(AliaseeVI, AliaseeInModule);
7528 
7529       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7530       LastSeenGUID = VI.getGUID();
7531       TheIndex.addGlobalValueSummary(VI, std::move(AS));
7532       break;
7533     }
7534     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7535     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
7536       unsigned ValueID = Record[0];
7537       uint64_t ModuleId = Record[1];
7538       uint64_t RawFlags = Record[2];
7539       unsigned RefArrayStart = 3;
7540       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7541                                       /* WriteOnly */ false,
7542                                       /* Constant */ false,
7543                                       GlobalObject::VCallVisibilityPublic);
7544       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7545       if (Version >= 5) {
7546         GVF = getDecodedGVarFlags(Record[3]);
7547         RefArrayStart = 4;
7548       }
7549       std::vector<ValueInfo> Refs =
7550           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7551       auto FS =
7552           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7553       LastSeenSummary = FS.get();
7554       FS->setModulePath(ModuleIdMap[ModuleId]);
7555       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7556       LastSeenGUID = VI.getGUID();
7557       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7558       break;
7559     }
7560     // FS_COMBINED_ORIGINAL_NAME: [original_name]
7561     case bitc::FS_COMBINED_ORIGINAL_NAME: {
7562       uint64_t OriginalName = Record[0];
7563       if (!LastSeenSummary)
7564         return error("Name attachment that does not follow a combined record");
7565       LastSeenSummary->setOriginalName(OriginalName);
7566       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
7567       // Reset the LastSeenSummary
7568       LastSeenSummary = nullptr;
7569       LastSeenGUID = 0;
7570       break;
7571     }
7572     case bitc::FS_TYPE_TESTS:
7573       assert(PendingTypeTests.empty());
7574       llvm::append_range(PendingTypeTests, Record);
7575       break;
7576 
7577     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
7578       assert(PendingTypeTestAssumeVCalls.empty());
7579       for (unsigned I = 0; I != Record.size(); I += 2)
7580         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
7581       break;
7582 
7583     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
7584       assert(PendingTypeCheckedLoadVCalls.empty());
7585       for (unsigned I = 0; I != Record.size(); I += 2)
7586         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
7587       break;
7588 
7589     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
7590       PendingTypeTestAssumeConstVCalls.push_back(
7591           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
7592       break;
7593 
7594     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
7595       PendingTypeCheckedLoadConstVCalls.push_back(
7596           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
7597       break;
7598 
7599     case bitc::FS_CFI_FUNCTION_DEFS: {
7600       std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
7601       for (unsigned I = 0; I != Record.size(); I += 2)
7602         CfiFunctionDefs.insert(
7603             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
7604       break;
7605     }
7606 
7607     case bitc::FS_CFI_FUNCTION_DECLS: {
7608       std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
7609       for (unsigned I = 0; I != Record.size(); I += 2)
7610         CfiFunctionDecls.insert(
7611             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
7612       break;
7613     }
7614 
7615     case bitc::FS_TYPE_ID:
7616       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
7617       break;
7618 
7619     case bitc::FS_TYPE_ID_METADATA:
7620       parseTypeIdCompatibleVtableSummaryRecord(Record);
7621       break;
7622 
7623     case bitc::FS_BLOCK_COUNT:
7624       TheIndex.addBlockCount(Record[0]);
7625       break;
7626 
7627     case bitc::FS_PARAM_ACCESS: {
7628       PendingParamAccesses = parseParamAccesses(Record);
7629       break;
7630     }
7631 
7632     case bitc::FS_STACK_IDS: { // [n x stackid]
7633       // Save stack ids in the reader to consult when adding stack ids from the
7634       // lists in the stack node and alloc node entries.
7635       StackIds = ArrayRef<uint64_t>(Record);
7636       break;
7637     }
7638 
7639     case bitc::FS_PERMODULE_CALLSITE_INFO: {
7640       unsigned ValueID = Record[0];
7641       SmallVector<unsigned> StackIdList;
7642       for (auto R = Record.begin() + 1; R != Record.end(); R++) {
7643         assert(*R < StackIds.size());
7644         StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
7645       }
7646       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7647       PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
7648       break;
7649     }
7650 
7651     case bitc::FS_COMBINED_CALLSITE_INFO: {
7652       auto RecordIter = Record.begin();
7653       unsigned ValueID = *RecordIter++;
7654       unsigned NumStackIds = *RecordIter++;
7655       unsigned NumVersions = *RecordIter++;
7656       assert(Record.size() == 3 + NumStackIds + NumVersions);
7657       SmallVector<unsigned> StackIdList;
7658       for (unsigned J = 0; J < NumStackIds; J++) {
7659         assert(*RecordIter < StackIds.size());
7660         StackIdList.push_back(
7661             TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
7662       }
7663       SmallVector<unsigned> Versions;
7664       for (unsigned J = 0; J < NumVersions; J++)
7665         Versions.push_back(*RecordIter++);
7666       ValueInfo VI = std::get<0>(
7667           getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
7668       PendingCallsites.push_back(
7669           CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
7670       break;
7671     }
7672 
7673     case bitc::FS_PERMODULE_ALLOC_INFO: {
7674       unsigned I = 0;
7675       std::vector<MIBInfo> MIBs;
7676       while (I < Record.size()) {
7677         assert(Record.size() - I >= 2);
7678         AllocationType AllocType = (AllocationType)Record[I++];
7679         unsigned NumStackEntries = Record[I++];
7680         assert(Record.size() - I >= NumStackEntries);
7681         SmallVector<unsigned> StackIdList;
7682         for (unsigned J = 0; J < NumStackEntries; J++) {
7683           assert(Record[I] < StackIds.size());
7684           StackIdList.push_back(
7685               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7686         }
7687         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7688       }
7689       PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
7690       break;
7691     }
7692 
7693     case bitc::FS_COMBINED_ALLOC_INFO: {
7694       unsigned I = 0;
7695       std::vector<MIBInfo> MIBs;
7696       unsigned NumMIBs = Record[I++];
7697       unsigned NumVersions = Record[I++];
7698       unsigned MIBsRead = 0;
7699       while (MIBsRead++ < NumMIBs) {
7700         assert(Record.size() - I >= 2);
7701         AllocationType AllocType = (AllocationType)Record[I++];
7702         unsigned NumStackEntries = Record[I++];
7703         assert(Record.size() - I >= NumStackEntries);
7704         SmallVector<unsigned> StackIdList;
7705         for (unsigned J = 0; J < NumStackEntries; J++) {
7706           assert(Record[I] < StackIds.size());
7707           StackIdList.push_back(
7708               TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7709         }
7710         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
7711       }
7712       assert(Record.size() - I >= NumVersions);
7713       SmallVector<uint8_t> Versions;
7714       for (unsigned J = 0; J < NumVersions; J++)
7715         Versions.push_back(Record[I++]);
7716       PendingAllocs.push_back(
7717           AllocInfo(std::move(Versions), std::move(MIBs)));
7718       break;
7719     }
7720     }
7721   }
7722   llvm_unreachable("Exit infinite loop");
7723 }
7724 
7725 // Parse the  module string table block into the Index.
7726 // This populates the ModulePathStringTable map in the index.
7727 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
7728   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
7729     return Err;
7730 
7731   SmallVector<uint64_t, 64> Record;
7732 
7733   SmallString<128> ModulePath;
7734   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
7735 
7736   while (true) {
7737     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7738     if (!MaybeEntry)
7739       return MaybeEntry.takeError();
7740     BitstreamEntry Entry = MaybeEntry.get();
7741 
7742     switch (Entry.Kind) {
7743     case BitstreamEntry::SubBlock: // Handled for us already.
7744     case BitstreamEntry::Error:
7745       return error("Malformed block");
7746     case BitstreamEntry::EndBlock:
7747       return Error::success();
7748     case BitstreamEntry::Record:
7749       // The interesting case.
7750       break;
7751     }
7752 
7753     Record.clear();
7754     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7755     if (!MaybeRecord)
7756       return MaybeRecord.takeError();
7757     switch (MaybeRecord.get()) {
7758     default: // Default behavior: ignore.
7759       break;
7760     case bitc::MST_CODE_ENTRY: {
7761       // MST_ENTRY: [modid, namechar x N]
7762       uint64_t ModuleId = Record[0];
7763 
7764       if (convertToString(Record, 1, ModulePath))
7765         return error("Invalid record");
7766 
7767       LastSeenModule = TheIndex.addModule(ModulePath);
7768       ModuleIdMap[ModuleId] = LastSeenModule->first();
7769 
7770       ModulePath.clear();
7771       break;
7772     }
7773     /// MST_CODE_HASH: [5*i32]
7774     case bitc::MST_CODE_HASH: {
7775       if (Record.size() != 5)
7776         return error("Invalid hash length " + Twine(Record.size()).str());
7777       if (!LastSeenModule)
7778         return error("Invalid hash that does not follow a module path");
7779       int Pos = 0;
7780       for (auto &Val : Record) {
7781         assert(!(Val >> 32) && "Unexpected high bits set");
7782         LastSeenModule->second[Pos++] = Val;
7783       }
7784       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
7785       LastSeenModule = nullptr;
7786       break;
7787     }
7788     }
7789   }
7790   llvm_unreachable("Exit infinite loop");
7791 }
7792 
7793 namespace {
7794 
7795 // FIXME: This class is only here to support the transition to llvm::Error. It
7796 // will be removed once this transition is complete. Clients should prefer to
7797 // deal with the Error value directly, rather than converting to error_code.
7798 class BitcodeErrorCategoryType : public std::error_category {
7799   const char *name() const noexcept override {
7800     return "llvm.bitcode";
7801   }
7802 
7803   std::string message(int IE) const override {
7804     BitcodeError E = static_cast<BitcodeError>(IE);
7805     switch (E) {
7806     case BitcodeError::CorruptedBitcode:
7807       return "Corrupted bitcode";
7808     }
7809     llvm_unreachable("Unknown error type!");
7810   }
7811 };
7812 
7813 } // end anonymous namespace
7814 
7815 const std::error_category &llvm::BitcodeErrorCategory() {
7816   static BitcodeErrorCategoryType ErrorCategory;
7817   return ErrorCategory;
7818 }
7819 
7820 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
7821                                             unsigned Block, unsigned RecordID) {
7822   if (Error Err = Stream.EnterSubBlock(Block))
7823     return std::move(Err);
7824 
7825   StringRef Strtab;
7826   while (true) {
7827     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7828     if (!MaybeEntry)
7829       return MaybeEntry.takeError();
7830     llvm::BitstreamEntry Entry = MaybeEntry.get();
7831 
7832     switch (Entry.Kind) {
7833     case BitstreamEntry::EndBlock:
7834       return Strtab;
7835 
7836     case BitstreamEntry::Error:
7837       return error("Malformed block");
7838 
7839     case BitstreamEntry::SubBlock:
7840       if (Error Err = Stream.SkipBlock())
7841         return std::move(Err);
7842       break;
7843 
7844     case BitstreamEntry::Record:
7845       StringRef Blob;
7846       SmallVector<uint64_t, 1> Record;
7847       Expected<unsigned> MaybeRecord =
7848           Stream.readRecord(Entry.ID, Record, &Blob);
7849       if (!MaybeRecord)
7850         return MaybeRecord.takeError();
7851       if (MaybeRecord.get() == RecordID)
7852         Strtab = Blob;
7853       break;
7854     }
7855   }
7856 }
7857 
7858 //===----------------------------------------------------------------------===//
7859 // External interface
7860 //===----------------------------------------------------------------------===//
7861 
7862 Expected<std::vector<BitcodeModule>>
7863 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
7864   auto FOrErr = getBitcodeFileContents(Buffer);
7865   if (!FOrErr)
7866     return FOrErr.takeError();
7867   return std::move(FOrErr->Mods);
7868 }
7869 
7870 Expected<BitcodeFileContents>
7871 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
7872   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
7873   if (!StreamOrErr)
7874     return StreamOrErr.takeError();
7875   BitstreamCursor &Stream = *StreamOrErr;
7876 
7877   BitcodeFileContents F;
7878   while (true) {
7879     uint64_t BCBegin = Stream.getCurrentByteNo();
7880 
7881     // We may be consuming bitcode from a client that leaves garbage at the end
7882     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
7883     // the end that there cannot possibly be another module, stop looking.
7884     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
7885       return F;
7886 
7887     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7888     if (!MaybeEntry)
7889       return MaybeEntry.takeError();
7890     llvm::BitstreamEntry Entry = MaybeEntry.get();
7891 
7892     switch (Entry.Kind) {
7893     case BitstreamEntry::EndBlock:
7894     case BitstreamEntry::Error:
7895       return error("Malformed block");
7896 
7897     case BitstreamEntry::SubBlock: {
7898       uint64_t IdentificationBit = -1ull;
7899       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
7900         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7901         if (Error Err = Stream.SkipBlock())
7902           return std::move(Err);
7903 
7904         {
7905           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7906           if (!MaybeEntry)
7907             return MaybeEntry.takeError();
7908           Entry = MaybeEntry.get();
7909         }
7910 
7911         if (Entry.Kind != BitstreamEntry::SubBlock ||
7912             Entry.ID != bitc::MODULE_BLOCK_ID)
7913           return error("Malformed block");
7914       }
7915 
7916       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
7917         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
7918         if (Error Err = Stream.SkipBlock())
7919           return std::move(Err);
7920 
7921         F.Mods.push_back({Stream.getBitcodeBytes().slice(
7922                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
7923                           Buffer.getBufferIdentifier(), IdentificationBit,
7924                           ModuleBit});
7925         continue;
7926       }
7927 
7928       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
7929         Expected<StringRef> Strtab =
7930             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
7931         if (!Strtab)
7932           return Strtab.takeError();
7933         // This string table is used by every preceding bitcode module that does
7934         // not have its own string table. A bitcode file may have multiple
7935         // string tables if it was created by binary concatenation, for example
7936         // with "llvm-cat -b".
7937         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
7938           if (!I.Strtab.empty())
7939             break;
7940           I.Strtab = *Strtab;
7941         }
7942         // Similarly, the string table is used by every preceding symbol table;
7943         // normally there will be just one unless the bitcode file was created
7944         // by binary concatenation.
7945         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
7946           F.StrtabForSymtab = *Strtab;
7947         continue;
7948       }
7949 
7950       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
7951         Expected<StringRef> SymtabOrErr =
7952             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
7953         if (!SymtabOrErr)
7954           return SymtabOrErr.takeError();
7955 
7956         // We can expect the bitcode file to have multiple symbol tables if it
7957         // was created by binary concatenation. In that case we silently
7958         // ignore any subsequent symbol tables, which is fine because this is a
7959         // low level function. The client is expected to notice that the number
7960         // of modules in the symbol table does not match the number of modules
7961         // in the input file and regenerate the symbol table.
7962         if (F.Symtab.empty())
7963           F.Symtab = *SymtabOrErr;
7964         continue;
7965       }
7966 
7967       if (Error Err = Stream.SkipBlock())
7968         return std::move(Err);
7969       continue;
7970     }
7971     case BitstreamEntry::Record:
7972       if (Error E = Stream.skipRecord(Entry.ID).takeError())
7973         return std::move(E);
7974       continue;
7975     }
7976   }
7977 }
7978 
7979 /// Get a lazy one-at-time loading module from bitcode.
7980 ///
7981 /// This isn't always used in a lazy context.  In particular, it's also used by
7982 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
7983 /// in forward-referenced functions from block address references.
7984 ///
7985 /// \param[in] MaterializeAll Set to \c true if we should materialize
7986 /// everything.
7987 Expected<std::unique_ptr<Module>>
7988 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
7989                              bool ShouldLazyLoadMetadata, bool IsImporting,
7990                              ParserCallbacks Callbacks) {
7991   BitstreamCursor Stream(Buffer);
7992 
7993   std::string ProducerIdentification;
7994   if (IdentificationBit != -1ull) {
7995     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
7996       return std::move(JumpFailed);
7997     if (Error E =
7998             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
7999       return std::move(E);
8000   }
8001 
8002   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8003     return std::move(JumpFailed);
8004   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8005                               Context);
8006 
8007   std::unique_ptr<Module> M =
8008       std::make_unique<Module>(ModuleIdentifier, Context);
8009   M->setMaterializer(R);
8010 
8011   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8012   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8013                                       IsImporting, Callbacks))
8014     return std::move(Err);
8015 
8016   if (MaterializeAll) {
8017     // Read in the entire module, and destroy the BitcodeReader.
8018     if (Error Err = M->materializeAll())
8019       return std::move(Err);
8020   } else {
8021     // Resolve forward references from blockaddresses.
8022     if (Error Err = R->materializeForwardReferencedFunctions())
8023       return std::move(Err);
8024   }
8025   return std::move(M);
8026 }
8027 
8028 Expected<std::unique_ptr<Module>>
8029 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8030                              bool IsImporting, ParserCallbacks Callbacks) {
8031   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8032                        Callbacks);
8033 }
8034 
8035 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
8036 // We don't use ModuleIdentifier here because the client may need to control the
8037 // module path used in the combined summary (e.g. when reading summaries for
8038 // regular LTO modules).
8039 Error BitcodeModule::readSummary(
8040     ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8041     std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8042   BitstreamCursor Stream(Buffer);
8043   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8044     return JumpFailed;
8045 
8046   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8047                                     ModulePath, IsPrevailing);
8048   return R.parseModule();
8049 }
8050 
8051 // Parse the specified bitcode buffer, returning the function info index.
8052 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
8053   BitstreamCursor Stream(Buffer);
8054   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8055     return std::move(JumpFailed);
8056 
8057   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
8058   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8059                                     ModuleIdentifier, 0);
8060 
8061   if (Error Err = R.parseModule())
8062     return std::move(Err);
8063 
8064   return std::move(Index);
8065 }
8066 
8067 static Expected<std::pair<bool, bool>>
8068 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream,
8069                                                  unsigned ID,
8070                                                  BitcodeLTOInfo &LTOInfo) {
8071   if (Error Err = Stream.EnterSubBlock(ID))
8072     return std::move(Err);
8073   SmallVector<uint64_t, 64> Record;
8074 
8075   while (true) {
8076     BitstreamEntry Entry;
8077     std::pair<bool, bool> Result = {false,false};
8078     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8079       return std::move(E);
8080 
8081     switch (Entry.Kind) {
8082     case BitstreamEntry::SubBlock: // Handled for us already.
8083     case BitstreamEntry::Error:
8084       return error("Malformed block");
8085     case BitstreamEntry::EndBlock: {
8086       // If no flags record found, set both flags to false.
8087       return Result;
8088     }
8089     case BitstreamEntry::Record:
8090       // The interesting case.
8091       break;
8092     }
8093 
8094     // Look for the FS_FLAGS record.
8095     Record.clear();
8096     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
8097     if (!MaybeBitCode)
8098       return MaybeBitCode.takeError();
8099     switch (MaybeBitCode.get()) {
8100     default: // Default behavior: ignore.
8101       break;
8102     case bitc::FS_FLAGS: { // [flags]
8103       uint64_t Flags = Record[0];
8104       // Scan flags.
8105       assert(Flags <= 0x2ff && "Unexpected bits in flag");
8106 
8107       bool EnableSplitLTOUnit = Flags & 0x8;
8108       bool UnifiedLTO = Flags & 0x200;
8109       Result = {EnableSplitLTOUnit, UnifiedLTO};
8110 
8111       return Result;
8112     }
8113     }
8114   }
8115   llvm_unreachable("Exit infinite loop");
8116 }
8117 
8118 // Check if the given bitcode buffer contains a global value summary block.
8119 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
8120   BitstreamCursor Stream(Buffer);
8121   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8122     return std::move(JumpFailed);
8123 
8124   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
8125     return std::move(Err);
8126 
8127   while (true) {
8128     llvm::BitstreamEntry Entry;
8129     if (Error E = Stream.advance().moveInto(Entry))
8130       return std::move(E);
8131 
8132     switch (Entry.Kind) {
8133     case BitstreamEntry::Error:
8134       return error("Malformed block");
8135     case BitstreamEntry::EndBlock:
8136       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8137                             /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8138 
8139     case BitstreamEntry::SubBlock:
8140       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
8141         BitcodeLTOInfo LTOInfo;
8142         Expected<std::pair<bool, bool>> Flags =
8143             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8144         if (!Flags)
8145           return Flags.takeError();
8146         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8147         LTOInfo.IsThinLTO = true;
8148         LTOInfo.HasSummary = true;
8149         return LTOInfo;
8150       }
8151 
8152       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
8153         BitcodeLTOInfo LTOInfo;
8154         Expected<std::pair<bool, bool>> Flags =
8155             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8156         if (!Flags)
8157           return Flags.takeError();
8158         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8159         LTOInfo.IsThinLTO = false;
8160         LTOInfo.HasSummary = true;
8161         return LTOInfo;
8162       }
8163 
8164       // Ignore other sub-blocks.
8165       if (Error Err = Stream.SkipBlock())
8166         return std::move(Err);
8167       continue;
8168 
8169     case BitstreamEntry::Record:
8170       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
8171         continue;
8172       else
8173         return StreamFailed.takeError();
8174     }
8175   }
8176 }
8177 
8178 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
8179   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
8180   if (!MsOrErr)
8181     return MsOrErr.takeError();
8182 
8183   if (MsOrErr->size() != 1)
8184     return error("Expected a single module");
8185 
8186   return (*MsOrErr)[0];
8187 }
8188 
8189 Expected<std::unique_ptr<Module>>
8190 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8191                            bool ShouldLazyLoadMetadata, bool IsImporting,
8192                            ParserCallbacks Callbacks) {
8193   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8194   if (!BM)
8195     return BM.takeError();
8196 
8197   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8198                            Callbacks);
8199 }
8200 
8201 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
8202     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8203     bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8204   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8205                                      IsImporting, Callbacks);
8206   if (MOrErr)
8207     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8208   return MOrErr;
8209 }
8210 
8211 Expected<std::unique_ptr<Module>>
8212 BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8213   return getModuleImpl(Context, true, false, false, Callbacks);
8214   // TODO: Restore the use-lists to the in-memory state when the bitcode was
8215   // written.  We must defer until the Module has been fully materialized.
8216 }
8217 
8218 Expected<std::unique_ptr<Module>>
8219 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8220                        ParserCallbacks Callbacks) {
8221   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8222   if (!BM)
8223     return BM.takeError();
8224 
8225   return BM->parseModule(Context, Callbacks);
8226 }
8227 
8228 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
8229   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8230   if (!StreamOrErr)
8231     return StreamOrErr.takeError();
8232 
8233   return readTriple(*StreamOrErr);
8234 }
8235 
8236 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
8237   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8238   if (!StreamOrErr)
8239     return StreamOrErr.takeError();
8240 
8241   return hasObjCCategory(*StreamOrErr);
8242 }
8243 
8244 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
8245   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8246   if (!StreamOrErr)
8247     return StreamOrErr.takeError();
8248 
8249   return readIdentificationCode(*StreamOrErr);
8250 }
8251 
8252 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
8253                                    ModuleSummaryIndex &CombinedIndex) {
8254   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8255   if (!BM)
8256     return BM.takeError();
8257 
8258   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8259 }
8260 
8261 Expected<std::unique_ptr<ModuleSummaryIndex>>
8262 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
8263   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8264   if (!BM)
8265     return BM.takeError();
8266 
8267   return BM->getSummary();
8268 }
8269 
8270 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
8271   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8272   if (!BM)
8273     return BM.takeError();
8274 
8275   return BM->getLTOInfo();
8276 }
8277 
8278 Expected<std::unique_ptr<ModuleSummaryIndex>>
8279 llvm::getModuleSummaryIndexForFile(StringRef Path,
8280                                    bool IgnoreEmptyThinLTOIndexFile) {
8281   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
8282       MemoryBuffer::getFileOrSTDIN(Path);
8283   if (!FileOrErr)
8284     return errorCodeToError(FileOrErr.getError());
8285   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8286     return nullptr;
8287   return getModuleSummaryIndex(**FileOrErr);
8288 }
8289