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