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