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