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