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