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