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