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