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