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