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