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