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