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