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