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