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