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