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