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