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