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