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