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