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