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