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