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