xref: /llvm-project/llvm/lib/Bitcode/Reader/BitcodeReader.cpp (revision 98204a2e5bb754b0260175e42614c5463807beb5)
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       }
5201 
5202       InstructionList.push_back(I);
5203       break;
5204     }
5205     case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
5206     case bitc::FUNC_CODE_INST_GEP_OLD:
5207     case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
5208       unsigned OpNum = 0;
5209 
5210       unsigned TyID;
5211       Type *Ty;
5212       GEPNoWrapFlags NW;
5213 
5214       if (BitCode == bitc::FUNC_CODE_INST_GEP) {
5215         NW = toGEPNoWrapFlags(Record[OpNum++]);
5216         TyID = Record[OpNum++];
5217         Ty = getTypeByID(TyID);
5218       } else {
5219         if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD)
5220           NW = GEPNoWrapFlags::inBounds();
5221         TyID = InvalidTypeID;
5222         Ty = nullptr;
5223       }
5224 
5225       Value *BasePtr;
5226       unsigned BasePtrTypeID;
5227       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
5228                            CurBB))
5229         return error("Invalid record");
5230 
5231       if (!Ty) {
5232         TyID = getContainedTypeID(BasePtrTypeID);
5233         if (BasePtr->getType()->isVectorTy())
5234           TyID = getContainedTypeID(TyID);
5235         Ty = getTypeByID(TyID);
5236       }
5237 
5238       SmallVector<Value*, 16> GEPIdx;
5239       while (OpNum != Record.size()) {
5240         Value *Op;
5241         unsigned OpTypeID;
5242         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5243           return error("Invalid record");
5244         GEPIdx.push_back(Op);
5245       }
5246 
5247       auto *GEP = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
5248       I = GEP;
5249 
5250       ResTypeID = TyID;
5251       if (cast<GEPOperator>(I)->getNumIndices() != 0) {
5252         auto GTI = std::next(gep_type_begin(I));
5253         for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
5254           unsigned SubType = 0;
5255           if (GTI.isStruct()) {
5256             ConstantInt *IdxC =
5257                 Idx->getType()->isVectorTy()
5258                     ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
5259                     : cast<ConstantInt>(Idx);
5260             SubType = IdxC->getZExtValue();
5261           }
5262           ResTypeID = getContainedTypeID(ResTypeID, SubType);
5263           ++GTI;
5264         }
5265       }
5266 
5267       // At this point ResTypeID is the result element type. We need a pointer
5268       // or vector of pointer to it.
5269       ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
5270       if (I->getType()->isVectorTy())
5271         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5272 
5273       InstructionList.push_back(I);
5274       GEP->setNoWrapFlags(NW);
5275       break;
5276     }
5277 
5278     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
5279                                        // EXTRACTVAL: [opty, opval, n x indices]
5280       unsigned OpNum = 0;
5281       Value *Agg;
5282       unsigned AggTypeID;
5283       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5284         return error("Invalid record");
5285       Type *Ty = Agg->getType();
5286 
5287       unsigned RecSize = Record.size();
5288       if (OpNum == RecSize)
5289         return error("EXTRACTVAL: Invalid instruction with 0 indices");
5290 
5291       SmallVector<unsigned, 4> EXTRACTVALIdx;
5292       ResTypeID = AggTypeID;
5293       for (; OpNum != RecSize; ++OpNum) {
5294         bool IsArray = Ty->isArrayTy();
5295         bool IsStruct = Ty->isStructTy();
5296         uint64_t Index = Record[OpNum];
5297 
5298         if (!IsStruct && !IsArray)
5299           return error("EXTRACTVAL: Invalid type");
5300         if ((unsigned)Index != Index)
5301           return error("Invalid value");
5302         if (IsStruct && Index >= Ty->getStructNumElements())
5303           return error("EXTRACTVAL: Invalid struct index");
5304         if (IsArray && Index >= Ty->getArrayNumElements())
5305           return error("EXTRACTVAL: Invalid array index");
5306         EXTRACTVALIdx.push_back((unsigned)Index);
5307 
5308         if (IsStruct) {
5309           Ty = Ty->getStructElementType(Index);
5310           ResTypeID = getContainedTypeID(ResTypeID, Index);
5311         } else {
5312           Ty = Ty->getArrayElementType();
5313           ResTypeID = getContainedTypeID(ResTypeID);
5314         }
5315       }
5316 
5317       I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
5318       InstructionList.push_back(I);
5319       break;
5320     }
5321 
5322     case bitc::FUNC_CODE_INST_INSERTVAL: {
5323                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
5324       unsigned OpNum = 0;
5325       Value *Agg;
5326       unsigned AggTypeID;
5327       if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
5328         return error("Invalid record");
5329       Value *Val;
5330       unsigned ValTypeID;
5331       if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
5332         return error("Invalid record");
5333 
5334       unsigned RecSize = Record.size();
5335       if (OpNum == RecSize)
5336         return error("INSERTVAL: Invalid instruction with 0 indices");
5337 
5338       SmallVector<unsigned, 4> INSERTVALIdx;
5339       Type *CurTy = Agg->getType();
5340       for (; OpNum != RecSize; ++OpNum) {
5341         bool IsArray = CurTy->isArrayTy();
5342         bool IsStruct = CurTy->isStructTy();
5343         uint64_t Index = Record[OpNum];
5344 
5345         if (!IsStruct && !IsArray)
5346           return error("INSERTVAL: Invalid type");
5347         if ((unsigned)Index != Index)
5348           return error("Invalid value");
5349         if (IsStruct && Index >= CurTy->getStructNumElements())
5350           return error("INSERTVAL: Invalid struct index");
5351         if (IsArray && Index >= CurTy->getArrayNumElements())
5352           return error("INSERTVAL: Invalid array index");
5353 
5354         INSERTVALIdx.push_back((unsigned)Index);
5355         if (IsStruct)
5356           CurTy = CurTy->getStructElementType(Index);
5357         else
5358           CurTy = CurTy->getArrayElementType();
5359       }
5360 
5361       if (CurTy != Val->getType())
5362         return error("Inserted value type doesn't match aggregate type");
5363 
5364       I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
5365       ResTypeID = AggTypeID;
5366       InstructionList.push_back(I);
5367       break;
5368     }
5369 
5370     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
5371       // obsolete form of select
5372       // handles select i1 ... in old bitcode
5373       unsigned OpNum = 0;
5374       Value *TrueVal, *FalseVal, *Cond;
5375       unsigned TypeID;
5376       Type *CondType = Type::getInt1Ty(Context);
5377       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
5378                            CurBB) ||
5379           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
5380                    FalseVal, CurBB) ||
5381           popValue(Record, OpNum, NextValueNo, CondType,
5382                    getVirtualTypeID(CondType), Cond, CurBB))
5383         return error("Invalid record");
5384 
5385       I = SelectInst::Create(Cond, TrueVal, FalseVal);
5386       ResTypeID = TypeID;
5387       InstructionList.push_back(I);
5388       break;
5389     }
5390 
5391     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
5392       // new form of select
5393       // handles select i1 or select [N x i1]
5394       unsigned OpNum = 0;
5395       Value *TrueVal, *FalseVal, *Cond;
5396       unsigned ValTypeID, CondTypeID;
5397       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
5398                            CurBB) ||
5399           popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
5400                    FalseVal, CurBB) ||
5401           getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
5402         return error("Invalid record");
5403 
5404       // select condition can be either i1 or [N x i1]
5405       if (VectorType* vector_type =
5406           dyn_cast<VectorType>(Cond->getType())) {
5407         // expect <n x i1>
5408         if (vector_type->getElementType() != Type::getInt1Ty(Context))
5409           return error("Invalid type for value");
5410       } else {
5411         // expect i1
5412         if (Cond->getType() != Type::getInt1Ty(Context))
5413           return error("Invalid type for value");
5414       }
5415 
5416       I = SelectInst::Create(Cond, TrueVal, FalseVal);
5417       ResTypeID = ValTypeID;
5418       InstructionList.push_back(I);
5419       if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
5420         FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
5421         if (FMF.any())
5422           I->setFastMathFlags(FMF);
5423       }
5424       break;
5425     }
5426 
5427     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
5428       unsigned OpNum = 0;
5429       Value *Vec, *Idx;
5430       unsigned VecTypeID, IdxTypeID;
5431       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
5432           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5433         return error("Invalid record");
5434       if (!Vec->getType()->isVectorTy())
5435         return error("Invalid type for value");
5436       I = ExtractElementInst::Create(Vec, Idx);
5437       ResTypeID = getContainedTypeID(VecTypeID);
5438       InstructionList.push_back(I);
5439       break;
5440     }
5441 
5442     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
5443       unsigned OpNum = 0;
5444       Value *Vec, *Elt, *Idx;
5445       unsigned VecTypeID, IdxTypeID;
5446       if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
5447         return error("Invalid record");
5448       if (!Vec->getType()->isVectorTy())
5449         return error("Invalid type for value");
5450       if (popValue(Record, OpNum, NextValueNo,
5451                    cast<VectorType>(Vec->getType())->getElementType(),
5452                    getContainedTypeID(VecTypeID), Elt, CurBB) ||
5453           getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
5454         return error("Invalid record");
5455       I = InsertElementInst::Create(Vec, Elt, Idx);
5456       ResTypeID = VecTypeID;
5457       InstructionList.push_back(I);
5458       break;
5459     }
5460 
5461     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
5462       unsigned OpNum = 0;
5463       Value *Vec1, *Vec2, *Mask;
5464       unsigned Vec1TypeID;
5465       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
5466                            CurBB) ||
5467           popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
5468                    Vec2, CurBB))
5469         return error("Invalid record");
5470 
5471       unsigned MaskTypeID;
5472       if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
5473         return error("Invalid record");
5474       if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
5475         return error("Invalid type for value");
5476 
5477       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
5478       ResTypeID =
5479           getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
5480       InstructionList.push_back(I);
5481       break;
5482     }
5483 
5484     case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
5485       // Old form of ICmp/FCmp returning bool
5486       // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
5487       // both legal on vectors but had different behaviour.
5488     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
5489       // FCmp/ICmp returning bool or vector of bool
5490 
5491       unsigned OpNum = 0;
5492       Value *LHS, *RHS;
5493       unsigned LHSTypeID;
5494       if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
5495           popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
5496                    CurBB))
5497         return error("Invalid record");
5498 
5499       if (OpNum >= Record.size())
5500         return error(
5501             "Invalid record: operand number exceeded available operands");
5502 
5503       CmpInst::Predicate PredVal = CmpInst::Predicate(Record[OpNum]);
5504       bool IsFP = LHS->getType()->isFPOrFPVectorTy();
5505       FastMathFlags FMF;
5506       if (IsFP && Record.size() > OpNum+1)
5507         FMF = getDecodedFastMathFlags(Record[++OpNum]);
5508 
5509       if (IsFP) {
5510         if (!CmpInst::isFPPredicate(PredVal))
5511           return error("Invalid fcmp predicate");
5512         I = new FCmpInst(PredVal, LHS, RHS);
5513       } else {
5514         if (!CmpInst::isIntPredicate(PredVal))
5515           return error("Invalid icmp predicate");
5516         I = new ICmpInst(PredVal, LHS, RHS);
5517         if (Record.size() > OpNum + 1 &&
5518             (Record[++OpNum] & (1 << bitc::ICMP_SAME_SIGN)))
5519           cast<ICmpInst>(I)->setSameSign();
5520       }
5521 
5522       if (OpNum + 1 != Record.size())
5523         return error("Invalid record");
5524 
5525       ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
5526       if (LHS->getType()->isVectorTy())
5527         ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
5528 
5529       if (FMF.any())
5530         I->setFastMathFlags(FMF);
5531       InstructionList.push_back(I);
5532       break;
5533     }
5534 
5535     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
5536       {
5537         unsigned Size = Record.size();
5538         if (Size == 0) {
5539           I = ReturnInst::Create(Context);
5540           InstructionList.push_back(I);
5541           break;
5542         }
5543 
5544         unsigned OpNum = 0;
5545         Value *Op = nullptr;
5546         unsigned OpTypeID;
5547         if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5548           return error("Invalid record");
5549         if (OpNum != Record.size())
5550           return error("Invalid record");
5551 
5552         I = ReturnInst::Create(Context, Op);
5553         InstructionList.push_back(I);
5554         break;
5555       }
5556     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
5557       if (Record.size() != 1 && Record.size() != 3)
5558         return error("Invalid record");
5559       BasicBlock *TrueDest = getBasicBlock(Record[0]);
5560       if (!TrueDest)
5561         return error("Invalid record");
5562 
5563       if (Record.size() == 1) {
5564         I = BranchInst::Create(TrueDest);
5565         InstructionList.push_back(I);
5566       }
5567       else {
5568         BasicBlock *FalseDest = getBasicBlock(Record[1]);
5569         Type *CondType = Type::getInt1Ty(Context);
5570         Value *Cond = getValue(Record, 2, NextValueNo, CondType,
5571                                getVirtualTypeID(CondType), CurBB);
5572         if (!FalseDest || !Cond)
5573           return error("Invalid record");
5574         I = BranchInst::Create(TrueDest, FalseDest, Cond);
5575         InstructionList.push_back(I);
5576       }
5577       break;
5578     }
5579     case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
5580       if (Record.size() != 1 && Record.size() != 2)
5581         return error("Invalid record");
5582       unsigned Idx = 0;
5583       Type *TokenTy = Type::getTokenTy(Context);
5584       Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5585                                    getVirtualTypeID(TokenTy), CurBB);
5586       if (!CleanupPad)
5587         return error("Invalid record");
5588       BasicBlock *UnwindDest = nullptr;
5589       if (Record.size() == 2) {
5590         UnwindDest = getBasicBlock(Record[Idx++]);
5591         if (!UnwindDest)
5592           return error("Invalid record");
5593       }
5594 
5595       I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
5596       InstructionList.push_back(I);
5597       break;
5598     }
5599     case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
5600       if (Record.size() != 2)
5601         return error("Invalid record");
5602       unsigned Idx = 0;
5603       Type *TokenTy = Type::getTokenTy(Context);
5604       Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5605                                  getVirtualTypeID(TokenTy), CurBB);
5606       if (!CatchPad)
5607         return error("Invalid record");
5608       BasicBlock *BB = getBasicBlock(Record[Idx++]);
5609       if (!BB)
5610         return error("Invalid record");
5611 
5612       I = CatchReturnInst::Create(CatchPad, BB);
5613       InstructionList.push_back(I);
5614       break;
5615     }
5616     case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
5617       // We must have, at minimum, the outer scope and the number of arguments.
5618       if (Record.size() < 2)
5619         return error("Invalid record");
5620 
5621       unsigned Idx = 0;
5622 
5623       Type *TokenTy = Type::getTokenTy(Context);
5624       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5625                                   getVirtualTypeID(TokenTy), CurBB);
5626       if (!ParentPad)
5627         return error("Invalid record");
5628 
5629       unsigned NumHandlers = Record[Idx++];
5630 
5631       SmallVector<BasicBlock *, 2> Handlers;
5632       for (unsigned Op = 0; Op != NumHandlers; ++Op) {
5633         BasicBlock *BB = getBasicBlock(Record[Idx++]);
5634         if (!BB)
5635           return error("Invalid record");
5636         Handlers.push_back(BB);
5637       }
5638 
5639       BasicBlock *UnwindDest = nullptr;
5640       if (Idx + 1 == Record.size()) {
5641         UnwindDest = getBasicBlock(Record[Idx++]);
5642         if (!UnwindDest)
5643           return error("Invalid record");
5644       }
5645 
5646       if (Record.size() != Idx)
5647         return error("Invalid record");
5648 
5649       auto *CatchSwitch =
5650           CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
5651       for (BasicBlock *Handler : Handlers)
5652         CatchSwitch->addHandler(Handler);
5653       I = CatchSwitch;
5654       ResTypeID = getVirtualTypeID(I->getType());
5655       InstructionList.push_back(I);
5656       break;
5657     }
5658     case bitc::FUNC_CODE_INST_CATCHPAD:
5659     case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
5660       // We must have, at minimum, the outer scope and the number of arguments.
5661       if (Record.size() < 2)
5662         return error("Invalid record");
5663 
5664       unsigned Idx = 0;
5665 
5666       Type *TokenTy = Type::getTokenTy(Context);
5667       Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
5668                                   getVirtualTypeID(TokenTy), CurBB);
5669       if (!ParentPad)
5670         return error("Invald record");
5671 
5672       unsigned NumArgOperands = Record[Idx++];
5673 
5674       SmallVector<Value *, 2> Args;
5675       for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
5676         Value *Val;
5677         unsigned ValTypeID;
5678         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
5679           return error("Invalid record");
5680         Args.push_back(Val);
5681       }
5682 
5683       if (Record.size() != Idx)
5684         return error("Invalid record");
5685 
5686       if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
5687         I = CleanupPadInst::Create(ParentPad, Args);
5688       else
5689         I = CatchPadInst::Create(ParentPad, Args);
5690       ResTypeID = getVirtualTypeID(I->getType());
5691       InstructionList.push_back(I);
5692       break;
5693     }
5694     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
5695       // Check magic
5696       if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
5697         // "New" SwitchInst format with case ranges. The changes to write this
5698         // format were reverted but we still recognize bitcode that uses it.
5699         // Hopefully someday we will have support for case ranges and can use
5700         // this format again.
5701 
5702         unsigned OpTyID = Record[1];
5703         Type *OpTy = getTypeByID(OpTyID);
5704         unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
5705 
5706         Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
5707         BasicBlock *Default = getBasicBlock(Record[3]);
5708         if (!OpTy || !Cond || !Default)
5709           return error("Invalid record");
5710 
5711         unsigned NumCases = Record[4];
5712 
5713         SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5714         InstructionList.push_back(SI);
5715 
5716         unsigned CurIdx = 5;
5717         for (unsigned i = 0; i != NumCases; ++i) {
5718           SmallVector<ConstantInt*, 1> CaseVals;
5719           unsigned NumItems = Record[CurIdx++];
5720           for (unsigned ci = 0; ci != NumItems; ++ci) {
5721             bool isSingleNumber = Record[CurIdx++];
5722 
5723             APInt Low;
5724             unsigned ActiveWords = 1;
5725             if (ValueBitWidth > 64)
5726               ActiveWords = Record[CurIdx++];
5727             Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5728                                 ValueBitWidth);
5729             CurIdx += ActiveWords;
5730 
5731             if (!isSingleNumber) {
5732               ActiveWords = 1;
5733               if (ValueBitWidth > 64)
5734                 ActiveWords = Record[CurIdx++];
5735               APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
5736                                          ValueBitWidth);
5737               CurIdx += ActiveWords;
5738 
5739               // FIXME: It is not clear whether values in the range should be
5740               // compared as signed or unsigned values. The partially
5741               // implemented changes that used this format in the past used
5742               // unsigned comparisons.
5743               for ( ; Low.ule(High); ++Low)
5744                 CaseVals.push_back(ConstantInt::get(Context, Low));
5745             } else
5746               CaseVals.push_back(ConstantInt::get(Context, Low));
5747           }
5748           BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
5749           for (ConstantInt *Cst : CaseVals)
5750             SI->addCase(Cst, DestBB);
5751         }
5752         I = SI;
5753         break;
5754       }
5755 
5756       // Old SwitchInst format without case ranges.
5757 
5758       if (Record.size() < 3 || (Record.size() & 1) == 0)
5759         return error("Invalid record");
5760       unsigned OpTyID = Record[0];
5761       Type *OpTy = getTypeByID(OpTyID);
5762       Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5763       BasicBlock *Default = getBasicBlock(Record[2]);
5764       if (!OpTy || !Cond || !Default)
5765         return error("Invalid record");
5766       unsigned NumCases = (Record.size()-3)/2;
5767       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
5768       InstructionList.push_back(SI);
5769       for (unsigned i = 0, e = NumCases; i != e; ++i) {
5770         ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
5771             getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
5772         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
5773         if (!CaseVal || !DestBB) {
5774           delete SI;
5775           return error("Invalid record");
5776         }
5777         SI->addCase(CaseVal, DestBB);
5778       }
5779       I = SI;
5780       break;
5781     }
5782     case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
5783       if (Record.size() < 2)
5784         return error("Invalid record");
5785       unsigned OpTyID = Record[0];
5786       Type *OpTy = getTypeByID(OpTyID);
5787       Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
5788       if (!OpTy || !Address)
5789         return error("Invalid record");
5790       unsigned NumDests = Record.size()-2;
5791       IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
5792       InstructionList.push_back(IBI);
5793       for (unsigned i = 0, e = NumDests; i != e; ++i) {
5794         if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
5795           IBI->addDestination(DestBB);
5796         } else {
5797           delete IBI;
5798           return error("Invalid record");
5799         }
5800       }
5801       I = IBI;
5802       break;
5803     }
5804 
5805     case bitc::FUNC_CODE_INST_INVOKE: {
5806       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
5807       if (Record.size() < 4)
5808         return error("Invalid record");
5809       unsigned OpNum = 0;
5810       AttributeList PAL = getAttributes(Record[OpNum++]);
5811       unsigned CCInfo = Record[OpNum++];
5812       BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
5813       BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
5814 
5815       unsigned FTyID = InvalidTypeID;
5816       FunctionType *FTy = nullptr;
5817       if ((CCInfo >> 13) & 1) {
5818         FTyID = Record[OpNum++];
5819         FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
5820         if (!FTy)
5821           return error("Explicit invoke type is not a function type");
5822       }
5823 
5824       Value *Callee;
5825       unsigned CalleeTypeID;
5826       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5827                            CurBB))
5828         return error("Invalid record");
5829 
5830       PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
5831       if (!CalleeTy)
5832         return error("Callee is not a pointer");
5833       if (!FTy) {
5834         FTyID = getContainedTypeID(CalleeTypeID);
5835         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5836         if (!FTy)
5837           return error("Callee is not of pointer to function type");
5838       }
5839       if (Record.size() < FTy->getNumParams() + OpNum)
5840         return error("Insufficient operands to call");
5841 
5842       SmallVector<Value*, 16> Ops;
5843       SmallVector<unsigned, 16> ArgTyIDs;
5844       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5845         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5846         Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5847                                ArgTyID, CurBB));
5848         ArgTyIDs.push_back(ArgTyID);
5849         if (!Ops.back())
5850           return error("Invalid record");
5851       }
5852 
5853       if (!FTy->isVarArg()) {
5854         if (Record.size() != OpNum)
5855           return error("Invalid record");
5856       } else {
5857         // Read type/value pairs for varargs params.
5858         while (OpNum != Record.size()) {
5859           Value *Op;
5860           unsigned OpTypeID;
5861           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5862             return error("Invalid record");
5863           Ops.push_back(Op);
5864           ArgTyIDs.push_back(OpTypeID);
5865         }
5866       }
5867 
5868       // Upgrade the bundles if needed.
5869       if (!OperandBundles.empty())
5870         UpgradeOperandBundles(OperandBundles);
5871 
5872       I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
5873                              OperandBundles);
5874       ResTypeID = getContainedTypeID(FTyID);
5875       OperandBundles.clear();
5876       InstructionList.push_back(I);
5877       cast<InvokeInst>(I)->setCallingConv(
5878           static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
5879       cast<InvokeInst>(I)->setAttributes(PAL);
5880       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
5881         I->deleteValue();
5882         return Err;
5883       }
5884 
5885       break;
5886     }
5887     case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
5888       unsigned Idx = 0;
5889       Value *Val = nullptr;
5890       unsigned ValTypeID;
5891       if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
5892         return error("Invalid record");
5893       I = ResumeInst::Create(Val);
5894       InstructionList.push_back(I);
5895       break;
5896     }
5897     case bitc::FUNC_CODE_INST_CALLBR: {
5898       // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
5899       unsigned OpNum = 0;
5900       AttributeList PAL = getAttributes(Record[OpNum++]);
5901       unsigned CCInfo = Record[OpNum++];
5902 
5903       BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
5904       unsigned NumIndirectDests = Record[OpNum++];
5905       SmallVector<BasicBlock *, 16> IndirectDests;
5906       for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
5907         IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
5908 
5909       unsigned FTyID = InvalidTypeID;
5910       FunctionType *FTy = nullptr;
5911       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
5912         FTyID = Record[OpNum++];
5913         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5914         if (!FTy)
5915           return error("Explicit call type is not a function type");
5916       }
5917 
5918       Value *Callee;
5919       unsigned CalleeTypeID;
5920       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
5921                            CurBB))
5922         return error("Invalid record");
5923 
5924       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
5925       if (!OpTy)
5926         return error("Callee is not a pointer type");
5927       if (!FTy) {
5928         FTyID = getContainedTypeID(CalleeTypeID);
5929         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
5930         if (!FTy)
5931           return error("Callee is not of pointer to function type");
5932       }
5933       if (Record.size() < FTy->getNumParams() + OpNum)
5934         return error("Insufficient operands to call");
5935 
5936       SmallVector<Value*, 16> Args;
5937       SmallVector<unsigned, 16> ArgTyIDs;
5938       // Read the fixed params.
5939       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
5940         Value *Arg;
5941         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
5942         if (FTy->getParamType(i)->isLabelTy())
5943           Arg = getBasicBlock(Record[OpNum]);
5944         else
5945           Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
5946                          ArgTyID, CurBB);
5947         if (!Arg)
5948           return error("Invalid record");
5949         Args.push_back(Arg);
5950         ArgTyIDs.push_back(ArgTyID);
5951       }
5952 
5953       // Read type/value pairs for varargs params.
5954       if (!FTy->isVarArg()) {
5955         if (OpNum != Record.size())
5956           return error("Invalid record");
5957       } else {
5958         while (OpNum != Record.size()) {
5959           Value *Op;
5960           unsigned OpTypeID;
5961           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
5962             return error("Invalid record");
5963           Args.push_back(Op);
5964           ArgTyIDs.push_back(OpTypeID);
5965         }
5966       }
5967 
5968       // Upgrade the bundles if needed.
5969       if (!OperandBundles.empty())
5970         UpgradeOperandBundles(OperandBundles);
5971 
5972       if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
5973         InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
5974         auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
5975           return CI.Type == InlineAsm::isLabel;
5976         };
5977         if (none_of(ConstraintInfo, IsLabelConstraint)) {
5978           // Upgrade explicit blockaddress arguments to label constraints.
5979           // Verify that the last arguments are blockaddress arguments that
5980           // match the indirect destinations. Clang always generates callbr
5981           // in this form. We could support reordering with more effort.
5982           unsigned FirstBlockArg = Args.size() - IndirectDests.size();
5983           for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
5984             unsigned LabelNo = ArgNo - FirstBlockArg;
5985             auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
5986             if (!BA || BA->getFunction() != F ||
5987                 LabelNo > IndirectDests.size() ||
5988                 BA->getBasicBlock() != IndirectDests[LabelNo])
5989               return error("callbr argument does not match indirect dest");
5990           }
5991 
5992           // Remove blockaddress arguments.
5993           Args.erase(Args.begin() + FirstBlockArg, Args.end());
5994           ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
5995 
5996           // Recreate the function type with less arguments.
5997           SmallVector<Type *> ArgTys;
5998           for (Value *Arg : Args)
5999             ArgTys.push_back(Arg->getType());
6000           FTy =
6001               FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
6002 
6003           // Update constraint string to use label constraints.
6004           std::string Constraints = IA->getConstraintString();
6005           unsigned ArgNo = 0;
6006           size_t Pos = 0;
6007           for (const auto &CI : ConstraintInfo) {
6008             if (CI.hasArg()) {
6009               if (ArgNo >= FirstBlockArg)
6010                 Constraints.insert(Pos, "!");
6011               ++ArgNo;
6012             }
6013 
6014             // Go to next constraint in string.
6015             Pos = Constraints.find(',', Pos);
6016             if (Pos == std::string::npos)
6017               break;
6018             ++Pos;
6019           }
6020 
6021           Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
6022                                   IA->hasSideEffects(), IA->isAlignStack(),
6023                                   IA->getDialect(), IA->canThrow());
6024         }
6025       }
6026 
6027       I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
6028                              OperandBundles);
6029       ResTypeID = getContainedTypeID(FTyID);
6030       OperandBundles.clear();
6031       InstructionList.push_back(I);
6032       cast<CallBrInst>(I)->setCallingConv(
6033           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6034       cast<CallBrInst>(I)->setAttributes(PAL);
6035       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6036         I->deleteValue();
6037         return Err;
6038       }
6039       break;
6040     }
6041     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
6042       I = new UnreachableInst(Context);
6043       InstructionList.push_back(I);
6044       break;
6045     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
6046       if (Record.empty())
6047         return error("Invalid phi record");
6048       // The first record specifies the type.
6049       unsigned TyID = Record[0];
6050       Type *Ty = getTypeByID(TyID);
6051       if (!Ty)
6052         return error("Invalid phi record");
6053 
6054       // Phi arguments are pairs of records of [value, basic block].
6055       // There is an optional final record for fast-math-flags if this phi has a
6056       // floating-point type.
6057       size_t NumArgs = (Record.size() - 1) / 2;
6058       PHINode *PN = PHINode::Create(Ty, NumArgs);
6059       if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
6060         PN->deleteValue();
6061         return error("Invalid phi record");
6062       }
6063       InstructionList.push_back(PN);
6064 
6065       SmallDenseMap<BasicBlock *, Value *> Args;
6066       for (unsigned i = 0; i != NumArgs; i++) {
6067         BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
6068         if (!BB) {
6069           PN->deleteValue();
6070           return error("Invalid phi BB");
6071         }
6072 
6073         // Phi nodes may contain the same predecessor multiple times, in which
6074         // case the incoming value must be identical. Directly reuse the already
6075         // seen value here, to avoid expanding a constant expression multiple
6076         // times.
6077         auto It = Args.find(BB);
6078         if (It != Args.end()) {
6079           PN->addIncoming(It->second, BB);
6080           continue;
6081         }
6082 
6083         // If there already is a block for this edge (from a different phi),
6084         // use it.
6085         BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
6086         if (!EdgeBB) {
6087           // Otherwise, use a temporary block (that we will discard if it
6088           // turns out to be unnecessary).
6089           if (!PhiConstExprBB)
6090             PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
6091           EdgeBB = PhiConstExprBB;
6092         }
6093 
6094         // With the new function encoding, it is possible that operands have
6095         // negative IDs (for forward references).  Use a signed VBR
6096         // representation to keep the encoding small.
6097         Value *V;
6098         if (UseRelativeIDs)
6099           V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6100         else
6101           V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
6102         if (!V) {
6103           PN->deleteValue();
6104           PhiConstExprBB->eraseFromParent();
6105           return error("Invalid phi record");
6106         }
6107 
6108         if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
6109           ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
6110           PhiConstExprBB = nullptr;
6111         }
6112         PN->addIncoming(V, BB);
6113         Args.insert({BB, V});
6114       }
6115       I = PN;
6116       ResTypeID = TyID;
6117 
6118       // If there are an even number of records, the final record must be FMF.
6119       if (Record.size() % 2 == 0) {
6120         assert(isa<FPMathOperator>(I) && "Unexpected phi type");
6121         FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
6122         if (FMF.any())
6123           I->setFastMathFlags(FMF);
6124       }
6125 
6126       break;
6127     }
6128 
6129     case bitc::FUNC_CODE_INST_LANDINGPAD:
6130     case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
6131       // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
6132       unsigned Idx = 0;
6133       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
6134         if (Record.size() < 3)
6135           return error("Invalid record");
6136       } else {
6137         assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
6138         if (Record.size() < 4)
6139           return error("Invalid record");
6140       }
6141       ResTypeID = Record[Idx++];
6142       Type *Ty = getTypeByID(ResTypeID);
6143       if (!Ty)
6144         return error("Invalid record");
6145       if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
6146         Value *PersFn = nullptr;
6147         unsigned PersFnTypeID;
6148         if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
6149                              nullptr))
6150           return error("Invalid record");
6151 
6152         if (!F->hasPersonalityFn())
6153           F->setPersonalityFn(cast<Constant>(PersFn));
6154         else if (F->getPersonalityFn() != cast<Constant>(PersFn))
6155           return error("Personality function mismatch");
6156       }
6157 
6158       bool IsCleanup = !!Record[Idx++];
6159       unsigned NumClauses = Record[Idx++];
6160       LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
6161       LP->setCleanup(IsCleanup);
6162       for (unsigned J = 0; J != NumClauses; ++J) {
6163         LandingPadInst::ClauseType CT =
6164           LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
6165         Value *Val;
6166         unsigned ValTypeID;
6167 
6168         if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
6169                              nullptr)) {
6170           delete LP;
6171           return error("Invalid record");
6172         }
6173 
6174         assert((CT != LandingPadInst::Catch ||
6175                 !isa<ArrayType>(Val->getType())) &&
6176                "Catch clause has a invalid type!");
6177         assert((CT != LandingPadInst::Filter ||
6178                 isa<ArrayType>(Val->getType())) &&
6179                "Filter clause has invalid type!");
6180         LP->addClause(cast<Constant>(Val));
6181       }
6182 
6183       I = LP;
6184       InstructionList.push_back(I);
6185       break;
6186     }
6187 
6188     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
6189       if (Record.size() != 4 && Record.size() != 5)
6190         return error("Invalid record");
6191       using APV = AllocaPackedValues;
6192       const uint64_t Rec = Record[3];
6193       const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
6194       const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
6195       unsigned TyID = Record[0];
6196       Type *Ty = getTypeByID(TyID);
6197       if (!Bitfield::get<APV::ExplicitType>(Rec)) {
6198         TyID = getContainedTypeID(TyID);
6199         Ty = getTypeByID(TyID);
6200         if (!Ty)
6201           return error("Missing element type for old-style alloca");
6202       }
6203       unsigned OpTyID = Record[1];
6204       Type *OpTy = getTypeByID(OpTyID);
6205       Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
6206       MaybeAlign Align;
6207       uint64_t AlignExp =
6208           Bitfield::get<APV::AlignLower>(Rec) |
6209           (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
6210       if (Error Err = parseAlignmentValue(AlignExp, Align)) {
6211         return Err;
6212       }
6213       if (!Ty || !Size)
6214         return error("Invalid record");
6215 
6216       const DataLayout &DL = TheModule->getDataLayout();
6217       unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
6218 
6219       SmallPtrSet<Type *, 4> Visited;
6220       if (!Align && !Ty->isSized(&Visited))
6221         return error("alloca of unsized type");
6222       if (!Align)
6223         Align = DL.getPrefTypeAlign(Ty);
6224 
6225       if (!Size->getType()->isIntegerTy())
6226         return error("alloca element count must have integer type");
6227 
6228       AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
6229       AI->setUsedWithInAlloca(InAlloca);
6230       AI->setSwiftError(SwiftError);
6231       I = AI;
6232       ResTypeID = getVirtualTypeID(AI->getType(), TyID);
6233       InstructionList.push_back(I);
6234       break;
6235     }
6236     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
6237       unsigned OpNum = 0;
6238       Value *Op;
6239       unsigned OpTypeID;
6240       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6241           (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
6242         return error("Invalid record");
6243 
6244       if (!isa<PointerType>(Op->getType()))
6245         return error("Load operand is not a pointer type");
6246 
6247       Type *Ty = nullptr;
6248       if (OpNum + 3 == Record.size()) {
6249         ResTypeID = Record[OpNum++];
6250         Ty = getTypeByID(ResTypeID);
6251       } else {
6252         ResTypeID = getContainedTypeID(OpTypeID);
6253         Ty = getTypeByID(ResTypeID);
6254       }
6255 
6256       if (!Ty)
6257         return error("Missing load type");
6258 
6259       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6260         return Err;
6261 
6262       MaybeAlign Align;
6263       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6264         return Err;
6265       SmallPtrSet<Type *, 4> Visited;
6266       if (!Align && !Ty->isSized(&Visited))
6267         return error("load of unsized type");
6268       if (!Align)
6269         Align = TheModule->getDataLayout().getABITypeAlign(Ty);
6270       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
6271       InstructionList.push_back(I);
6272       break;
6273     }
6274     case bitc::FUNC_CODE_INST_LOADATOMIC: {
6275        // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
6276       unsigned OpNum = 0;
6277       Value *Op;
6278       unsigned OpTypeID;
6279       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
6280           (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
6281         return error("Invalid record");
6282 
6283       if (!isa<PointerType>(Op->getType()))
6284         return error("Load operand is not a pointer type");
6285 
6286       Type *Ty = nullptr;
6287       if (OpNum + 5 == Record.size()) {
6288         ResTypeID = Record[OpNum++];
6289         Ty = getTypeByID(ResTypeID);
6290       } else {
6291         ResTypeID = getContainedTypeID(OpTypeID);
6292         Ty = getTypeByID(ResTypeID);
6293       }
6294 
6295       if (!Ty)
6296         return error("Missing atomic load type");
6297 
6298       if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
6299         return Err;
6300 
6301       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6302       if (Ordering == AtomicOrdering::NotAtomic ||
6303           Ordering == AtomicOrdering::Release ||
6304           Ordering == AtomicOrdering::AcquireRelease)
6305         return error("Invalid record");
6306       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6307         return error("Invalid record");
6308       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6309 
6310       MaybeAlign Align;
6311       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6312         return Err;
6313       if (!Align)
6314         return error("Alignment missing from atomic load");
6315       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
6316       InstructionList.push_back(I);
6317       break;
6318     }
6319     case bitc::FUNC_CODE_INST_STORE:
6320     case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
6321       unsigned OpNum = 0;
6322       Value *Val, *Ptr;
6323       unsigned PtrTypeID, ValTypeID;
6324       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6325         return error("Invalid record");
6326 
6327       if (BitCode == bitc::FUNC_CODE_INST_STORE) {
6328         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6329           return error("Invalid record");
6330       } else {
6331         ValTypeID = getContainedTypeID(PtrTypeID);
6332         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6333                      ValTypeID, Val, CurBB))
6334           return error("Invalid record");
6335       }
6336 
6337       if (OpNum + 2 != Record.size())
6338         return error("Invalid record");
6339 
6340       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6341         return Err;
6342       MaybeAlign Align;
6343       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6344         return Err;
6345       SmallPtrSet<Type *, 4> Visited;
6346       if (!Align && !Val->getType()->isSized(&Visited))
6347         return error("store of unsized type");
6348       if (!Align)
6349         Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
6350       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
6351       InstructionList.push_back(I);
6352       break;
6353     }
6354     case bitc::FUNC_CODE_INST_STOREATOMIC:
6355     case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
6356       // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
6357       unsigned OpNum = 0;
6358       Value *Val, *Ptr;
6359       unsigned PtrTypeID, ValTypeID;
6360       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
6361           !isa<PointerType>(Ptr->getType()))
6362         return error("Invalid record");
6363       if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
6364         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6365           return error("Invalid record");
6366       } else {
6367         ValTypeID = getContainedTypeID(PtrTypeID);
6368         if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
6369                      ValTypeID, Val, CurBB))
6370           return error("Invalid record");
6371       }
6372 
6373       if (OpNum + 4 != Record.size())
6374         return error("Invalid record");
6375 
6376       if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
6377         return Err;
6378       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6379       if (Ordering == AtomicOrdering::NotAtomic ||
6380           Ordering == AtomicOrdering::Acquire ||
6381           Ordering == AtomicOrdering::AcquireRelease)
6382         return error("Invalid record");
6383       SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6384       if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
6385         return error("Invalid record");
6386 
6387       MaybeAlign Align;
6388       if (Error Err = parseAlignmentValue(Record[OpNum], Align))
6389         return Err;
6390       if (!Align)
6391         return error("Alignment missing from atomic store");
6392       I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
6393       InstructionList.push_back(I);
6394       break;
6395     }
6396     case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
6397       // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
6398       // failure_ordering?, weak?]
6399       const size_t NumRecords = Record.size();
6400       unsigned OpNum = 0;
6401       Value *Ptr = nullptr;
6402       unsigned PtrTypeID;
6403       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6404         return error("Invalid record");
6405 
6406       if (!isa<PointerType>(Ptr->getType()))
6407         return error("Cmpxchg operand is not a pointer type");
6408 
6409       Value *Cmp = nullptr;
6410       unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
6411       if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
6412                    CmpTypeID, Cmp, CurBB))
6413         return error("Invalid record");
6414 
6415       Value *New = nullptr;
6416       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
6417                    New, CurBB) ||
6418           NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
6419         return error("Invalid record");
6420 
6421       const AtomicOrdering SuccessOrdering =
6422           getDecodedOrdering(Record[OpNum + 1]);
6423       if (SuccessOrdering == AtomicOrdering::NotAtomic ||
6424           SuccessOrdering == AtomicOrdering::Unordered)
6425         return error("Invalid record");
6426 
6427       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6428 
6429       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6430         return Err;
6431 
6432       const AtomicOrdering FailureOrdering =
6433           NumRecords < 7
6434               ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
6435               : getDecodedOrdering(Record[OpNum + 3]);
6436 
6437       if (FailureOrdering == AtomicOrdering::NotAtomic ||
6438           FailureOrdering == AtomicOrdering::Unordered)
6439         return error("Invalid record");
6440 
6441       const Align Alignment(
6442           TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6443 
6444       I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
6445                                 FailureOrdering, SSID);
6446       cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
6447 
6448       if (NumRecords < 8) {
6449         // Before weak cmpxchgs existed, the instruction simply returned the
6450         // value loaded from memory, so bitcode files from that era will be
6451         // expecting the first component of a modern cmpxchg.
6452         I->insertInto(CurBB, CurBB->end());
6453         I = ExtractValueInst::Create(I, 0);
6454         ResTypeID = CmpTypeID;
6455       } else {
6456         cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
6457         unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6458         ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6459       }
6460 
6461       InstructionList.push_back(I);
6462       break;
6463     }
6464     case bitc::FUNC_CODE_INST_CMPXCHG: {
6465       // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
6466       // failure_ordering, weak, align?]
6467       const size_t NumRecords = Record.size();
6468       unsigned OpNum = 0;
6469       Value *Ptr = nullptr;
6470       unsigned PtrTypeID;
6471       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6472         return error("Invalid record");
6473 
6474       if (!isa<PointerType>(Ptr->getType()))
6475         return error("Cmpxchg operand is not a pointer type");
6476 
6477       Value *Cmp = nullptr;
6478       unsigned CmpTypeID;
6479       if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
6480         return error("Invalid record");
6481 
6482       Value *Val = nullptr;
6483       if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
6484                    CurBB))
6485         return error("Invalid record");
6486 
6487       if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
6488         return error("Invalid record");
6489 
6490       const bool IsVol = Record[OpNum];
6491 
6492       const AtomicOrdering SuccessOrdering =
6493           getDecodedOrdering(Record[OpNum + 1]);
6494       if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
6495         return error("Invalid cmpxchg success ordering");
6496 
6497       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
6498 
6499       if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
6500         return Err;
6501 
6502       const AtomicOrdering FailureOrdering =
6503           getDecodedOrdering(Record[OpNum + 3]);
6504       if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
6505         return error("Invalid cmpxchg failure ordering");
6506 
6507       const bool IsWeak = Record[OpNum + 4];
6508 
6509       MaybeAlign Alignment;
6510 
6511       if (NumRecords == (OpNum + 6)) {
6512         if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
6513           return Err;
6514       }
6515       if (!Alignment)
6516         Alignment =
6517             Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
6518 
6519       I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
6520                                 FailureOrdering, SSID);
6521       cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
6522       cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
6523 
6524       unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
6525       ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
6526 
6527       InstructionList.push_back(I);
6528       break;
6529     }
6530     case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
6531     case bitc::FUNC_CODE_INST_ATOMICRMW: {
6532       // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
6533       // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
6534       const size_t NumRecords = Record.size();
6535       unsigned OpNum = 0;
6536 
6537       Value *Ptr = nullptr;
6538       unsigned PtrTypeID;
6539       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
6540         return error("Invalid record");
6541 
6542       if (!isa<PointerType>(Ptr->getType()))
6543         return error("Invalid record");
6544 
6545       Value *Val = nullptr;
6546       unsigned ValTypeID = InvalidTypeID;
6547       if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
6548         ValTypeID = getContainedTypeID(PtrTypeID);
6549         if (popValue(Record, OpNum, NextValueNo,
6550                      getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
6551           return error("Invalid record");
6552       } else {
6553         if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
6554           return error("Invalid record");
6555       }
6556 
6557       if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
6558         return error("Invalid record");
6559 
6560       const AtomicRMWInst::BinOp Operation =
6561           getDecodedRMWOperation(Record[OpNum]);
6562       if (Operation < AtomicRMWInst::FIRST_BINOP ||
6563           Operation > AtomicRMWInst::LAST_BINOP)
6564         return error("Invalid record");
6565 
6566       const bool IsVol = Record[OpNum + 1];
6567 
6568       const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
6569       if (Ordering == AtomicOrdering::NotAtomic ||
6570           Ordering == AtomicOrdering::Unordered)
6571         return error("Invalid record");
6572 
6573       const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
6574 
6575       MaybeAlign Alignment;
6576 
6577       if (NumRecords == (OpNum + 5)) {
6578         if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
6579           return Err;
6580       }
6581 
6582       if (!Alignment)
6583         Alignment =
6584             Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
6585 
6586       I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
6587       ResTypeID = ValTypeID;
6588       cast<AtomicRMWInst>(I)->setVolatile(IsVol);
6589 
6590       InstructionList.push_back(I);
6591       break;
6592     }
6593     case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
6594       if (2 != Record.size())
6595         return error("Invalid record");
6596       AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
6597       if (Ordering == AtomicOrdering::NotAtomic ||
6598           Ordering == AtomicOrdering::Unordered ||
6599           Ordering == AtomicOrdering::Monotonic)
6600         return error("Invalid record");
6601       SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
6602       I = new FenceInst(Context, Ordering, SSID);
6603       InstructionList.push_back(I);
6604       break;
6605     }
6606     case bitc::FUNC_CODE_DEBUG_RECORD_LABEL: {
6607       // DbgLabelRecords are placed after the Instructions that they are
6608       // attached to.
6609       SeenDebugRecord = true;
6610       Instruction *Inst = getLastInstruction();
6611       if (!Inst)
6612         return error("Invalid dbg record: missing instruction");
6613       DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[0]));
6614       DILabel *Label = cast<DILabel>(getFnMetadataByID(Record[1]));
6615       Inst->getParent()->insertDbgRecordBefore(
6616           new DbgLabelRecord(Label, DebugLoc(DIL)), Inst->getIterator());
6617       continue; // This isn't an instruction.
6618     }
6619     case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6620     case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6621     case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6622     case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6623       // DbgVariableRecords are placed after the Instructions that they are
6624       // attached to.
6625       SeenDebugRecord = true;
6626       Instruction *Inst = getLastInstruction();
6627       if (!Inst)
6628         return error("Invalid dbg record: missing instruction");
6629 
6630       // First 3 fields are common to all kinds:
6631       //   DILocation, DILocalVariable, DIExpression
6632       // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE)
6633       //   ..., LocationMetadata
6634       // dbg_value (FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE - abbrev'd)
6635       //   ..., Value
6636       // dbg_declare (FUNC_CODE_DEBUG_RECORD_DECLARE)
6637       //   ..., LocationMetadata
6638       // dbg_assign (FUNC_CODE_DEBUG_RECORD_ASSIGN)
6639       //   ..., LocationMetadata, DIAssignID, DIExpression, LocationMetadata
6640       unsigned Slot = 0;
6641       // Common fields (0-2).
6642       DILocation *DIL = cast<DILocation>(getFnMetadataByID(Record[Slot++]));
6643       DILocalVariable *Var =
6644           cast<DILocalVariable>(getFnMetadataByID(Record[Slot++]));
6645       DIExpression *Expr =
6646           cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6647 
6648       // Union field (3: LocationMetadata | Value).
6649       Metadata *RawLocation = nullptr;
6650       if (BitCode == bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE) {
6651         Value *V = nullptr;
6652         unsigned TyID = 0;
6653         // We never expect to see a fwd reference value here because
6654         // use-before-defs are encoded with the standard non-abbrev record
6655         // type (they'd require encoding the type too, and they're rare). As a
6656         // result, getValueTypePair only ever increments Slot by one here (once
6657         // for the value, never twice for value and type).
6658         unsigned SlotBefore = Slot;
6659         if (getValueTypePair(Record, Slot, NextValueNo, V, TyID, CurBB))
6660           return error("Invalid dbg record: invalid value");
6661         (void)SlotBefore;
6662         assert((SlotBefore == Slot - 1) && "unexpected fwd ref");
6663         RawLocation = ValueAsMetadata::get(V);
6664       } else {
6665         RawLocation = getFnMetadataByID(Record[Slot++]);
6666       }
6667 
6668       DbgVariableRecord *DVR = nullptr;
6669       switch (BitCode) {
6670       case bitc::FUNC_CODE_DEBUG_RECORD_VALUE:
6671       case bitc::FUNC_CODE_DEBUG_RECORD_VALUE_SIMPLE:
6672         DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6673                                     DbgVariableRecord::LocationType::Value);
6674         break;
6675       case bitc::FUNC_CODE_DEBUG_RECORD_DECLARE:
6676         DVR = new DbgVariableRecord(RawLocation, Var, Expr, DIL,
6677                                     DbgVariableRecord::LocationType::Declare);
6678         break;
6679       case bitc::FUNC_CODE_DEBUG_RECORD_ASSIGN: {
6680         DIAssignID *ID = cast<DIAssignID>(getFnMetadataByID(Record[Slot++]));
6681         DIExpression *AddrExpr =
6682             cast<DIExpression>(getFnMetadataByID(Record[Slot++]));
6683         Metadata *Addr = getFnMetadataByID(Record[Slot++]);
6684         DVR = new DbgVariableRecord(RawLocation, Var, Expr, ID, Addr, AddrExpr,
6685                                     DIL);
6686         break;
6687       }
6688       default:
6689         llvm_unreachable("Unknown DbgVariableRecord bitcode");
6690       }
6691       Inst->getParent()->insertDbgRecordBefore(DVR, Inst->getIterator());
6692       continue; // This isn't an instruction.
6693     }
6694     case bitc::FUNC_CODE_INST_CALL: {
6695       // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
6696       if (Record.size() < 3)
6697         return error("Invalid record");
6698 
6699       unsigned OpNum = 0;
6700       AttributeList PAL = getAttributes(Record[OpNum++]);
6701       unsigned CCInfo = Record[OpNum++];
6702 
6703       FastMathFlags FMF;
6704       if ((CCInfo >> bitc::CALL_FMF) & 1) {
6705         FMF = getDecodedFastMathFlags(Record[OpNum++]);
6706         if (!FMF.any())
6707           return error("Fast math flags indicator set for call with no FMF");
6708       }
6709 
6710       unsigned FTyID = InvalidTypeID;
6711       FunctionType *FTy = nullptr;
6712       if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
6713         FTyID = Record[OpNum++];
6714         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6715         if (!FTy)
6716           return error("Explicit call type is not a function type");
6717       }
6718 
6719       Value *Callee;
6720       unsigned CalleeTypeID;
6721       if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
6722                            CurBB))
6723         return error("Invalid record");
6724 
6725       PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
6726       if (!OpTy)
6727         return error("Callee is not a pointer type");
6728       if (!FTy) {
6729         FTyID = getContainedTypeID(CalleeTypeID);
6730         FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
6731         if (!FTy)
6732           return error("Callee is not of pointer to function type");
6733       }
6734       if (Record.size() < FTy->getNumParams() + OpNum)
6735         return error("Insufficient operands to call");
6736 
6737       SmallVector<Value*, 16> Args;
6738       SmallVector<unsigned, 16> ArgTyIDs;
6739       // Read the fixed params.
6740       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
6741         unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
6742         if (FTy->getParamType(i)->isLabelTy())
6743           Args.push_back(getBasicBlock(Record[OpNum]));
6744         else
6745           Args.push_back(getValue(Record, OpNum, NextValueNo,
6746                                   FTy->getParamType(i), ArgTyID, CurBB));
6747         ArgTyIDs.push_back(ArgTyID);
6748         if (!Args.back())
6749           return error("Invalid record");
6750       }
6751 
6752       // Read type/value pairs for varargs params.
6753       if (!FTy->isVarArg()) {
6754         if (OpNum != Record.size())
6755           return error("Invalid record");
6756       } else {
6757         while (OpNum != Record.size()) {
6758           Value *Op;
6759           unsigned OpTypeID;
6760           if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6761             return error("Invalid record");
6762           Args.push_back(Op);
6763           ArgTyIDs.push_back(OpTypeID);
6764         }
6765       }
6766 
6767       // Upgrade the bundles if needed.
6768       if (!OperandBundles.empty())
6769         UpgradeOperandBundles(OperandBundles);
6770 
6771       I = CallInst::Create(FTy, Callee, Args, OperandBundles);
6772       ResTypeID = getContainedTypeID(FTyID);
6773       OperandBundles.clear();
6774       InstructionList.push_back(I);
6775       cast<CallInst>(I)->setCallingConv(
6776           static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
6777       CallInst::TailCallKind TCK = CallInst::TCK_None;
6778       if (CCInfo & (1 << bitc::CALL_TAIL))
6779         TCK = CallInst::TCK_Tail;
6780       if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
6781         TCK = CallInst::TCK_MustTail;
6782       if (CCInfo & (1 << bitc::CALL_NOTAIL))
6783         TCK = CallInst::TCK_NoTail;
6784       cast<CallInst>(I)->setTailCallKind(TCK);
6785       cast<CallInst>(I)->setAttributes(PAL);
6786       if (isa<DbgInfoIntrinsic>(I))
6787         SeenDebugIntrinsic = true;
6788       if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
6789         I->deleteValue();
6790         return Err;
6791       }
6792       if (FMF.any()) {
6793         if (!isa<FPMathOperator>(I))
6794           return error("Fast-math-flags specified for call without "
6795                        "floating-point scalar or vector return type");
6796         I->setFastMathFlags(FMF);
6797       }
6798       break;
6799     }
6800     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
6801       if (Record.size() < 3)
6802         return error("Invalid record");
6803       unsigned OpTyID = Record[0];
6804       Type *OpTy = getTypeByID(OpTyID);
6805       Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
6806       ResTypeID = Record[2];
6807       Type *ResTy = getTypeByID(ResTypeID);
6808       if (!OpTy || !Op || !ResTy)
6809         return error("Invalid record");
6810       I = new VAArgInst(Op, ResTy);
6811       InstructionList.push_back(I);
6812       break;
6813     }
6814 
6815     case bitc::FUNC_CODE_OPERAND_BUNDLE: {
6816       // A call or an invoke can be optionally prefixed with some variable
6817       // number of operand bundle blocks.  These blocks are read into
6818       // OperandBundles and consumed at the next call or invoke instruction.
6819 
6820       if (Record.empty() || Record[0] >= BundleTags.size())
6821         return error("Invalid record");
6822 
6823       std::vector<Value *> Inputs;
6824 
6825       unsigned OpNum = 1;
6826       while (OpNum != Record.size()) {
6827         Value *Op;
6828         if (getValueOrMetadata(Record, OpNum, NextValueNo, Op, CurBB))
6829           return error("Invalid record");
6830         Inputs.push_back(Op);
6831       }
6832 
6833       OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
6834       continue;
6835     }
6836 
6837     case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
6838       unsigned OpNum = 0;
6839       Value *Op = nullptr;
6840       unsigned OpTypeID;
6841       if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
6842         return error("Invalid record");
6843       if (OpNum != Record.size())
6844         return error("Invalid record");
6845 
6846       I = new FreezeInst(Op);
6847       ResTypeID = OpTypeID;
6848       InstructionList.push_back(I);
6849       break;
6850     }
6851     }
6852 
6853     // Add instruction to end of current BB.  If there is no current BB, reject
6854     // this file.
6855     if (!CurBB) {
6856       I->deleteValue();
6857       return error("Invalid instruction with no BB");
6858     }
6859     if (!OperandBundles.empty()) {
6860       I->deleteValue();
6861       return error("Operand bundles found with no consumer");
6862     }
6863     I->insertInto(CurBB, CurBB->end());
6864 
6865     // If this was a terminator instruction, move to the next block.
6866     if (I->isTerminator()) {
6867       ++CurBBNo;
6868       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
6869     }
6870 
6871     // Non-void values get registered in the value table for future use.
6872     if (!I->getType()->isVoidTy()) {
6873       assert(I->getType() == getTypeByID(ResTypeID) &&
6874              "Incorrect result type ID");
6875       if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
6876         return Err;
6877     }
6878   }
6879 
6880 OutOfRecordLoop:
6881 
6882   if (!OperandBundles.empty())
6883     return error("Operand bundles found with no consumer");
6884 
6885   // Check the function list for unresolved values.
6886   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
6887     if (!A->getParent()) {
6888       // We found at least one unresolved value.  Nuke them all to avoid leaks.
6889       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
6890         if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
6891           A->replaceAllUsesWith(PoisonValue::get(A->getType()));
6892           delete A;
6893         }
6894       }
6895       return error("Never resolved value found in function");
6896     }
6897   }
6898 
6899   // Unexpected unresolved metadata about to be dropped.
6900   if (MDLoader->hasFwdRefs())
6901     return error("Invalid function metadata: outgoing forward refs");
6902 
6903   if (PhiConstExprBB)
6904     PhiConstExprBB->eraseFromParent();
6905 
6906   for (const auto &Pair : ConstExprEdgeBBs) {
6907     BasicBlock *From = Pair.first.first;
6908     BasicBlock *To = Pair.first.second;
6909     BasicBlock *EdgeBB = Pair.second;
6910     BranchInst::Create(To, EdgeBB);
6911     From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
6912     To->replacePhiUsesWith(From, EdgeBB);
6913     EdgeBB->moveBefore(To);
6914   }
6915 
6916   // Trim the value list down to the size it was before we parsed this function.
6917   ValueList.shrinkTo(ModuleValueListSize);
6918   MDLoader->shrinkTo(ModuleMDLoaderSize);
6919   std::vector<BasicBlock*>().swap(FunctionBBs);
6920   return Error::success();
6921 }
6922 
6923 /// Find the function body in the bitcode stream
6924 Error BitcodeReader::findFunctionInStream(
6925     Function *F,
6926     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
6927   while (DeferredFunctionInfoIterator->second == 0) {
6928     // This is the fallback handling for the old format bitcode that
6929     // didn't contain the function index in the VST, or when we have
6930     // an anonymous function which would not have a VST entry.
6931     // Assert that we have one of those two cases.
6932     assert(VSTOffset == 0 || !F->hasName());
6933     // Parse the next body in the stream and set its position in the
6934     // DeferredFunctionInfo map.
6935     if (Error Err = rememberAndSkipFunctionBodies())
6936       return Err;
6937   }
6938   return Error::success();
6939 }
6940 
6941 SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
6942   if (Val == SyncScope::SingleThread || Val == SyncScope::System)
6943     return SyncScope::ID(Val);
6944   if (Val >= SSIDs.size())
6945     return SyncScope::System; // Map unknown synchronization scopes to system.
6946   return SSIDs[Val];
6947 }
6948 
6949 //===----------------------------------------------------------------------===//
6950 // GVMaterializer implementation
6951 //===----------------------------------------------------------------------===//
6952 
6953 Error BitcodeReader::materialize(GlobalValue *GV) {
6954   Function *F = dyn_cast<Function>(GV);
6955   // If it's not a function or is already material, ignore the request.
6956   if (!F || !F->isMaterializable())
6957     return Error::success();
6958 
6959   DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
6960   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
6961   // If its position is recorded as 0, its body is somewhere in the stream
6962   // but we haven't seen it yet.
6963   if (DFII->second == 0)
6964     if (Error Err = findFunctionInStream(F, DFII))
6965       return Err;
6966 
6967   // Materialize metadata before parsing any function bodies.
6968   if (Error Err = materializeMetadata())
6969     return Err;
6970 
6971   // Move the bit stream to the saved position of the deferred function body.
6972   if (Error JumpFailed = Stream.JumpToBit(DFII->second))
6973     return JumpFailed;
6974 
6975   // Regardless of the debug info format we want to end up in, we need
6976   // IsNewDbgInfoFormat=true to construct any debug records seen in the bitcode.
6977   F->IsNewDbgInfoFormat = true;
6978 
6979   if (Error Err = parseFunctionBody(F))
6980     return Err;
6981   F->setIsMaterializable(false);
6982 
6983   // All parsed Functions should load into the debug info format dictated by the
6984   // Module, unless we're attempting to preserve the input debug info format.
6985   if (SeenDebugIntrinsic && SeenDebugRecord)
6986     return error("Mixed debug intrinsics and debug records in bitcode module!");
6987   if (PreserveInputDbgFormat == cl::boolOrDefault::BOU_TRUE) {
6988     bool SeenAnyDebugInfo = SeenDebugIntrinsic || SeenDebugRecord;
6989     bool NewDbgInfoFormatDesired =
6990         SeenAnyDebugInfo ? SeenDebugRecord : F->getParent()->IsNewDbgInfoFormat;
6991     if (SeenAnyDebugInfo) {
6992       UseNewDbgInfoFormat = SeenDebugRecord;
6993       WriteNewDbgInfoFormatToBitcode = SeenDebugRecord;
6994       WriteNewDbgInfoFormat = SeenDebugRecord;
6995     }
6996     // If the module's debug info format doesn't match the observed input
6997     // format, then set its format now; we don't need to call the conversion
6998     // function because there must be no existing intrinsics to convert.
6999     // Otherwise, just set the format on this function now.
7000     if (NewDbgInfoFormatDesired != F->getParent()->IsNewDbgInfoFormat)
7001       F->getParent()->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
7002     else
7003       F->setNewDbgInfoFormatFlag(NewDbgInfoFormatDesired);
7004   } else {
7005     // If we aren't preserving formats, we use the Module flag to get our
7006     // desired format instead of reading flags, in case we are lazy-loading and
7007     // the format of the module has been changed since it was set by the flags.
7008     // We only need to convert debug info here if we have debug records but
7009     // desire the intrinsic format; everything else is a no-op or handled by the
7010     // autoupgrader.
7011     bool ModuleIsNewDbgInfoFormat = F->getParent()->IsNewDbgInfoFormat;
7012     if (ModuleIsNewDbgInfoFormat || !SeenDebugRecord)
7013       F->setNewDbgInfoFormatFlag(ModuleIsNewDbgInfoFormat);
7014     else
7015       F->setIsNewDbgInfoFormat(ModuleIsNewDbgInfoFormat);
7016   }
7017 
7018   if (StripDebugInfo)
7019     stripDebugInfo(*F);
7020 
7021   // Upgrade any old intrinsic calls in the function.
7022   for (auto &I : UpgradedIntrinsics) {
7023     for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
7024       if (CallInst *CI = dyn_cast<CallInst>(U))
7025         UpgradeIntrinsicCall(CI, I.second);
7026   }
7027 
7028   // Finish fn->subprogram upgrade for materialized functions.
7029   if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
7030     F->setSubprogram(SP);
7031 
7032   // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
7033   if (!MDLoader->isStrippingTBAA()) {
7034     for (auto &I : instructions(F)) {
7035       MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
7036       if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
7037         continue;
7038       MDLoader->setStripTBAA(true);
7039       stripTBAA(F->getParent());
7040     }
7041   }
7042 
7043   for (auto &I : instructions(F)) {
7044     // "Upgrade" older incorrect branch weights by dropping them.
7045     if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
7046       if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
7047         MDString *MDS = cast<MDString>(MD->getOperand(0));
7048         StringRef ProfName = MDS->getString();
7049         // Check consistency of !prof branch_weights metadata.
7050         if (ProfName != "branch_weights")
7051           continue;
7052         unsigned ExpectedNumOperands = 0;
7053         if (BranchInst *BI = dyn_cast<BranchInst>(&I))
7054           ExpectedNumOperands = BI->getNumSuccessors();
7055         else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
7056           ExpectedNumOperands = SI->getNumSuccessors();
7057         else if (isa<CallInst>(&I))
7058           ExpectedNumOperands = 1;
7059         else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
7060           ExpectedNumOperands = IBI->getNumDestinations();
7061         else if (isa<SelectInst>(&I))
7062           ExpectedNumOperands = 2;
7063         else
7064           continue; // ignore and continue.
7065 
7066         unsigned Offset = getBranchWeightOffset(MD);
7067 
7068         // If branch weight doesn't match, just strip branch weight.
7069         if (MD->getNumOperands() != Offset + ExpectedNumOperands)
7070           I.setMetadata(LLVMContext::MD_prof, nullptr);
7071       }
7072     }
7073 
7074     // Remove incompatible attributes on function calls.
7075     if (auto *CI = dyn_cast<CallBase>(&I)) {
7076       CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
7077           CI->getFunctionType()->getReturnType(), CI->getRetAttributes()));
7078 
7079       for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
7080         CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
7081                                         CI->getArgOperand(ArgNo)->getType(),
7082                                         CI->getParamAttributes(ArgNo)));
7083     }
7084   }
7085 
7086   // Look for functions that rely on old function attribute behavior.
7087   UpgradeFunctionAttributes(*F);
7088 
7089   // Bring in any functions that this function forward-referenced via
7090   // blockaddresses.
7091   return materializeForwardReferencedFunctions();
7092 }
7093 
7094 Error BitcodeReader::materializeModule() {
7095   if (Error Err = materializeMetadata())
7096     return Err;
7097 
7098   // Promise to materialize all forward references.
7099   WillMaterializeAllForwardRefs = true;
7100 
7101   // Iterate over the module, deserializing any functions that are still on
7102   // disk.
7103   for (Function &F : *TheModule) {
7104     if (Error Err = materialize(&F))
7105       return Err;
7106   }
7107   // At this point, if there are any function bodies, parse the rest of
7108   // the bits in the module past the last function block we have recorded
7109   // through either lazy scanning or the VST.
7110   if (LastFunctionBlockBit || NextUnreadBit)
7111     if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
7112                                     ? LastFunctionBlockBit
7113                                     : NextUnreadBit))
7114       return Err;
7115 
7116   // Check that all block address forward references got resolved (as we
7117   // promised above).
7118   if (!BasicBlockFwdRefs.empty())
7119     return error("Never resolved function from blockaddress");
7120 
7121   // Upgrade any intrinsic calls that slipped through (should not happen!) and
7122   // delete the old functions to clean up. We can't do this unless the entire
7123   // module is materialized because there could always be another function body
7124   // with calls to the old function.
7125   for (auto &I : UpgradedIntrinsics) {
7126     for (auto *U : I.first->users()) {
7127       if (CallInst *CI = dyn_cast<CallInst>(U))
7128         UpgradeIntrinsicCall(CI, I.second);
7129     }
7130     if (!I.first->use_empty())
7131       I.first->replaceAllUsesWith(I.second);
7132     I.first->eraseFromParent();
7133   }
7134   UpgradedIntrinsics.clear();
7135 
7136   UpgradeDebugInfo(*TheModule);
7137 
7138   UpgradeModuleFlags(*TheModule);
7139 
7140   UpgradeARCRuntime(*TheModule);
7141 
7142   return Error::success();
7143 }
7144 
7145 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
7146   return IdentifiedStructTypes;
7147 }
7148 
7149 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
7150     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
7151     StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
7152     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
7153       ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
7154 
7155 void ModuleSummaryIndexBitcodeReader::addThisModule() {
7156   TheIndex.addModule(ModulePath);
7157 }
7158 
7159 ModuleSummaryIndex::ModuleInfo *
7160 ModuleSummaryIndexBitcodeReader::getThisModule() {
7161   return TheIndex.getModule(ModulePath);
7162 }
7163 
7164 template <bool AllowNullValueInfo>
7165 std::pair<ValueInfo, GlobalValue::GUID>
7166 ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
7167   auto VGI = ValueIdToValueInfoMap[ValueId];
7168   // We can have a null value info for memprof callsite info records in
7169   // distributed ThinLTO index files when the callee function summary is not
7170   // included in the index. The bitcode writer records 0 in that case,
7171   // and the caller of this helper will set AllowNullValueInfo to true.
7172   assert(AllowNullValueInfo || std::get<0>(VGI));
7173   return VGI;
7174 }
7175 
7176 void ModuleSummaryIndexBitcodeReader::setValueGUID(
7177     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
7178     StringRef SourceFileName) {
7179   std::string GlobalId =
7180       GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
7181   auto ValueGUID = GlobalValue::getGUID(GlobalId);
7182   auto OriginalNameID = ValueGUID;
7183   if (GlobalValue::isLocalLinkage(Linkage))
7184     OriginalNameID = GlobalValue::getGUID(ValueName);
7185   if (PrintSummaryGUIDs)
7186     dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
7187            << ValueName << "\n";
7188 
7189   // UseStrtab is false for legacy summary formats and value names are
7190   // created on stack. In that case we save the name in a string saver in
7191   // the index so that the value name can be recorded.
7192   ValueIdToValueInfoMap[ValueID] = std::make_pair(
7193       TheIndex.getOrInsertValueInfo(
7194           ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
7195       OriginalNameID);
7196 }
7197 
7198 // Specialized value symbol table parser used when reading module index
7199 // blocks where we don't actually create global values. The parsed information
7200 // is saved in the bitcode reader for use when later parsing summaries.
7201 Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
7202     uint64_t Offset,
7203     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
7204   // With a strtab the VST is not required to parse the summary.
7205   if (UseStrtab)
7206     return Error::success();
7207 
7208   assert(Offset > 0 && "Expected non-zero VST offset");
7209   Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
7210   if (!MaybeCurrentBit)
7211     return MaybeCurrentBit.takeError();
7212   uint64_t CurrentBit = MaybeCurrentBit.get();
7213 
7214   if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
7215     return Err;
7216 
7217   SmallVector<uint64_t, 64> Record;
7218 
7219   // Read all the records for this value table.
7220   SmallString<128> ValueName;
7221 
7222   while (true) {
7223     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7224     if (!MaybeEntry)
7225       return MaybeEntry.takeError();
7226     BitstreamEntry Entry = MaybeEntry.get();
7227 
7228     switch (Entry.Kind) {
7229     case BitstreamEntry::SubBlock: // Handled for us already.
7230     case BitstreamEntry::Error:
7231       return error("Malformed block");
7232     case BitstreamEntry::EndBlock:
7233       // Done parsing VST, jump back to wherever we came from.
7234       if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
7235         return JumpFailed;
7236       return Error::success();
7237     case BitstreamEntry::Record:
7238       // The interesting case.
7239       break;
7240     }
7241 
7242     // Read a record.
7243     Record.clear();
7244     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7245     if (!MaybeRecord)
7246       return MaybeRecord.takeError();
7247     switch (MaybeRecord.get()) {
7248     default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
7249       break;
7250     case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
7251       if (convertToString(Record, 1, ValueName))
7252         return error("Invalid record");
7253       unsigned ValueID = Record[0];
7254       assert(!SourceFileName.empty());
7255       auto VLI = ValueIdToLinkageMap.find(ValueID);
7256       assert(VLI != ValueIdToLinkageMap.end() &&
7257              "No linkage found for VST entry?");
7258       auto Linkage = VLI->second;
7259       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7260       ValueName.clear();
7261       break;
7262     }
7263     case bitc::VST_CODE_FNENTRY: {
7264       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
7265       if (convertToString(Record, 2, ValueName))
7266         return error("Invalid record");
7267       unsigned ValueID = Record[0];
7268       assert(!SourceFileName.empty());
7269       auto VLI = ValueIdToLinkageMap.find(ValueID);
7270       assert(VLI != ValueIdToLinkageMap.end() &&
7271              "No linkage found for VST entry?");
7272       auto Linkage = VLI->second;
7273       setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
7274       ValueName.clear();
7275       break;
7276     }
7277     case bitc::VST_CODE_COMBINED_ENTRY: {
7278       // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
7279       unsigned ValueID = Record[0];
7280       GlobalValue::GUID RefGUID = Record[1];
7281       // The "original name", which is the second value of the pair will be
7282       // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
7283       ValueIdToValueInfoMap[ValueID] =
7284           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7285       break;
7286     }
7287     }
7288   }
7289 }
7290 
7291 // Parse just the blocks needed for building the index out of the module.
7292 // At the end of this routine the module Index is populated with a map
7293 // from global value id to GlobalValueSummary objects.
7294 Error ModuleSummaryIndexBitcodeReader::parseModule() {
7295   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
7296     return Err;
7297 
7298   SmallVector<uint64_t, 64> Record;
7299   DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
7300   unsigned ValueId = 0;
7301 
7302   // Read the index for this module.
7303   while (true) {
7304     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
7305     if (!MaybeEntry)
7306       return MaybeEntry.takeError();
7307     llvm::BitstreamEntry Entry = MaybeEntry.get();
7308 
7309     switch (Entry.Kind) {
7310     case BitstreamEntry::Error:
7311       return error("Malformed block");
7312     case BitstreamEntry::EndBlock:
7313       return Error::success();
7314 
7315     case BitstreamEntry::SubBlock:
7316       switch (Entry.ID) {
7317       default: // Skip unknown content.
7318         if (Error Err = Stream.SkipBlock())
7319           return Err;
7320         break;
7321       case bitc::BLOCKINFO_BLOCK_ID:
7322         // Need to parse these to get abbrev ids (e.g. for VST)
7323         if (Error Err = readBlockInfo())
7324           return Err;
7325         break;
7326       case bitc::VALUE_SYMTAB_BLOCK_ID:
7327         // Should have been parsed earlier via VSTOffset, unless there
7328         // is no summary section.
7329         assert(((SeenValueSymbolTable && VSTOffset > 0) ||
7330                 !SeenGlobalValSummary) &&
7331                "Expected early VST parse via VSTOffset record");
7332         if (Error Err = Stream.SkipBlock())
7333           return Err;
7334         break;
7335       case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
7336       case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
7337         // Add the module if it is a per-module index (has a source file name).
7338         if (!SourceFileName.empty())
7339           addThisModule();
7340         assert(!SeenValueSymbolTable &&
7341                "Already read VST when parsing summary block?");
7342         // We might not have a VST if there were no values in the
7343         // summary. An empty summary block generated when we are
7344         // performing ThinLTO compiles so we don't later invoke
7345         // the regular LTO process on them.
7346         if (VSTOffset > 0) {
7347           if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
7348             return Err;
7349           SeenValueSymbolTable = true;
7350         }
7351         SeenGlobalValSummary = true;
7352         if (Error Err = parseEntireSummary(Entry.ID))
7353           return Err;
7354         break;
7355       case bitc::MODULE_STRTAB_BLOCK_ID:
7356         if (Error Err = parseModuleStringTable())
7357           return Err;
7358         break;
7359       }
7360       continue;
7361 
7362     case BitstreamEntry::Record: {
7363         Record.clear();
7364         Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7365         if (!MaybeBitCode)
7366           return MaybeBitCode.takeError();
7367         switch (MaybeBitCode.get()) {
7368         default:
7369           break; // Default behavior, ignore unknown content.
7370         case bitc::MODULE_CODE_VERSION: {
7371           if (Error Err = parseVersionRecord(Record).takeError())
7372             return Err;
7373           break;
7374         }
7375         /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
7376         case bitc::MODULE_CODE_SOURCE_FILENAME: {
7377           SmallString<128> ValueName;
7378           if (convertToString(Record, 0, ValueName))
7379             return error("Invalid record");
7380           SourceFileName = ValueName.c_str();
7381           break;
7382         }
7383         /// MODULE_CODE_HASH: [5*i32]
7384         case bitc::MODULE_CODE_HASH: {
7385           if (Record.size() != 5)
7386             return error("Invalid hash length " + Twine(Record.size()).str());
7387           auto &Hash = getThisModule()->second;
7388           int Pos = 0;
7389           for (auto &Val : Record) {
7390             assert(!(Val >> 32) && "Unexpected high bits set");
7391             Hash[Pos++] = Val;
7392           }
7393           break;
7394         }
7395         /// MODULE_CODE_VSTOFFSET: [offset]
7396         case bitc::MODULE_CODE_VSTOFFSET:
7397           if (Record.empty())
7398             return error("Invalid record");
7399           // Note that we subtract 1 here because the offset is relative to one
7400           // word before the start of the identification or module block, which
7401           // was historically always the start of the regular bitcode header.
7402           VSTOffset = Record[0] - 1;
7403           break;
7404         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
7405         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
7406         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
7407         // v2: [strtab offset, strtab size, v1]
7408         case bitc::MODULE_CODE_GLOBALVAR:
7409         case bitc::MODULE_CODE_FUNCTION:
7410         case bitc::MODULE_CODE_ALIAS: {
7411           StringRef Name;
7412           ArrayRef<uint64_t> GVRecord;
7413           std::tie(Name, GVRecord) = readNameFromStrtab(Record);
7414           if (GVRecord.size() <= 3)
7415             return error("Invalid record");
7416           uint64_t RawLinkage = GVRecord[3];
7417           GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
7418           if (!UseStrtab) {
7419             ValueIdToLinkageMap[ValueId++] = Linkage;
7420             break;
7421           }
7422 
7423           setValueGUID(ValueId++, Name, Linkage, SourceFileName);
7424           break;
7425         }
7426         }
7427       }
7428       continue;
7429     }
7430   }
7431 }
7432 
7433 SmallVector<ValueInfo, 0>
7434 ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
7435   SmallVector<ValueInfo, 0> Ret;
7436   Ret.reserve(Record.size());
7437   for (uint64_t RefValueId : Record)
7438     Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
7439   return Ret;
7440 }
7441 
7442 SmallVector<FunctionSummary::EdgeTy, 0>
7443 ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
7444                                               bool IsOldProfileFormat,
7445                                               bool HasProfile, bool HasRelBF) {
7446   SmallVector<FunctionSummary::EdgeTy, 0> Ret;
7447   // In the case of new profile formats, there are two Record entries per
7448   // Edge. Otherwise, conservatively reserve up to Record.size.
7449   if (!IsOldProfileFormat && (HasProfile || HasRelBF))
7450     Ret.reserve(Record.size() / 2);
7451   else
7452     Ret.reserve(Record.size());
7453 
7454   for (unsigned I = 0, E = Record.size(); I != E; ++I) {
7455     CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
7456     bool HasTailCall = false;
7457     uint64_t RelBF = 0;
7458     ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7459     if (IsOldProfileFormat) {
7460       I += 1; // Skip old callsitecount field
7461       if (HasProfile)
7462         I += 1; // Skip old profilecount field
7463     } else if (HasProfile)
7464       std::tie(Hotness, HasTailCall) =
7465           getDecodedHotnessCallEdgeInfo(Record[++I]);
7466     else if (HasRelBF)
7467       getDecodedRelBFCallEdgeInfo(Record[++I], RelBF, HasTailCall);
7468     Ret.push_back(FunctionSummary::EdgeTy{
7469         Callee, CalleeInfo(Hotness, HasTailCall, RelBF)});
7470   }
7471   return Ret;
7472 }
7473 
7474 static void
7475 parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
7476                                        WholeProgramDevirtResolution &Wpd) {
7477   uint64_t ArgNum = Record[Slot++];
7478   WholeProgramDevirtResolution::ByArg &B =
7479       Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
7480   Slot += ArgNum;
7481 
7482   B.TheKind =
7483       static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
7484   B.Info = Record[Slot++];
7485   B.Byte = Record[Slot++];
7486   B.Bit = Record[Slot++];
7487 }
7488 
7489 static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
7490                                               StringRef Strtab, size_t &Slot,
7491                                               TypeIdSummary &TypeId) {
7492   uint64_t Id = Record[Slot++];
7493   WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
7494 
7495   Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
7496   Wpd.SingleImplName = {Strtab.data() + Record[Slot],
7497                         static_cast<size_t>(Record[Slot + 1])};
7498   Slot += 2;
7499 
7500   uint64_t ResByArgNum = Record[Slot++];
7501   for (uint64_t I = 0; I != ResByArgNum; ++I)
7502     parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
7503 }
7504 
7505 static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
7506                                      StringRef Strtab,
7507                                      ModuleSummaryIndex &TheIndex) {
7508   size_t Slot = 0;
7509   TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
7510       {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
7511   Slot += 2;
7512 
7513   TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
7514   TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
7515   TypeId.TTRes.AlignLog2 = Record[Slot++];
7516   TypeId.TTRes.SizeM1 = Record[Slot++];
7517   TypeId.TTRes.BitMask = Record[Slot++];
7518   TypeId.TTRes.InlineBits = Record[Slot++];
7519 
7520   while (Slot < Record.size())
7521     parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
7522 }
7523 
7524 std::vector<FunctionSummary::ParamAccess>
7525 ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
7526   auto ReadRange = [&]() {
7527     APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
7528                 BitcodeReader::decodeSignRotatedValue(Record.front()));
7529     Record = Record.drop_front();
7530     APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
7531                 BitcodeReader::decodeSignRotatedValue(Record.front()));
7532     Record = Record.drop_front();
7533     ConstantRange Range{Lower, Upper};
7534     assert(!Range.isFullSet());
7535     assert(!Range.isUpperSignWrapped());
7536     return Range;
7537   };
7538 
7539   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7540   while (!Record.empty()) {
7541     PendingParamAccesses.emplace_back();
7542     FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
7543     ParamAccess.ParamNo = Record.front();
7544     Record = Record.drop_front();
7545     ParamAccess.Use = ReadRange();
7546     ParamAccess.Calls.resize(Record.front());
7547     Record = Record.drop_front();
7548     for (auto &Call : ParamAccess.Calls) {
7549       Call.ParamNo = Record.front();
7550       Record = Record.drop_front();
7551       Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
7552       Record = Record.drop_front();
7553       Call.Offsets = ReadRange();
7554     }
7555   }
7556   return PendingParamAccesses;
7557 }
7558 
7559 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
7560     ArrayRef<uint64_t> Record, size_t &Slot,
7561     TypeIdCompatibleVtableInfo &TypeId) {
7562   uint64_t Offset = Record[Slot++];
7563   ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
7564   TypeId.push_back({Offset, Callee});
7565 }
7566 
7567 void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
7568     ArrayRef<uint64_t> Record) {
7569   size_t Slot = 0;
7570   TypeIdCompatibleVtableInfo &TypeId =
7571       TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
7572           {Strtab.data() + Record[Slot],
7573            static_cast<size_t>(Record[Slot + 1])});
7574   Slot += 2;
7575 
7576   while (Slot < Record.size())
7577     parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
7578 }
7579 
7580 SmallVector<unsigned> ModuleSummaryIndexBitcodeReader::parseAllocInfoContext(
7581     ArrayRef<uint64_t> Record, unsigned &I) {
7582   SmallVector<unsigned> StackIdList;
7583   // For backwards compatibility with old format before radix tree was
7584   // used, simply see if we found a radix tree array record (and thus if
7585   // the RadixArray is non-empty).
7586   if (RadixArray.empty()) {
7587     unsigned NumStackEntries = Record[I++];
7588     assert(Record.size() - I >= NumStackEntries);
7589     StackIdList.reserve(NumStackEntries);
7590     for (unsigned J = 0; J < NumStackEntries; J++) {
7591       assert(Record[I] < StackIds.size());
7592       StackIdList.push_back(
7593           TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
7594     }
7595   } else {
7596     unsigned RadixIndex = Record[I++];
7597     // See the comments above CallStackRadixTreeBuilder in ProfileData/MemProf.h
7598     // for a detailed description of the radix tree array format. Briefly, the
7599     // first entry will be the number of frames, any negative values are the
7600     // negative of the offset of the next frame, and otherwise the frames are in
7601     // increasing linear order.
7602     assert(RadixIndex < RadixArray.size());
7603     unsigned NumStackIds = RadixArray[RadixIndex++];
7604     StackIdList.reserve(NumStackIds);
7605     while (NumStackIds--) {
7606       assert(RadixIndex < RadixArray.size());
7607       unsigned Elem = RadixArray[RadixIndex];
7608       if (static_cast<std::make_signed_t<unsigned>>(Elem) < 0) {
7609         RadixIndex = RadixIndex - Elem;
7610         assert(RadixIndex < RadixArray.size());
7611         Elem = RadixArray[RadixIndex];
7612         // We shouldn't encounter a second offset in a row.
7613         assert(static_cast<std::make_signed_t<unsigned>>(Elem) >= 0);
7614       }
7615       RadixIndex++;
7616       StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[Elem]));
7617     }
7618   }
7619   return StackIdList;
7620 }
7621 
7622 static void setSpecialRefs(SmallVectorImpl<ValueInfo> &Refs, unsigned ROCnt,
7623                            unsigned WOCnt) {
7624   // Readonly and writeonly refs are in the end of the refs list.
7625   assert(ROCnt + WOCnt <= Refs.size());
7626   unsigned FirstWORef = Refs.size() - WOCnt;
7627   unsigned RefNo = FirstWORef - ROCnt;
7628   for (; RefNo < FirstWORef; ++RefNo)
7629     Refs[RefNo].setReadOnly();
7630   for (; RefNo < Refs.size(); ++RefNo)
7631     Refs[RefNo].setWriteOnly();
7632 }
7633 
7634 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
7635 // objects in the index.
7636 Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
7637   if (Error Err = Stream.EnterSubBlock(ID))
7638     return Err;
7639   SmallVector<uint64_t, 64> Record;
7640 
7641   // Parse version
7642   {
7643     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7644     if (!MaybeEntry)
7645       return MaybeEntry.takeError();
7646     BitstreamEntry Entry = MaybeEntry.get();
7647 
7648     if (Entry.Kind != BitstreamEntry::Record)
7649       return error("Invalid Summary Block: record for version expected");
7650     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
7651     if (!MaybeRecord)
7652       return MaybeRecord.takeError();
7653     if (MaybeRecord.get() != bitc::FS_VERSION)
7654       return error("Invalid Summary Block: version expected");
7655   }
7656   const uint64_t Version = Record[0];
7657   const bool IsOldProfileFormat = Version == 1;
7658   if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
7659     return error("Invalid summary version " + Twine(Version) +
7660                  ". Version should be in the range [1-" +
7661                  Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
7662                  "].");
7663   Record.clear();
7664 
7665   // Keep around the last seen summary to be used when we see an optional
7666   // "OriginalName" attachement.
7667   GlobalValueSummary *LastSeenSummary = nullptr;
7668   GlobalValue::GUID LastSeenGUID = 0;
7669 
7670   // We can expect to see any number of type ID information records before
7671   // each function summary records; these variables store the information
7672   // collected so far so that it can be used to create the summary object.
7673   std::vector<GlobalValue::GUID> PendingTypeTests;
7674   std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
7675       PendingTypeCheckedLoadVCalls;
7676   std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
7677       PendingTypeCheckedLoadConstVCalls;
7678   std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
7679 
7680   std::vector<CallsiteInfo> PendingCallsites;
7681   std::vector<AllocInfo> PendingAllocs;
7682   std::vector<uint64_t> PendingContextIds;
7683 
7684   while (true) {
7685     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
7686     if (!MaybeEntry)
7687       return MaybeEntry.takeError();
7688     BitstreamEntry Entry = MaybeEntry.get();
7689 
7690     switch (Entry.Kind) {
7691     case BitstreamEntry::SubBlock: // Handled for us already.
7692     case BitstreamEntry::Error:
7693       return error("Malformed block");
7694     case BitstreamEntry::EndBlock:
7695       return Error::success();
7696     case BitstreamEntry::Record:
7697       // The interesting case.
7698       break;
7699     }
7700 
7701     // Read a record. The record format depends on whether this
7702     // is a per-module index or a combined index file. In the per-module
7703     // case the records contain the associated value's ID for correlation
7704     // with VST entries. In the combined index the correlation is done
7705     // via the bitcode offset of the summary records (which were saved
7706     // in the combined index VST entries). The records also contain
7707     // information used for ThinLTO renaming and importing.
7708     Record.clear();
7709     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
7710     if (!MaybeBitCode)
7711       return MaybeBitCode.takeError();
7712     switch (unsigned BitCode = MaybeBitCode.get()) {
7713     default: // Default behavior: ignore.
7714       break;
7715     case bitc::FS_FLAGS: {  // [flags]
7716       TheIndex.setFlags(Record[0]);
7717       break;
7718     }
7719     case bitc::FS_VALUE_GUID: { // [valueid, refguid_upper32, refguid_lower32]
7720       uint64_t ValueID = Record[0];
7721       GlobalValue::GUID RefGUID;
7722       if (Version >= 11) {
7723         RefGUID = Record[1] << 32 | Record[2];
7724       } else {
7725         RefGUID = Record[1];
7726       }
7727       ValueIdToValueInfoMap[ValueID] =
7728           std::make_pair(TheIndex.getOrInsertValueInfo(RefGUID), RefGUID);
7729       break;
7730     }
7731     // FS_PERMODULE is legacy and does not have support for the tail call flag.
7732     // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
7733     //                numrefs x valueid, n x (valueid)]
7734     // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
7735     //                        numrefs x valueid,
7736     //                        n x (valueid, hotness+tailcall flags)]
7737     // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
7738     //                      numrefs x valueid,
7739     //                      n x (valueid, relblockfreq+tailcall)]
7740     case bitc::FS_PERMODULE:
7741     case bitc::FS_PERMODULE_RELBF:
7742     case bitc::FS_PERMODULE_PROFILE: {
7743       unsigned ValueID = Record[0];
7744       uint64_t RawFlags = Record[1];
7745       unsigned InstCount = Record[2];
7746       uint64_t RawFunFlags = 0;
7747       unsigned NumRefs = Record[3];
7748       unsigned NumRORefs = 0, NumWORefs = 0;
7749       int RefListStartIndex = 4;
7750       if (Version >= 4) {
7751         RawFunFlags = Record[3];
7752         NumRefs = Record[4];
7753         RefListStartIndex = 5;
7754         if (Version >= 5) {
7755           NumRORefs = Record[5];
7756           RefListStartIndex = 6;
7757           if (Version >= 7) {
7758             NumWORefs = Record[6];
7759             RefListStartIndex = 7;
7760           }
7761         }
7762       }
7763 
7764       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7765       // The module path string ref set in the summary must be owned by the
7766       // index's module string table. Since we don't have a module path
7767       // string table section in the per-module index, we create a single
7768       // module path string table entry with an empty (0) ID to take
7769       // ownership.
7770       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7771       assert(Record.size() >= RefListStartIndex + NumRefs &&
7772              "Record size inconsistent with number of references");
7773       SmallVector<ValueInfo, 0> Refs = makeRefList(
7774           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7775       bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
7776       bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
7777       SmallVector<FunctionSummary::EdgeTy, 0> Calls = makeCallList(
7778           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7779           IsOldProfileFormat, HasProfile, HasRelBF);
7780       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7781       auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
7782       // In order to save memory, only record the memprof summaries if this is
7783       // the prevailing copy of a symbol. The linker doesn't resolve local
7784       // linkage values so don't check whether those are prevailing.
7785       auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
7786       if (IsPrevailing && !GlobalValue::isLocalLinkage(LT) &&
7787           !IsPrevailing(VIAndOriginalGUID.first.getGUID())) {
7788         PendingCallsites.clear();
7789         PendingAllocs.clear();
7790       }
7791       auto FS = std::make_unique<FunctionSummary>(
7792           Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
7793           std::move(Calls), std::move(PendingTypeTests),
7794           std::move(PendingTypeTestAssumeVCalls),
7795           std::move(PendingTypeCheckedLoadVCalls),
7796           std::move(PendingTypeTestAssumeConstVCalls),
7797           std::move(PendingTypeCheckedLoadConstVCalls),
7798           std::move(PendingParamAccesses), std::move(PendingCallsites),
7799           std::move(PendingAllocs));
7800       FS->setModulePath(getThisModule()->first());
7801       FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
7802       TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
7803                                      std::move(FS));
7804       break;
7805     }
7806     // FS_ALIAS: [valueid, flags, valueid]
7807     // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
7808     // they expect all aliasee summaries to be available.
7809     case bitc::FS_ALIAS: {
7810       unsigned ValueID = Record[0];
7811       uint64_t RawFlags = Record[1];
7812       unsigned AliaseeID = Record[2];
7813       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7814       auto AS = std::make_unique<AliasSummary>(Flags);
7815       // The module path string ref set in the summary must be owned by the
7816       // index's module string table. Since we don't have a module path
7817       // string table section in the per-module index, we create a single
7818       // module path string table entry with an empty (0) ID to take
7819       // ownership.
7820       AS->setModulePath(getThisModule()->first());
7821 
7822       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
7823       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
7824       if (!AliaseeInModule)
7825         return error("Alias expects aliasee summary to be parsed");
7826       AS->setAliasee(AliaseeVI, AliaseeInModule);
7827 
7828       auto GUID = getValueInfoFromValueId(ValueID);
7829       AS->setOriginalName(std::get<1>(GUID));
7830       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
7831       break;
7832     }
7833     // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
7834     case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
7835       unsigned ValueID = Record[0];
7836       uint64_t RawFlags = Record[1];
7837       unsigned RefArrayStart = 2;
7838       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7839                                       /* WriteOnly */ false,
7840                                       /* Constant */ false,
7841                                       GlobalObject::VCallVisibilityPublic);
7842       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7843       if (Version >= 5) {
7844         GVF = getDecodedGVarFlags(Record[2]);
7845         RefArrayStart = 3;
7846       }
7847       SmallVector<ValueInfo, 0> Refs =
7848           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7849       auto FS =
7850           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7851       FS->setModulePath(getThisModule()->first());
7852       auto GUID = getValueInfoFromValueId(ValueID);
7853       FS->setOriginalName(std::get<1>(GUID));
7854       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
7855       break;
7856     }
7857     // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
7858     //                        numrefs, numrefs x valueid,
7859     //                        n x (valueid, offset)]
7860     case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
7861       unsigned ValueID = Record[0];
7862       uint64_t RawFlags = Record[1];
7863       GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
7864       unsigned NumRefs = Record[3];
7865       unsigned RefListStartIndex = 4;
7866       unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
7867       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7868       SmallVector<ValueInfo, 0> Refs = makeRefList(
7869           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7870       VTableFuncList VTableFuncs;
7871       for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
7872         ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
7873         uint64_t Offset = Record[++I];
7874         VTableFuncs.push_back({Callee, Offset});
7875       }
7876       auto VS =
7877           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7878       VS->setModulePath(getThisModule()->first());
7879       VS->setVTableFuncs(VTableFuncs);
7880       auto GUID = getValueInfoFromValueId(ValueID);
7881       VS->setOriginalName(std::get<1>(GUID));
7882       TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
7883       break;
7884     }
7885     // FS_COMBINED is legacy and does not have support for the tail call flag.
7886     // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
7887     //               numrefs x valueid, n x (valueid)]
7888     // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
7889     //                       numrefs x valueid,
7890     //                       n x (valueid, hotness+tailcall flags)]
7891     case bitc::FS_COMBINED:
7892     case bitc::FS_COMBINED_PROFILE: {
7893       unsigned ValueID = Record[0];
7894       uint64_t ModuleId = Record[1];
7895       uint64_t RawFlags = Record[2];
7896       unsigned InstCount = Record[3];
7897       uint64_t RawFunFlags = 0;
7898       unsigned NumRefs = Record[4];
7899       unsigned NumRORefs = 0, NumWORefs = 0;
7900       int RefListStartIndex = 5;
7901 
7902       if (Version >= 4) {
7903         RawFunFlags = Record[4];
7904         RefListStartIndex = 6;
7905         size_t NumRefsIndex = 5;
7906         if (Version >= 5) {
7907           unsigned NumRORefsOffset = 1;
7908           RefListStartIndex = 7;
7909           if (Version >= 6) {
7910             NumRefsIndex = 6;
7911             RefListStartIndex = 8;
7912             if (Version >= 7) {
7913               RefListStartIndex = 9;
7914               NumWORefs = Record[8];
7915               NumRORefsOffset = 2;
7916             }
7917           }
7918           NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
7919         }
7920         NumRefs = Record[NumRefsIndex];
7921       }
7922 
7923       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7924       int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
7925       assert(Record.size() >= RefListStartIndex + NumRefs &&
7926              "Record size inconsistent with number of references");
7927       SmallVector<ValueInfo, 0> Refs = makeRefList(
7928           ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
7929       bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
7930       SmallVector<FunctionSummary::EdgeTy, 0> Edges = makeCallList(
7931           ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
7932           IsOldProfileFormat, HasProfile, false);
7933       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7934       setSpecialRefs(Refs, NumRORefs, NumWORefs);
7935       auto FS = std::make_unique<FunctionSummary>(
7936           Flags, InstCount, getDecodedFFlags(RawFunFlags), std::move(Refs),
7937           std::move(Edges), std::move(PendingTypeTests),
7938           std::move(PendingTypeTestAssumeVCalls),
7939           std::move(PendingTypeCheckedLoadVCalls),
7940           std::move(PendingTypeTestAssumeConstVCalls),
7941           std::move(PendingTypeCheckedLoadConstVCalls),
7942           std::move(PendingParamAccesses), std::move(PendingCallsites),
7943           std::move(PendingAllocs));
7944       LastSeenSummary = FS.get();
7945       LastSeenGUID = VI.getGUID();
7946       FS->setModulePath(ModuleIdMap[ModuleId]);
7947       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7948       break;
7949     }
7950     // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
7951     // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
7952     // they expect all aliasee summaries to be available.
7953     case bitc::FS_COMBINED_ALIAS: {
7954       unsigned ValueID = Record[0];
7955       uint64_t ModuleId = Record[1];
7956       uint64_t RawFlags = Record[2];
7957       unsigned AliaseeValueId = Record[3];
7958       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7959       auto AS = std::make_unique<AliasSummary>(Flags);
7960       LastSeenSummary = AS.get();
7961       AS->setModulePath(ModuleIdMap[ModuleId]);
7962 
7963       auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
7964       auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
7965       AS->setAliasee(AliaseeVI, AliaseeInModule);
7966 
7967       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7968       LastSeenGUID = VI.getGUID();
7969       TheIndex.addGlobalValueSummary(VI, std::move(AS));
7970       break;
7971     }
7972     // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
7973     case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
7974       unsigned ValueID = Record[0];
7975       uint64_t ModuleId = Record[1];
7976       uint64_t RawFlags = Record[2];
7977       unsigned RefArrayStart = 3;
7978       GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
7979                                       /* WriteOnly */ false,
7980                                       /* Constant */ false,
7981                                       GlobalObject::VCallVisibilityPublic);
7982       auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
7983       if (Version >= 5) {
7984         GVF = getDecodedGVarFlags(Record[3]);
7985         RefArrayStart = 4;
7986       }
7987       SmallVector<ValueInfo, 0> Refs =
7988           makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
7989       auto FS =
7990           std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
7991       LastSeenSummary = FS.get();
7992       FS->setModulePath(ModuleIdMap[ModuleId]);
7993       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
7994       LastSeenGUID = VI.getGUID();
7995       TheIndex.addGlobalValueSummary(VI, std::move(FS));
7996       break;
7997     }
7998     // FS_COMBINED_ORIGINAL_NAME: [original_name]
7999     case bitc::FS_COMBINED_ORIGINAL_NAME: {
8000       uint64_t OriginalName = Record[0];
8001       if (!LastSeenSummary)
8002         return error("Name attachment that does not follow a combined record");
8003       LastSeenSummary->setOriginalName(OriginalName);
8004       TheIndex.addOriginalName(LastSeenGUID, OriginalName);
8005       // Reset the LastSeenSummary
8006       LastSeenSummary = nullptr;
8007       LastSeenGUID = 0;
8008       break;
8009     }
8010     case bitc::FS_TYPE_TESTS:
8011       assert(PendingTypeTests.empty());
8012       llvm::append_range(PendingTypeTests, Record);
8013       break;
8014 
8015     case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
8016       assert(PendingTypeTestAssumeVCalls.empty());
8017       for (unsigned I = 0; I != Record.size(); I += 2)
8018         PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
8019       break;
8020 
8021     case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
8022       assert(PendingTypeCheckedLoadVCalls.empty());
8023       for (unsigned I = 0; I != Record.size(); I += 2)
8024         PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
8025       break;
8026 
8027     case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
8028       PendingTypeTestAssumeConstVCalls.push_back(
8029           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8030       break;
8031 
8032     case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
8033       PendingTypeCheckedLoadConstVCalls.push_back(
8034           {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
8035       break;
8036 
8037     case bitc::FS_CFI_FUNCTION_DEFS: {
8038       std::set<std::string, std::less<>> &CfiFunctionDefs =
8039           TheIndex.cfiFunctionDefs();
8040       for (unsigned I = 0; I != Record.size(); I += 2)
8041         CfiFunctionDefs.insert(
8042             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
8043       break;
8044     }
8045 
8046     case bitc::FS_CFI_FUNCTION_DECLS: {
8047       std::set<std::string, std::less<>> &CfiFunctionDecls =
8048           TheIndex.cfiFunctionDecls();
8049       for (unsigned I = 0; I != Record.size(); I += 2)
8050         CfiFunctionDecls.insert(
8051             {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
8052       break;
8053     }
8054 
8055     case bitc::FS_TYPE_ID:
8056       parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
8057       break;
8058 
8059     case bitc::FS_TYPE_ID_METADATA:
8060       parseTypeIdCompatibleVtableSummaryRecord(Record);
8061       break;
8062 
8063     case bitc::FS_BLOCK_COUNT:
8064       TheIndex.addBlockCount(Record[0]);
8065       break;
8066 
8067     case bitc::FS_PARAM_ACCESS: {
8068       PendingParamAccesses = parseParamAccesses(Record);
8069       break;
8070     }
8071 
8072     case bitc::FS_STACK_IDS: { // [n x stackid]
8073       // Save stack ids in the reader to consult when adding stack ids from the
8074       // lists in the stack node and alloc node entries.
8075       if (Version <= 11) {
8076         StackIds = ArrayRef<uint64_t>(Record);
8077         break;
8078       }
8079       // This is an array of 32-bit fixed-width values, holding each 64-bit
8080       // context id as a pair of adjacent (most significant first) 32-bit words.
8081       assert(Record.size() % 2 == 0);
8082       StackIds.reserve(Record.size() / 2);
8083       for (auto R = Record.begin(); R != Record.end(); R += 2)
8084         StackIds.push_back(*R << 32 | *(R + 1));
8085       break;
8086     }
8087 
8088     case bitc::FS_CONTEXT_RADIX_TREE_ARRAY: { // [n x entry]
8089       RadixArray = ArrayRef<uint64_t>(Record);
8090       break;
8091     }
8092 
8093     case bitc::FS_PERMODULE_CALLSITE_INFO: {
8094       unsigned ValueID = Record[0];
8095       SmallVector<unsigned> StackIdList;
8096       for (auto R = Record.begin() + 1; R != Record.end(); R++) {
8097         assert(*R < StackIds.size());
8098         StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
8099       }
8100       ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
8101       PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
8102       break;
8103     }
8104 
8105     case bitc::FS_COMBINED_CALLSITE_INFO: {
8106       auto RecordIter = Record.begin();
8107       unsigned ValueID = *RecordIter++;
8108       unsigned NumStackIds = *RecordIter++;
8109       unsigned NumVersions = *RecordIter++;
8110       assert(Record.size() == 3 + NumStackIds + NumVersions);
8111       SmallVector<unsigned> StackIdList;
8112       for (unsigned J = 0; J < NumStackIds; J++) {
8113         assert(*RecordIter < StackIds.size());
8114         StackIdList.push_back(
8115             TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
8116       }
8117       SmallVector<unsigned> Versions;
8118       for (unsigned J = 0; J < NumVersions; J++)
8119         Versions.push_back(*RecordIter++);
8120       ValueInfo VI = std::get<0>(
8121           getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
8122       PendingCallsites.push_back(
8123           CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
8124       break;
8125     }
8126 
8127     case bitc::FS_ALLOC_CONTEXT_IDS: {
8128       // This is an array of 32-bit fixed-width values, holding each 64-bit
8129       // context id as a pair of adjacent (most significant first) 32-bit words.
8130       assert(Record.size() % 2 == 0);
8131       PendingContextIds.reserve(Record.size() / 2);
8132       for (auto R = Record.begin(); R != Record.end(); R += 2)
8133         PendingContextIds.push_back(*R << 32 | *(R + 1));
8134       break;
8135     }
8136 
8137     case bitc::FS_PERMODULE_ALLOC_INFO: {
8138       unsigned I = 0;
8139       std::vector<MIBInfo> MIBs;
8140       unsigned NumMIBs = 0;
8141       if (Version >= 10)
8142         NumMIBs = Record[I++];
8143       unsigned MIBsRead = 0;
8144       while ((Version >= 10 && MIBsRead++ < NumMIBs) ||
8145              (Version < 10 && I < Record.size())) {
8146         assert(Record.size() - I >= 2);
8147         AllocationType AllocType = (AllocationType)Record[I++];
8148         auto StackIdList = parseAllocInfoContext(Record, I);
8149         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8150       }
8151       // We either have nothing left or at least NumMIBs context size info
8152       // indices left (for the total sizes included when reporting of hinted
8153       // bytes is enabled).
8154       assert(I == Record.size() || Record.size() - I >= NumMIBs);
8155       std::vector<std::vector<ContextTotalSize>> AllContextSizes;
8156       if (I < Record.size()) {
8157         assert(!PendingContextIds.empty() &&
8158                "Missing context ids for alloc sizes");
8159         unsigned ContextIdIndex = 0;
8160         MIBsRead = 0;
8161         // The sizes are a linearized array of sizes, where for each MIB there
8162         // is 1 or more sizes (due to context trimming, each MIB in the metadata
8163         // and summarized here can correspond to more than one original context
8164         // from the profile).
8165         while (MIBsRead++ < NumMIBs) {
8166           // First read the number of contexts recorded for this MIB.
8167           unsigned NumContextSizeInfoEntries = Record[I++];
8168           assert(Record.size() - I >= NumContextSizeInfoEntries);
8169           std::vector<ContextTotalSize> ContextSizes;
8170           ContextSizes.reserve(NumContextSizeInfoEntries);
8171           for (unsigned J = 0; J < NumContextSizeInfoEntries; J++) {
8172             assert(ContextIdIndex < PendingContextIds.size());
8173             // PendingContextIds read from the preceding FS_ALLOC_CONTEXT_IDS
8174             // should be in the same order as the total sizes.
8175             ContextSizes.push_back(
8176                 {PendingContextIds[ContextIdIndex++], Record[I++]});
8177           }
8178           AllContextSizes.push_back(std::move(ContextSizes));
8179         }
8180         PendingContextIds.clear();
8181       }
8182       PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
8183       if (!AllContextSizes.empty()) {
8184         assert(PendingAllocs.back().MIBs.size() == AllContextSizes.size());
8185         PendingAllocs.back().ContextSizeInfos = std::move(AllContextSizes);
8186       }
8187       break;
8188     }
8189 
8190     case bitc::FS_COMBINED_ALLOC_INFO: {
8191       unsigned I = 0;
8192       std::vector<MIBInfo> MIBs;
8193       unsigned NumMIBs = Record[I++];
8194       unsigned NumVersions = Record[I++];
8195       unsigned MIBsRead = 0;
8196       while (MIBsRead++ < NumMIBs) {
8197         assert(Record.size() - I >= 2);
8198         AllocationType AllocType = (AllocationType)Record[I++];
8199         auto StackIdList = parseAllocInfoContext(Record, I);
8200         MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
8201       }
8202       assert(Record.size() - I >= NumVersions);
8203       SmallVector<uint8_t> Versions;
8204       for (unsigned J = 0; J < NumVersions; J++)
8205         Versions.push_back(Record[I++]);
8206       assert(I == Record.size());
8207       PendingAllocs.push_back(AllocInfo(std::move(Versions), std::move(MIBs)));
8208       break;
8209     }
8210     }
8211   }
8212   llvm_unreachable("Exit infinite loop");
8213 }
8214 
8215 // Parse the  module string table block into the Index.
8216 // This populates the ModulePathStringTable map in the index.
8217 Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
8218   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
8219     return Err;
8220 
8221   SmallVector<uint64_t, 64> Record;
8222 
8223   SmallString<128> ModulePath;
8224   ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
8225 
8226   while (true) {
8227     Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
8228     if (!MaybeEntry)
8229       return MaybeEntry.takeError();
8230     BitstreamEntry Entry = MaybeEntry.get();
8231 
8232     switch (Entry.Kind) {
8233     case BitstreamEntry::SubBlock: // Handled for us already.
8234     case BitstreamEntry::Error:
8235       return error("Malformed block");
8236     case BitstreamEntry::EndBlock:
8237       return Error::success();
8238     case BitstreamEntry::Record:
8239       // The interesting case.
8240       break;
8241     }
8242 
8243     Record.clear();
8244     Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
8245     if (!MaybeRecord)
8246       return MaybeRecord.takeError();
8247     switch (MaybeRecord.get()) {
8248     default: // Default behavior: ignore.
8249       break;
8250     case bitc::MST_CODE_ENTRY: {
8251       // MST_ENTRY: [modid, namechar x N]
8252       uint64_t ModuleId = Record[0];
8253 
8254       if (convertToString(Record, 1, ModulePath))
8255         return error("Invalid record");
8256 
8257       LastSeenModule = TheIndex.addModule(ModulePath);
8258       ModuleIdMap[ModuleId] = LastSeenModule->first();
8259 
8260       ModulePath.clear();
8261       break;
8262     }
8263     /// MST_CODE_HASH: [5*i32]
8264     case bitc::MST_CODE_HASH: {
8265       if (Record.size() != 5)
8266         return error("Invalid hash length " + Twine(Record.size()).str());
8267       if (!LastSeenModule)
8268         return error("Invalid hash that does not follow a module path");
8269       int Pos = 0;
8270       for (auto &Val : Record) {
8271         assert(!(Val >> 32) && "Unexpected high bits set");
8272         LastSeenModule->second[Pos++] = Val;
8273       }
8274       // Reset LastSeenModule to avoid overriding the hash unexpectedly.
8275       LastSeenModule = nullptr;
8276       break;
8277     }
8278     }
8279   }
8280   llvm_unreachable("Exit infinite loop");
8281 }
8282 
8283 namespace {
8284 
8285 // FIXME: This class is only here to support the transition to llvm::Error. It
8286 // will be removed once this transition is complete. Clients should prefer to
8287 // deal with the Error value directly, rather than converting to error_code.
8288 class BitcodeErrorCategoryType : public std::error_category {
8289   const char *name() const noexcept override {
8290     return "llvm.bitcode";
8291   }
8292 
8293   std::string message(int IE) const override {
8294     BitcodeError E = static_cast<BitcodeError>(IE);
8295     switch (E) {
8296     case BitcodeError::CorruptedBitcode:
8297       return "Corrupted bitcode";
8298     }
8299     llvm_unreachable("Unknown error type!");
8300   }
8301 };
8302 
8303 } // end anonymous namespace
8304 
8305 const std::error_category &llvm::BitcodeErrorCategory() {
8306   static BitcodeErrorCategoryType ErrorCategory;
8307   return ErrorCategory;
8308 }
8309 
8310 static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
8311                                             unsigned Block, unsigned RecordID) {
8312   if (Error Err = Stream.EnterSubBlock(Block))
8313     return std::move(Err);
8314 
8315   StringRef Strtab;
8316   while (true) {
8317     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8318     if (!MaybeEntry)
8319       return MaybeEntry.takeError();
8320     llvm::BitstreamEntry Entry = MaybeEntry.get();
8321 
8322     switch (Entry.Kind) {
8323     case BitstreamEntry::EndBlock:
8324       return Strtab;
8325 
8326     case BitstreamEntry::Error:
8327       return error("Malformed block");
8328 
8329     case BitstreamEntry::SubBlock:
8330       if (Error Err = Stream.SkipBlock())
8331         return std::move(Err);
8332       break;
8333 
8334     case BitstreamEntry::Record:
8335       StringRef Blob;
8336       SmallVector<uint64_t, 1> Record;
8337       Expected<unsigned> MaybeRecord =
8338           Stream.readRecord(Entry.ID, Record, &Blob);
8339       if (!MaybeRecord)
8340         return MaybeRecord.takeError();
8341       if (MaybeRecord.get() == RecordID)
8342         Strtab = Blob;
8343       break;
8344     }
8345   }
8346 }
8347 
8348 //===----------------------------------------------------------------------===//
8349 // External interface
8350 //===----------------------------------------------------------------------===//
8351 
8352 Expected<std::vector<BitcodeModule>>
8353 llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
8354   auto FOrErr = getBitcodeFileContents(Buffer);
8355   if (!FOrErr)
8356     return FOrErr.takeError();
8357   return std::move(FOrErr->Mods);
8358 }
8359 
8360 Expected<BitcodeFileContents>
8361 llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
8362   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8363   if (!StreamOrErr)
8364     return StreamOrErr.takeError();
8365   BitstreamCursor &Stream = *StreamOrErr;
8366 
8367   BitcodeFileContents F;
8368   while (true) {
8369     uint64_t BCBegin = Stream.getCurrentByteNo();
8370 
8371     // We may be consuming bitcode from a client that leaves garbage at the end
8372     // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
8373     // the end that there cannot possibly be another module, stop looking.
8374     if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
8375       return F;
8376 
8377     Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8378     if (!MaybeEntry)
8379       return MaybeEntry.takeError();
8380     llvm::BitstreamEntry Entry = MaybeEntry.get();
8381 
8382     switch (Entry.Kind) {
8383     case BitstreamEntry::EndBlock:
8384     case BitstreamEntry::Error:
8385       return error("Malformed block");
8386 
8387     case BitstreamEntry::SubBlock: {
8388       uint64_t IdentificationBit = -1ull;
8389       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
8390         IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8391         if (Error Err = Stream.SkipBlock())
8392           return std::move(Err);
8393 
8394         {
8395           Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
8396           if (!MaybeEntry)
8397             return MaybeEntry.takeError();
8398           Entry = MaybeEntry.get();
8399         }
8400 
8401         if (Entry.Kind != BitstreamEntry::SubBlock ||
8402             Entry.ID != bitc::MODULE_BLOCK_ID)
8403           return error("Malformed block");
8404       }
8405 
8406       if (Entry.ID == bitc::MODULE_BLOCK_ID) {
8407         uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
8408         if (Error Err = Stream.SkipBlock())
8409           return std::move(Err);
8410 
8411         F.Mods.push_back({Stream.getBitcodeBytes().slice(
8412                               BCBegin, Stream.getCurrentByteNo() - BCBegin),
8413                           Buffer.getBufferIdentifier(), IdentificationBit,
8414                           ModuleBit});
8415         continue;
8416       }
8417 
8418       if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
8419         Expected<StringRef> Strtab =
8420             readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
8421         if (!Strtab)
8422           return Strtab.takeError();
8423         // This string table is used by every preceding bitcode module that does
8424         // not have its own string table. A bitcode file may have multiple
8425         // string tables if it was created by binary concatenation, for example
8426         // with "llvm-cat -b".
8427         for (BitcodeModule &I : llvm::reverse(F.Mods)) {
8428           if (!I.Strtab.empty())
8429             break;
8430           I.Strtab = *Strtab;
8431         }
8432         // Similarly, the string table is used by every preceding symbol table;
8433         // normally there will be just one unless the bitcode file was created
8434         // by binary concatenation.
8435         if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
8436           F.StrtabForSymtab = *Strtab;
8437         continue;
8438       }
8439 
8440       if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
8441         Expected<StringRef> SymtabOrErr =
8442             readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
8443         if (!SymtabOrErr)
8444           return SymtabOrErr.takeError();
8445 
8446         // We can expect the bitcode file to have multiple symbol tables if it
8447         // was created by binary concatenation. In that case we silently
8448         // ignore any subsequent symbol tables, which is fine because this is a
8449         // low level function. The client is expected to notice that the number
8450         // of modules in the symbol table does not match the number of modules
8451         // in the input file and regenerate the symbol table.
8452         if (F.Symtab.empty())
8453           F.Symtab = *SymtabOrErr;
8454         continue;
8455       }
8456 
8457       if (Error Err = Stream.SkipBlock())
8458         return std::move(Err);
8459       continue;
8460     }
8461     case BitstreamEntry::Record:
8462       if (Error E = Stream.skipRecord(Entry.ID).takeError())
8463         return std::move(E);
8464       continue;
8465     }
8466   }
8467 }
8468 
8469 /// Get a lazy one-at-time loading module from bitcode.
8470 ///
8471 /// This isn't always used in a lazy context.  In particular, it's also used by
8472 /// \a parseModule().  If this is truly lazy, then we need to eagerly pull
8473 /// in forward-referenced functions from block address references.
8474 ///
8475 /// \param[in] MaterializeAll Set to \c true if we should materialize
8476 /// everything.
8477 Expected<std::unique_ptr<Module>>
8478 BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
8479                              bool ShouldLazyLoadMetadata, bool IsImporting,
8480                              ParserCallbacks Callbacks) {
8481   BitstreamCursor Stream(Buffer);
8482 
8483   std::string ProducerIdentification;
8484   if (IdentificationBit != -1ull) {
8485     if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
8486       return std::move(JumpFailed);
8487     if (Error E =
8488             readIdentificationBlock(Stream).moveInto(ProducerIdentification))
8489       return std::move(E);
8490   }
8491 
8492   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8493     return std::move(JumpFailed);
8494   auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
8495                               Context);
8496 
8497   std::unique_ptr<Module> M =
8498       std::make_unique<Module>(ModuleIdentifier, Context);
8499   M->setMaterializer(R);
8500 
8501   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
8502   if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
8503                                       IsImporting, Callbacks))
8504     return std::move(Err);
8505 
8506   if (MaterializeAll) {
8507     // Read in the entire module, and destroy the BitcodeReader.
8508     if (Error Err = M->materializeAll())
8509       return std::move(Err);
8510   } else {
8511     // Resolve forward references from blockaddresses.
8512     if (Error Err = R->materializeForwardReferencedFunctions())
8513       return std::move(Err);
8514   }
8515 
8516   return std::move(M);
8517 }
8518 
8519 Expected<std::unique_ptr<Module>>
8520 BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
8521                              bool IsImporting, ParserCallbacks Callbacks) {
8522   return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
8523                        Callbacks);
8524 }
8525 
8526 // Parse the specified bitcode buffer and merge the index into CombinedIndex.
8527 // We don't use ModuleIdentifier here because the client may need to control the
8528 // module path used in the combined summary (e.g. when reading summaries for
8529 // regular LTO modules).
8530 Error BitcodeModule::readSummary(
8531     ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
8532     std::function<bool(GlobalValue::GUID)> IsPrevailing) {
8533   BitstreamCursor Stream(Buffer);
8534   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8535     return JumpFailed;
8536 
8537   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
8538                                     ModulePath, IsPrevailing);
8539   return R.parseModule();
8540 }
8541 
8542 // Parse the specified bitcode buffer, returning the function info index.
8543 Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
8544   BitstreamCursor Stream(Buffer);
8545   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8546     return std::move(JumpFailed);
8547 
8548   auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
8549   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
8550                                     ModuleIdentifier, 0);
8551 
8552   if (Error Err = R.parseModule())
8553     return std::move(Err);
8554 
8555   return std::move(Index);
8556 }
8557 
8558 static Expected<std::pair<bool, bool>>
8559 getEnableSplitLTOUnitAndUnifiedFlag(BitstreamCursor &Stream,
8560                                                  unsigned ID,
8561                                                  BitcodeLTOInfo &LTOInfo) {
8562   if (Error Err = Stream.EnterSubBlock(ID))
8563     return std::move(Err);
8564   SmallVector<uint64_t, 64> Record;
8565 
8566   while (true) {
8567     BitstreamEntry Entry;
8568     std::pair<bool, bool> Result = {false,false};
8569     if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
8570       return std::move(E);
8571 
8572     switch (Entry.Kind) {
8573     case BitstreamEntry::SubBlock: // Handled for us already.
8574     case BitstreamEntry::Error:
8575       return error("Malformed block");
8576     case BitstreamEntry::EndBlock: {
8577       // If no flags record found, set both flags to false.
8578       return Result;
8579     }
8580     case BitstreamEntry::Record:
8581       // The interesting case.
8582       break;
8583     }
8584 
8585     // Look for the FS_FLAGS record.
8586     Record.clear();
8587     Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
8588     if (!MaybeBitCode)
8589       return MaybeBitCode.takeError();
8590     switch (MaybeBitCode.get()) {
8591     default: // Default behavior: ignore.
8592       break;
8593     case bitc::FS_FLAGS: { // [flags]
8594       uint64_t Flags = Record[0];
8595       // Scan flags.
8596       assert(Flags <= 0x2ff && "Unexpected bits in flag");
8597 
8598       bool EnableSplitLTOUnit = Flags & 0x8;
8599       bool UnifiedLTO = Flags & 0x200;
8600       Result = {EnableSplitLTOUnit, UnifiedLTO};
8601 
8602       return Result;
8603     }
8604     }
8605   }
8606   llvm_unreachable("Exit infinite loop");
8607 }
8608 
8609 // Check if the given bitcode buffer contains a global value summary block.
8610 Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
8611   BitstreamCursor Stream(Buffer);
8612   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
8613     return std::move(JumpFailed);
8614 
8615   if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
8616     return std::move(Err);
8617 
8618   while (true) {
8619     llvm::BitstreamEntry Entry;
8620     if (Error E = Stream.advance().moveInto(Entry))
8621       return std::move(E);
8622 
8623     switch (Entry.Kind) {
8624     case BitstreamEntry::Error:
8625       return error("Malformed block");
8626     case BitstreamEntry::EndBlock:
8627       return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
8628                             /*EnableSplitLTOUnit=*/false, /*UnifiedLTO=*/false};
8629 
8630     case BitstreamEntry::SubBlock:
8631       if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
8632         BitcodeLTOInfo LTOInfo;
8633         Expected<std::pair<bool, bool>> Flags =
8634             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8635         if (!Flags)
8636           return Flags.takeError();
8637         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8638         LTOInfo.IsThinLTO = true;
8639         LTOInfo.HasSummary = true;
8640         return LTOInfo;
8641       }
8642 
8643       if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
8644         BitcodeLTOInfo LTOInfo;
8645         Expected<std::pair<bool, bool>> Flags =
8646             getEnableSplitLTOUnitAndUnifiedFlag(Stream, Entry.ID, LTOInfo);
8647         if (!Flags)
8648           return Flags.takeError();
8649         std::tie(LTOInfo.EnableSplitLTOUnit, LTOInfo.UnifiedLTO) = Flags.get();
8650         LTOInfo.IsThinLTO = false;
8651         LTOInfo.HasSummary = true;
8652         return LTOInfo;
8653       }
8654 
8655       // Ignore other sub-blocks.
8656       if (Error Err = Stream.SkipBlock())
8657         return std::move(Err);
8658       continue;
8659 
8660     case BitstreamEntry::Record:
8661       if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
8662         continue;
8663       else
8664         return StreamFailed.takeError();
8665     }
8666   }
8667 }
8668 
8669 static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
8670   Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
8671   if (!MsOrErr)
8672     return MsOrErr.takeError();
8673 
8674   if (MsOrErr->size() != 1)
8675     return error("Expected a single module");
8676 
8677   return (*MsOrErr)[0];
8678 }
8679 
8680 Expected<std::unique_ptr<Module>>
8681 llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
8682                            bool ShouldLazyLoadMetadata, bool IsImporting,
8683                            ParserCallbacks Callbacks) {
8684   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8685   if (!BM)
8686     return BM.takeError();
8687 
8688   return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
8689                            Callbacks);
8690 }
8691 
8692 Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
8693     std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
8694     bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
8695   auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
8696                                      IsImporting, Callbacks);
8697   if (MOrErr)
8698     (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
8699   return MOrErr;
8700 }
8701 
8702 Expected<std::unique_ptr<Module>>
8703 BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
8704   return getModuleImpl(Context, true, false, false, Callbacks);
8705   // TODO: Restore the use-lists to the in-memory state when the bitcode was
8706   // written.  We must defer until the Module has been fully materialized.
8707 }
8708 
8709 Expected<std::unique_ptr<Module>>
8710 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
8711                        ParserCallbacks Callbacks) {
8712   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8713   if (!BM)
8714     return BM.takeError();
8715 
8716   return BM->parseModule(Context, Callbacks);
8717 }
8718 
8719 Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
8720   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8721   if (!StreamOrErr)
8722     return StreamOrErr.takeError();
8723 
8724   return readTriple(*StreamOrErr);
8725 }
8726 
8727 Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
8728   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8729   if (!StreamOrErr)
8730     return StreamOrErr.takeError();
8731 
8732   return hasObjCCategory(*StreamOrErr);
8733 }
8734 
8735 Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
8736   Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
8737   if (!StreamOrErr)
8738     return StreamOrErr.takeError();
8739 
8740   return readIdentificationCode(*StreamOrErr);
8741 }
8742 
8743 Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
8744                                    ModuleSummaryIndex &CombinedIndex) {
8745   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8746   if (!BM)
8747     return BM.takeError();
8748 
8749   return BM->readSummary(CombinedIndex, BM->getModuleIdentifier());
8750 }
8751 
8752 Expected<std::unique_ptr<ModuleSummaryIndex>>
8753 llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
8754   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8755   if (!BM)
8756     return BM.takeError();
8757 
8758   return BM->getSummary();
8759 }
8760 
8761 Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
8762   Expected<BitcodeModule> BM = getSingleModule(Buffer);
8763   if (!BM)
8764     return BM.takeError();
8765 
8766   return BM->getLTOInfo();
8767 }
8768 
8769 Expected<std::unique_ptr<ModuleSummaryIndex>>
8770 llvm::getModuleSummaryIndexForFile(StringRef Path,
8771                                    bool IgnoreEmptyThinLTOIndexFile) {
8772   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
8773       MemoryBuffer::getFileOrSTDIN(Path);
8774   if (!FileOrErr)
8775     return errorCodeToError(FileOrErr.getError());
8776   if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
8777     return nullptr;
8778   return getModuleSummaryIndex(**FileOrErr);
8779 }
8780