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