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