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