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