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