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