BitcodeReader.cpp revision 933b5a904f7215c692b41a1c0481f4ea5f4abde1
1551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//
3551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//                     The LLVM Compiler Infrastructure
4551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//
5551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines// This file is distributed under the University of Illinois Open Source
6551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines// License. See LICENSE.TXT for details.
7551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//
8551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//===----------------------------------------------------------------------===//
937b74a387bb3993387029859c2d9d051c41c724eStephen Hines//
1037b74a387bb3993387029859c2d9d051c41c724eStephen Hines// This header defines the BitcodeReader class.
11551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//
12551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//===----------------------------------------------------------------------===//
13551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
14551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/Bitcode/ReaderWriter.h"
15551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "BitReader_2_7.h"
16551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/ADT/STLExtras.h"
17551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/ADT/SmallString.h"
18551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/ADT/SmallVector.h"
19551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/AutoUpgrade.h"
2037b74a387bb3993387029859c2d9d051c41c724eStephen Hines#include "llvm/IR/Constants.h"
2137b74a387bb3993387029859c2d9d051c41c724eStephen Hines#include "llvm/IR/DerivedTypes.h"
22551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/DiagnosticPrinter.h"
23551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/GVMaterializer.h"
24551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/InlineAsm.h"
25551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/IntrinsicInst.h"
26551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/LLVMContext.h"
27551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/Module.h"
28551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/OperandTraits.h"
29551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/IR/Operator.h"
30551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/Support/ManagedStatic.h"
31551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#include "llvm/Support/MathExtras.h"
3237b74a387bb3993387029859c2d9d051c41c724eStephen Hines#include "llvm/Support/MemoryBuffer.h"
3337b74a387bb3993387029859c2d9d051c41c724eStephen Hines
3437b74a387bb3993387029859c2d9d051c41c724eStephen Hinesusing namespace llvm;
35551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hinesusing namespace llvm_2_7;
36551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
3737b74a387bb3993387029859c2d9d051c41c724eStephen Hines#define METADATA_NODE_2_7             2
3837b74a387bb3993387029859c2d9d051c41c724eStephen Hines#define METADATA_FN_NODE_2_7          3
3937b74a387bb3993387029859c2d9d051c41c724eStephen Hines#define METADATA_NAMED_NODE_2_7       5
40551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define METADATA_ATTACHMENT_2_7       7
41551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define FUNC_CODE_INST_UNWIND_2_7     14
4237b74a387bb3993387029859c2d9d051c41c724eStephen Hines#define FUNC_CODE_INST_MALLOC_2_7     17
43551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define FUNC_CODE_INST_FREE_2_7       18
44551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define FUNC_CODE_INST_STORE_2_7      21
45551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define FUNC_CODE_INST_CALL_2_7       22
4637b74a387bb3993387029859c2d9d051c41c724eStephen Hines#define FUNC_CODE_INST_GETRESULT_2_7  25
4737b74a387bb3993387029859c2d9d051c41c724eStephen Hines#define FUNC_CODE_DEBUG_LOC_2_7       32
4837b74a387bb3993387029859c2d9d051c41c724eStephen Hines
49551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define TYPE_BLOCK_ID_OLD_3_0         10
50551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define TYPE_SYMTAB_BLOCK_ID_OLD_3_0  13
51551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines#define TYPE_CODE_STRUCT_OLD_3_0      10
5237b74a387bb3993387029859c2d9d051c41c724eStephen Hines
53551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hinesnamespace {
54551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
55551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void StripDebugInfoOfFunction(Module* M, const char* name) {
56551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    if (Function* FuncStart = M->getFunction(name)) {
5737b74a387bb3993387029859c2d9d051c41c724eStephen Hines      while (!FuncStart->use_empty()) {
5837b74a387bb3993387029859c2d9d051c41c724eStephen Hines        cast<CallInst>(*FuncStart->use_begin())->eraseFromParent();
59551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines      }
60551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines      FuncStart->eraseFromParent();
61551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    }
62551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  }
6337b74a387bb3993387029859c2d9d051c41c724eStephen Hines
6437b74a387bb3993387029859c2d9d051c41c724eStephen Hines  /// This function strips all debug info intrinsics, except for llvm.dbg.declare.
65551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// If an llvm.dbg.declare intrinsic is invalid, then this function simply
66551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// strips that use.
67551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void CheckDebugInfoIntrinsics(Module *M) {
68551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    StripDebugInfoOfFunction(M, "llvm.dbg.func.start");
6937b74a387bb3993387029859c2d9d051c41c724eStephen Hines    StripDebugInfoOfFunction(M, "llvm.dbg.stoppoint");
7037b74a387bb3993387029859c2d9d051c41c724eStephen Hines    StripDebugInfoOfFunction(M, "llvm.dbg.region.start");
71551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    StripDebugInfoOfFunction(M, "llvm.dbg.region.end");
72551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
73551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    if (Function *Declare = M->getFunction("llvm.dbg.declare")) {
7437b74a387bb3993387029859c2d9d051c41c724eStephen Hines      if (!Declare->use_empty()) {
75551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines        DbgDeclareInst *DDI = cast<DbgDeclareInst>(*Declare->use_begin());
76551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines        if (!isa<MDNode>(ValueAsMetadata::get(DDI->getArgOperand(0))) ||
77551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines            !isa<MDNode>(ValueAsMetadata::get(DDI->getArgOperand(1)))) {
78551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines          while (!Declare->use_empty()) {
79551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines            CallInst *CI = cast<CallInst>(*Declare->use_begin());
8037b74a387bb3993387029859c2d9d051c41c724eStephen Hines            CI->eraseFromParent();
81551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines          }
82551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines          Declare->eraseFromParent();
83551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines        }
8437b74a387bb3993387029859c2d9d051c41c724eStephen Hines      }
8537b74a387bb3993387029859c2d9d051c41c724eStephen Hines    }
8637b74a387bb3993387029859c2d9d051c41c724eStephen Hines  }
87551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
8837b74a387bb3993387029859c2d9d051c41c724eStephen Hines//===----------------------------------------------------------------------===//
89551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//                          BitcodeReaderValueList Class
90551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//===----------------------------------------------------------------------===//
91551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
9237b74a387bb3993387029859c2d9d051c41c724eStephen Hinesclass BitcodeReaderValueList {
9337b74a387bb3993387029859c2d9d051c41c724eStephen Hines  std::vector<WeakVH> ValuePtrs;
94551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
95551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// ResolveConstants - As we resolve forward-referenced constants, we add
96551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// information about them to this vector.  This allows us to resolve them in
9737b74a387bb3993387029859c2d9d051c41c724eStephen Hines  /// bulk instead of resolving each reference at a time.  See the code in
98551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// ResolveConstantForwardRefs for more information about this.
99551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  ///
100551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// The key of this vector is the placeholder constant, the value is the slot
101551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// number that holds the resolved value.
102551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
10337b74a387bb3993387029859c2d9d051c41c724eStephen Hines  ResolveConstantsTy ResolveConstants;
104551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  LLVMContext &Context;
105551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hinespublic:
106551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
107551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  ~BitcodeReaderValueList() {
108551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    assert(ResolveConstants.empty() && "Constants not resolved?");
109551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  }
110a6c24dff8b7fa2551a3a885e77a2e814f5b764a2Stephen Hines
111551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  // vector compatibility methods
112551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  unsigned size() const { return ValuePtrs.size(); }
113551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void resize(unsigned N) { ValuePtrs.resize(N); }
114551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void push_back(Value *V) {
115551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    ValuePtrs.push_back(V);
116551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  }
11737b74a387bb3993387029859c2d9d051c41c724eStephen Hines
11837b74a387bb3993387029859c2d9d051c41c724eStephen Hines  void clear() {
11937b74a387bb3993387029859c2d9d051c41c724eStephen Hines    assert(ResolveConstants.empty() && "Constants not resolved?");
12037b74a387bb3993387029859c2d9d051c41c724eStephen Hines    ValuePtrs.clear();
12137b74a387bb3993387029859c2d9d051c41c724eStephen Hines  }
122551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
123551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  Value *operator[](unsigned i) const {
124551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    assert(i < ValuePtrs.size());
125551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    return ValuePtrs[i];
126a6c24dff8b7fa2551a3a885e77a2e814f5b764a2Stephen Hines  }
127551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
128551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  Value *back() const { return ValuePtrs.back(); }
129551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    void pop_back() { ValuePtrs.pop_back(); }
130551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  bool empty() const { return ValuePtrs.empty(); }
131551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void shrinkTo(unsigned N) {
132551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    assert(N <= size() && "Invalid shrinkTo request!");
133551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    ValuePtrs.resize(N);
134551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  }
135551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
13637b74a387bb3993387029859c2d9d051c41c724eStephen Hines  Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
13737b74a387bb3993387029859c2d9d051c41c724eStephen Hines  Value *getValueFwdRef(unsigned Idx, Type *Ty);
138551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
13937b74a387bb3993387029859c2d9d051c41c724eStephen Hines  void AssignValue(Value *V, unsigned Idx);
140551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
141551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
142551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  /// resolves any forward references.
143551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void ResolveConstantForwardRefs();
144551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines};
14537b74a387bb3993387029859c2d9d051c41c724eStephen Hines
14637b74a387bb3993387029859c2d9d051c41c724eStephen Hines
14737b74a387bb3993387029859c2d9d051c41c724eStephen Hines//===----------------------------------------------------------------------===//
148551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines//                          BitcodeReaderMDValueList Class
14937b74a387bb3993387029859c2d9d051c41c724eStephen Hines//===----------------------------------------------------------------------===//
150551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
151551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hinesclass BitcodeReaderMDValueList {
152551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  unsigned NumFwdRefs;
15337b74a387bb3993387029859c2d9d051c41c724eStephen Hines  bool AnyFwdRefs;
154551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  std::vector<TrackingMDRef> MDValuePtrs;
155551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
156551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  LLVMContext &Context;
15737b74a387bb3993387029859c2d9d051c41c724eStephen Hinespublic:
15837b74a387bb3993387029859c2d9d051c41c724eStephen Hines  BitcodeReaderMDValueList(LLVMContext &C)
15937b74a387bb3993387029859c2d9d051c41c724eStephen Hines      : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
160551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
161551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  // vector compatibility methods
162551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  unsigned size() const       { return MDValuePtrs.size(); }
16337b74a387bb3993387029859c2d9d051c41c724eStephen Hines  void resize(unsigned N)     { MDValuePtrs.resize(N); }
164551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
165551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void clear()                { MDValuePtrs.clear();  }
166551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  Metadata *back() const      { return MDValuePtrs.back(); }
167551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void pop_back()             { MDValuePtrs.pop_back(); }
168551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  bool empty() const          { return MDValuePtrs.empty(); }
169551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
170551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  Metadata *operator[](unsigned i) const {
171551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines    assert(i < MDValuePtrs.size());
17237b74a387bb3993387029859c2d9d051c41c724eStephen Hines    return MDValuePtrs[i];
173551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  }
174551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
175551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  void shrinkTo(unsigned N) {
17637b74a387bb3993387029859c2d9d051c41c724eStephen Hines    assert(N <= size() && "Invalid shrinkTo request!");
177a6c24dff8b7fa2551a3a885e77a2e814f5b764a2Stephen Hines    MDValuePtrs.resize(N);
178551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  }
179551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
18037b74a387bb3993387029859c2d9d051c41c724eStephen Hines  Metadata *getValueFwdRef(unsigned Idx);
181a6c24dff8b7fa2551a3a885e77a2e814f5b764a2Stephen Hines  void AssignValue(Metadata *MD, unsigned Idx);
182a6c24dff8b7fa2551a3a885e77a2e814f5b764a2Stephen Hines  void tryToResolveCycles();
183551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines};
184551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines
185551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hinesclass BitcodeReader : public GVMaterializer {
186551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  LLVMContext &Context;
187551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  DiagnosticHandlerFunction DiagnosticHandler;
188551ae4ebd3e9d137ea668fb83ae4a55b8cfba451Stephen Hines  Module *TheModule;
18937b74a387bb3993387029859c2d9d051c41c724eStephen Hines  std::unique_ptr<MemoryBuffer> Buffer;
19037b74a387bb3993387029859c2d9d051c41c724eStephen Hines  std::unique_ptr<BitstreamReader> StreamFile;
19137b74a387bb3993387029859c2d9d051c41c724eStephen Hines  BitstreamCursor Stream;
192  DataStreamer *LazyStreamer;
193  uint64_t NextUnreadBit;
194  bool SeenValueSymbolTable;
195
196  std::vector<Type*> TypeList;
197  BitcodeReaderValueList ValueList;
198  BitcodeReaderMDValueList MDValueList;
199  SmallVector<Instruction *, 64> InstructionList;
200
201  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
202  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
203
204  /// MAttributes - The set of attributes by index.  Index zero in the
205  /// file is for null, and is thus not represented here.  As such all indices
206  /// are off by one.
207  std::vector<AttributeSet> MAttributes;
208
209  /// \brief The set of attribute groups.
210  std::map<unsigned, AttributeSet> MAttributeGroups;
211
212  /// FunctionBBs - While parsing a function body, this is a list of the basic
213  /// blocks for the function.
214  std::vector<BasicBlock*> FunctionBBs;
215
216  // When reading the module header, this list is populated with functions that
217  // have bodies later in the file.
218  std::vector<Function*> FunctionsWithBodies;
219
220  // When intrinsic functions are encountered which require upgrading they are
221  // stored here with their replacement function.
222  typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
223  UpgradedIntrinsicMap UpgradedIntrinsics;
224
225  // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
226  DenseMap<unsigned, unsigned> MDKindMap;
227
228  // Several operations happen after the module header has been read, but
229  // before function bodies are processed. This keeps track of whether
230  // we've done this yet.
231  bool SeenFirstFunctionBody;
232
233  /// DeferredFunctionInfo - When function bodies are initially scanned, this
234  /// map contains info about where to find deferred function body in the
235  /// stream.
236  DenseMap<Function*, uint64_t> DeferredFunctionInfo;
237
238  /// BlockAddrFwdRefs - These are blockaddr references to basic blocks.  These
239  /// are resolved lazily when functions are loaded.
240  typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
241  DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
242
243  /// LLVM2_7MetadataDetected - True if metadata produced by LLVM 2.7 or
244  /// earlier was detected, in which case we behave slightly differently,
245  /// for compatibility.
246  /// FIXME: Remove in LLVM 3.0.
247  bool LLVM2_7MetadataDetected;
248  static const std::error_category &BitcodeErrorCategory();
249
250public:
251  std::error_code Error(BitcodeError E, const Twine &Message);
252  std::error_code Error(BitcodeError E);
253  std::error_code Error(const Twine &Message);
254
255  explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
256                         DiagnosticHandlerFunction DiagnosticHandler);
257  ~BitcodeReader() { FreeState(); }
258
259  void FreeState();
260
261  void releaseBuffer();
262
263  bool isDematerializable(const GlobalValue *GV) const override;
264  std::error_code materialize(GlobalValue *GV) override;
265  std::error_code materializeModule(Module *M) override;
266  std::vector<StructType *> getIdentifiedStructTypes() const override;
267  void dematerialize(GlobalValue *GV) override;
268
269  /// @brief Main interface to parsing a bitcode buffer.
270  /// @returns true if an error occurred.
271  std::error_code ParseBitcodeInto(Module *M);
272
273  /// @brief Cheap mechanism to just extract module triple
274  /// @returns true if an error occurred.
275  llvm::ErrorOr<std::string> parseTriple();
276
277  static uint64_t decodeSignRotatedValue(uint64_t V);
278
279  /// Materialize any deferred Metadata block.
280  std::error_code materializeMetadata() override;
281
282  void setStripDebugInfo() override;
283
284private:
285  std::vector<StructType *> IdentifiedStructTypes;
286  StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
287  StructType *createIdentifiedStructType(LLVMContext &Context);
288
289  Type *getTypeByID(unsigned ID);
290  Type *getTypeByIDOrNull(unsigned ID);
291  Value *getFnValueByID(unsigned ID, Type *Ty) {
292    if (Ty && Ty->isMetadataTy())
293      return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
294    return ValueList.getValueFwdRef(ID, Ty);
295  }
296  Metadata *getFnMetadataByID(unsigned ID) {
297    return MDValueList.getValueFwdRef(ID);
298  }
299  BasicBlock *getBasicBlock(unsigned ID) const {
300    if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
301    return FunctionBBs[ID];
302  }
303  AttributeSet getAttributes(unsigned i) const {
304    if (i-1 < MAttributes.size())
305      return MAttributes[i-1];
306    return AttributeSet();
307  }
308
309  /// getValueTypePair - Read a value/type pair out of the specified record from
310  /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
311  /// Return true on failure.
312  bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313                        unsigned InstNum, Value *&ResVal) {
314    if (Slot == Record.size()) return true;
315    unsigned ValNo = (unsigned)Record[Slot++];
316    if (ValNo < InstNum) {
317      // If this is not a forward reference, just return the value we already
318      // have.
319      ResVal = getFnValueByID(ValNo, nullptr);
320      return ResVal == nullptr;
321    } else if (Slot == Record.size()) {
322      return true;
323    }
324
325    unsigned TypeNo = (unsigned)Record[Slot++];
326    ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
327    return ResVal == nullptr;
328  }
329  bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
330                Type *Ty, Value *&ResVal) {
331    if (Slot == Record.size()) return true;
332    unsigned ValNo = (unsigned)Record[Slot++];
333    ResVal = getFnValueByID(ValNo, Ty);
334    return ResVal == 0;
335  }
336
337
338  std::error_code ParseModule(bool Resume);
339  std::error_code ParseAttributeBlock();
340  std::error_code ParseTypeTable();
341  std::error_code ParseOldTypeTable();         // FIXME: Remove in LLVM 3.1
342  std::error_code ParseTypeTableBody();
343
344  std::error_code ParseOldTypeSymbolTable();   // FIXME: Remove in LLVM 3.1
345  std::error_code ParseValueSymbolTable();
346  std::error_code ParseConstants();
347  std::error_code RememberAndSkipFunctionBody();
348  std::error_code ParseFunctionBody(Function *F);
349  std::error_code GlobalCleanup();
350  std::error_code ResolveGlobalAndAliasInits();
351  std::error_code ParseMetadata();
352  std::error_code ParseMetadataAttachment();
353  llvm::ErrorOr<std::string> parseModuleTriple();
354  std::error_code InitStream();
355  std::error_code InitStreamFromBuffer();
356  std::error_code InitLazyStream();
357};
358} // end anonymous namespace
359
360static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
361                             std::error_code EC, const Twine &Message) {
362  BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
363  DiagnosticHandler(DI);
364  return EC;
365}
366
367static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
368                             std::error_code EC) {
369  return Error(DiagnosticHandler, EC, EC.message());
370}
371
372std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
373  return ::Error(DiagnosticHandler, make_error_code(E), Message);
374}
375
376std::error_code BitcodeReader::Error(const Twine &Message) {
377  return ::Error(DiagnosticHandler,
378                 make_error_code(BitcodeError::CorruptedBitcode), Message);
379}
380
381std::error_code BitcodeReader::Error(BitcodeError E) {
382  return ::Error(DiagnosticHandler, make_error_code(E));
383}
384
385static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
386                                                LLVMContext &C) {
387  if (F)
388    return F;
389  return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
390}
391
392BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
393                             DiagnosticHandlerFunction DiagnosticHandler)
394    : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
395      TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
396      NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
397      MDValueList(C), SeenFirstFunctionBody(false),
398      LLVM2_7MetadataDetected(false) {}
399
400
401void BitcodeReader::FreeState() {
402  Buffer = nullptr;
403  std::vector<Type*>().swap(TypeList);
404  ValueList.clear();
405  MDValueList.clear();
406
407  std::vector<AttributeSet>().swap(MAttributes);
408  std::vector<BasicBlock*>().swap(FunctionBBs);
409  std::vector<Function*>().swap(FunctionsWithBodies);
410  DeferredFunctionInfo.clear();
411  MDKindMap.clear();
412}
413
414//===----------------------------------------------------------------------===//
415//  Helper functions to implement forward reference resolution, etc.
416//===----------------------------------------------------------------------===//
417
418/// ConvertToString - Convert a string from a record into an std::string, return
419/// true on failure.
420template<typename StrTy>
421static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
422                            StrTy &Result) {
423  if (Idx > Record.size())
424    return true;
425
426  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
427    Result += (char)Record[i];
428  return false;
429}
430
431static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
432  switch (Val) {
433  default: // Map unknown/new linkages to external
434  case 0:
435    return GlobalValue::ExternalLinkage;
436  case 1:
437    return GlobalValue::WeakAnyLinkage;
438  case 2:
439    return GlobalValue::AppendingLinkage;
440  case 3:
441    return GlobalValue::InternalLinkage;
442  case 4:
443    return GlobalValue::LinkOnceAnyLinkage;
444  case 5:
445    return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
446  case 6:
447    return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
448  case 7:
449    return GlobalValue::ExternalWeakLinkage;
450  case 8:
451    return GlobalValue::CommonLinkage;
452  case 9:
453    return GlobalValue::PrivateLinkage;
454  case 10:
455    return GlobalValue::WeakODRLinkage;
456  case 11:
457    return GlobalValue::LinkOnceODRLinkage;
458  case 12:
459    return GlobalValue::AvailableExternallyLinkage;
460  case 13:
461    return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
462  case 14:
463    return GlobalValue::ExternalWeakLinkage; // Obsolete LinkerPrivateWeakLinkage
464  //ANDROID: convert LinkOnceODRAutoHideLinkage -> LinkOnceODRLinkage
465  case 15:
466    return GlobalValue::LinkOnceODRLinkage;
467  }
468}
469
470static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
471  switch (Val) {
472  default: // Map unknown visibilities to default.
473  case 0: return GlobalValue::DefaultVisibility;
474  case 1: return GlobalValue::HiddenVisibility;
475  case 2: return GlobalValue::ProtectedVisibility;
476  }
477}
478
479static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
480  switch (Val) {
481    case 0: return GlobalVariable::NotThreadLocal;
482    default: // Map unknown non-zero value to general dynamic.
483    case 1: return GlobalVariable::GeneralDynamicTLSModel;
484    case 2: return GlobalVariable::LocalDynamicTLSModel;
485    case 3: return GlobalVariable::InitialExecTLSModel;
486    case 4: return GlobalVariable::LocalExecTLSModel;
487  }
488}
489
490static int GetDecodedCastOpcode(unsigned Val) {
491  switch (Val) {
492  default: return -1;
493  case bitc::CAST_TRUNC   : return Instruction::Trunc;
494  case bitc::CAST_ZEXT    : return Instruction::ZExt;
495  case bitc::CAST_SEXT    : return Instruction::SExt;
496  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
497  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
498  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
499  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
500  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
501  case bitc::CAST_FPEXT   : return Instruction::FPExt;
502  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
503  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
504  case bitc::CAST_BITCAST : return Instruction::BitCast;
505  }
506}
507static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
508  switch (Val) {
509  default: return -1;
510  case bitc::BINOP_ADD:
511    return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
512  case bitc::BINOP_SUB:
513    return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
514  case bitc::BINOP_MUL:
515    return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
516  case bitc::BINOP_UDIV: return Instruction::UDiv;
517  case bitc::BINOP_SDIV:
518    return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
519  case bitc::BINOP_UREM: return Instruction::URem;
520  case bitc::BINOP_SREM:
521    return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
522  case bitc::BINOP_SHL:  return Instruction::Shl;
523  case bitc::BINOP_LSHR: return Instruction::LShr;
524  case bitc::BINOP_ASHR: return Instruction::AShr;
525  case bitc::BINOP_AND:  return Instruction::And;
526  case bitc::BINOP_OR:   return Instruction::Or;
527  case bitc::BINOP_XOR:  return Instruction::Xor;
528  }
529}
530
531namespace llvm {
532namespace {
533  /// @brief A class for maintaining the slot number definition
534  /// as a placeholder for the actual definition for forward constants defs.
535  class ConstantPlaceHolder : public ConstantExpr {
536    void operator=(const ConstantPlaceHolder &) = delete;
537  public:
538    // allocate space for exactly one operand
539    void *operator new(size_t s) {
540      return User::operator new(s, 1);
541    }
542    explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
543      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
544      Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
545    }
546
547    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
548    static bool classof(const Value *V) {
549      return isa<ConstantExpr>(V) &&
550             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
551    }
552
553
554    /// Provide fast operand accessors
555    DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
556  };
557}
558
559// FIXME: can we inherit this from ConstantExpr?
560template <>
561struct OperandTraits<ConstantPlaceHolder> :
562  public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
563};
564DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
565}
566
567
568void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
569  if (Idx == size()) {
570    push_back(V);
571    return;
572  }
573
574  if (Idx >= size())
575    resize(Idx+1);
576
577  WeakVH &OldV = ValuePtrs[Idx];
578  if (!OldV) {
579    OldV = V;
580    return;
581  }
582
583  // Handle constants and non-constants (e.g. instrs) differently for
584  // efficiency.
585  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
586    ResolveConstants.push_back(std::make_pair(PHC, Idx));
587    OldV = V;
588  } else {
589    // If there was a forward reference to this value, replace it.
590    Value *PrevVal = OldV;
591    OldV->replaceAllUsesWith(V);
592    delete PrevVal;
593  }
594}
595
596
597Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
598                                                    Type *Ty) {
599  if (Idx >= size())
600    resize(Idx + 1);
601
602  if (Value *V = ValuePtrs[Idx]) {
603    assert(Ty == V->getType() && "Type mismatch in constant table!");
604    return cast<Constant>(V);
605  }
606
607  // Create and return a placeholder, which will later be RAUW'd.
608  Constant *C = new ConstantPlaceHolder(Ty, Context);
609  ValuePtrs[Idx] = C;
610  return C;
611}
612
613Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
614  if (Idx >= size())
615    resize(Idx + 1);
616
617  if (Value *V = ValuePtrs[Idx]) {
618    assert((!Ty || Ty == V->getType()) && "Type mismatch in value table!");
619    return V;
620  }
621
622  // No type specified, must be invalid reference.
623  if (!Ty) return nullptr;
624
625  // Create and return a placeholder, which will later be RAUW'd.
626  Value *V = new Argument(Ty);
627  ValuePtrs[Idx] = V;
628  return V;
629}
630
631/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
632/// resolves any forward references.  The idea behind this is that we sometimes
633/// get constants (such as large arrays) which reference *many* forward ref
634/// constants.  Replacing each of these causes a lot of thrashing when
635/// building/reuniquing the constant.  Instead of doing this, we look at all the
636/// uses and rewrite all the place holders at once for any constant that uses
637/// a placeholder.
638void BitcodeReaderValueList::ResolveConstantForwardRefs() {
639  // Sort the values by-pointer so that they are efficient to look up with a
640  // binary search.
641  std::sort(ResolveConstants.begin(), ResolveConstants.end());
642
643  SmallVector<Constant*, 64> NewOps;
644
645  while (!ResolveConstants.empty()) {
646    Value *RealVal = operator[](ResolveConstants.back().second);
647    Constant *Placeholder = ResolveConstants.back().first;
648    ResolveConstants.pop_back();
649
650    // Loop over all users of the placeholder, updating them to reference the
651    // new value.  If they reference more than one placeholder, update them all
652    // at once.
653    while (!Placeholder->use_empty()) {
654      auto UI = Placeholder->user_begin();
655      User *U = *UI;
656
657      // If the using object isn't uniqued, just update the operands.  This
658      // handles instructions and initializers for global variables.
659      if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
660        UI.getUse().set(RealVal);
661        continue;
662      }
663
664      // Otherwise, we have a constant that uses the placeholder.  Replace that
665      // constant with a new constant that has *all* placeholder uses updated.
666      Constant *UserC = cast<Constant>(U);
667      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
668           I != E; ++I) {
669        Value *NewOp;
670        if (!isa<ConstantPlaceHolder>(*I)) {
671          // Not a placeholder reference.
672          NewOp = *I;
673        } else if (*I == Placeholder) {
674          // Common case is that it just references this one placeholder.
675          NewOp = RealVal;
676        } else {
677          // Otherwise, look up the placeholder in ResolveConstants.
678          ResolveConstantsTy::iterator It =
679            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
680                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
681                                                            0));
682          assert(It != ResolveConstants.end() && It->first == *I);
683          NewOp = operator[](It->second);
684        }
685
686        NewOps.push_back(cast<Constant>(NewOp));
687      }
688
689      // Make the new constant.
690      Constant *NewC;
691      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
692        NewC = ConstantArray::get(UserCA->getType(), NewOps);
693      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
694        NewC = ConstantStruct::get(UserCS->getType(), NewOps);
695      } else if (isa<ConstantVector>(UserC)) {
696        NewC = ConstantVector::get(NewOps);
697      } else {
698        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
699        NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
700      }
701
702      UserC->replaceAllUsesWith(NewC);
703      UserC->destroyConstant();
704      NewOps.clear();
705    }
706
707    // Update all ValueHandles, they should be the only users at this point.
708    Placeholder->replaceAllUsesWith(RealVal);
709    delete Placeholder;
710  }
711}
712
713void BitcodeReaderMDValueList::AssignValue(Metadata *MD, unsigned Idx) {
714  if (Idx == size()) {
715    push_back(MD);
716    return;
717  }
718
719  if (Idx >= size())
720    resize(Idx+1);
721
722  TrackingMDRef &OldMD = MDValuePtrs[Idx];
723  if (!OldMD) {
724    OldMD.reset(MD);
725    return;
726  }
727
728  // If there was a forward reference to this value, replace it.
729  TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
730  PrevMD->replaceAllUsesWith(MD);
731  --NumFwdRefs;
732}
733
734Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
735  if (Idx >= size())
736    resize(Idx + 1);
737
738  if (Metadata *MD = MDValuePtrs[Idx])
739    return MD;
740
741  // Create and return a placeholder, which will later be RAUW'd.
742  AnyFwdRefs = true;
743  ++NumFwdRefs;
744  Metadata *MD = MDNode::getTemporary(Context, None).release();
745  MDValuePtrs[Idx].reset(MD);
746  return MD;
747}
748
749void BitcodeReaderMDValueList::tryToResolveCycles() {
750  if (!AnyFwdRefs)
751    // Nothing to do.
752    return;
753
754  if (NumFwdRefs)
755    // Still forward references... can't resolve cycles.
756    return;
757
758  // Resolve any cycles.
759  for (auto &MD : MDValuePtrs) {
760    auto *N = dyn_cast_or_null<MDNode>(MD);
761    if (!N)
762      continue;
763
764    assert(!N->isTemporary() && "Unexpected forward reference");
765    N->resolveCycles();
766  }
767}
768
769Type *BitcodeReader::getTypeByID(unsigned ID) {
770  // The type table size is always specified correctly.
771  if (ID >= TypeList.size())
772    return nullptr;
773
774  if (Type *Ty = TypeList[ID])
775    return Ty;
776
777  // If we have a forward reference, the only possible case is when it is to a
778  // named struct.  Just create a placeholder for now.
779  return TypeList[ID] = createIdentifiedStructType(Context);
780}
781
782StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
783                                                      StringRef Name) {
784  auto *Ret = StructType::create(Context, Name);
785  IdentifiedStructTypes.push_back(Ret);
786  return Ret;
787}
788
789StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
790  auto *Ret = StructType::create(Context);
791  IdentifiedStructTypes.push_back(Ret);
792  return Ret;
793}
794
795
796/// FIXME: Remove in LLVM 3.1, only used by ParseOldTypeTable.
797Type *BitcodeReader::getTypeByIDOrNull(unsigned ID) {
798  if (ID >= TypeList.size())
799    TypeList.resize(ID+1);
800
801  return TypeList[ID];
802}
803
804//===----------------------------------------------------------------------===//
805//  Functions for parsing blocks from the bitcode file
806//===----------------------------------------------------------------------===//
807
808
809/// \brief This fills an AttrBuilder object with the LLVM attributes that have
810/// been decoded from the given integer. This function must stay in sync with
811/// 'encodeLLVMAttributesForBitcode'.
812static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
813                                           uint64_t EncodedAttrs) {
814  // FIXME: Remove in 4.0.
815
816  // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
817  // the bits above 31 down by 11 bits.
818  unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
819  assert((!Alignment || isPowerOf2_32(Alignment)) &&
820         "Alignment must be a power of two.");
821
822  if (Alignment)
823    B.addAlignmentAttr(Alignment);
824  B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
825                (EncodedAttrs & 0xffff));
826}
827
828std::error_code BitcodeReader::ParseAttributeBlock() {
829  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
830    return Error("Invalid record");
831
832  if (!MAttributes.empty())
833    return Error("Invalid multiple blocks");
834
835  SmallVector<uint64_t, 64> Record;
836
837  SmallVector<AttributeSet, 8> Attrs;
838
839  // Read all the records.
840  while (1) {
841    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
842
843    switch (Entry.Kind) {
844    case BitstreamEntry::SubBlock: // Handled for us already.
845    case BitstreamEntry::Error:
846      return Error("Malformed block");
847    case BitstreamEntry::EndBlock:
848      return std::error_code();
849    case BitstreamEntry::Record:
850      // The interesting case.
851      break;
852    }
853
854    // Read a record.
855    Record.clear();
856    switch (Stream.readRecord(Entry.ID, Record)) {
857    default:  // Default behavior: ignore.
858      break;
859    case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
860      if (Record.size() & 1)
861        return Error("Invalid record");
862
863      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
864        AttrBuilder B;
865        decodeLLVMAttributesForBitcode(B, Record[i+1]);
866        Attrs.push_back(AttributeSet::get(Context, Record[i], B));
867      }
868
869      MAttributes.push_back(AttributeSet::get(Context, Attrs));
870      Attrs.clear();
871      break;
872    }
873    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
874      for (unsigned i = 0, e = Record.size(); i != e; ++i)
875        Attrs.push_back(MAttributeGroups[Record[i]]);
876
877      MAttributes.push_back(AttributeSet::get(Context, Attrs));
878      Attrs.clear();
879      break;
880    }
881    }
882  }
883}
884
885
886std::error_code BitcodeReader::ParseTypeTable() {
887  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
888    return Error("Invalid record");
889
890  return ParseTypeTableBody();
891}
892
893std::error_code BitcodeReader::ParseTypeTableBody() {
894  if (!TypeList.empty())
895    return Error("Invalid multiple blocks");
896
897  SmallVector<uint64_t, 64> Record;
898  unsigned NumRecords = 0;
899
900  SmallString<64> TypeName;
901
902  // Read all the records for this type table.
903  while (1) {
904    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
905
906    switch (Entry.Kind) {
907    case BitstreamEntry::SubBlock: // Handled for us already.
908    case BitstreamEntry::Error:
909      return Error("Malformed block");
910    case BitstreamEntry::EndBlock:
911      if (NumRecords != TypeList.size())
912        return Error("Malformed block");
913      return std::error_code();
914    case BitstreamEntry::Record:
915      // The interesting case.
916      break;
917    }
918
919    // Read a record.
920    Record.clear();
921    Type *ResultTy = nullptr;
922    switch (Stream.readRecord(Entry.ID, Record)) {
923    default:
924      return Error("Invalid value");
925    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
926      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
927      // type list.  This allows us to reserve space.
928      if (Record.size() < 1)
929        return Error("Invalid record");
930      TypeList.resize(Record[0]);
931      continue;
932    case bitc::TYPE_CODE_VOID:      // VOID
933      ResultTy = Type::getVoidTy(Context);
934      break;
935    case bitc::TYPE_CODE_HALF:     // HALF
936      ResultTy = Type::getHalfTy(Context);
937      break;
938    case bitc::TYPE_CODE_FLOAT:     // FLOAT
939      ResultTy = Type::getFloatTy(Context);
940      break;
941    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
942      ResultTy = Type::getDoubleTy(Context);
943      break;
944    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
945      ResultTy = Type::getX86_FP80Ty(Context);
946      break;
947    case bitc::TYPE_CODE_FP128:     // FP128
948      ResultTy = Type::getFP128Ty(Context);
949      break;
950    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
951      ResultTy = Type::getPPC_FP128Ty(Context);
952      break;
953    case bitc::TYPE_CODE_LABEL:     // LABEL
954      ResultTy = Type::getLabelTy(Context);
955      break;
956    case bitc::TYPE_CODE_METADATA:  // METADATA
957      ResultTy = Type::getMetadataTy(Context);
958      break;
959    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
960      ResultTy = Type::getX86_MMXTy(Context);
961      break;
962    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
963      if (Record.size() < 1)
964        return Error("Invalid record");
965
966      ResultTy = IntegerType::get(Context, Record[0]);
967      break;
968    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
969                                    //          [pointee type, address space]
970      if (Record.size() < 1)
971        return Error("Invalid record");
972      unsigned AddressSpace = 0;
973      if (Record.size() == 2)
974        AddressSpace = Record[1];
975      ResultTy = getTypeByID(Record[0]);
976      if (!ResultTy)
977        return Error("Invalid type");
978      ResultTy = PointerType::get(ResultTy, AddressSpace);
979      break;
980    }
981    case bitc::TYPE_CODE_FUNCTION_OLD: {
982      // FIXME: attrid is dead, remove it in LLVM 4.0
983      // FUNCTION: [vararg, attrid, retty, paramty x N]
984      if (Record.size() < 3)
985        return Error("Invalid record");
986      SmallVector<Type*, 8> ArgTys;
987      for (unsigned i = 3, e = Record.size(); i != e; ++i) {
988        if (Type *T = getTypeByID(Record[i]))
989          ArgTys.push_back(T);
990        else
991          break;
992      }
993
994      ResultTy = getTypeByID(Record[2]);
995      if (!ResultTy || ArgTys.size() < Record.size()-3)
996        return Error("Invalid type");
997
998      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
999      break;
1000    }
1001    case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
1002      if (Record.size() < 1)
1003        return Error("Invalid record");
1004      SmallVector<Type*, 8> EltTys;
1005      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1006        if (Type *T = getTypeByID(Record[i]))
1007          EltTys.push_back(T);
1008        else
1009          break;
1010      }
1011      if (EltTys.size() != Record.size()-1)
1012        return Error("Invalid type");
1013      ResultTy = StructType::get(Context, EltTys, Record[0]);
1014      break;
1015    }
1016    case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
1017      if (ConvertToString(Record, 0, TypeName))
1018        return Error("Invalid record");
1019      continue;
1020
1021    case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1022      if (Record.size() < 1)
1023        return Error("Invalid record");
1024
1025      if (NumRecords >= TypeList.size())
1026        return Error("Invalid TYPE table");
1027
1028      // Check to see if this was forward referenced, if so fill in the temp.
1029      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1030      if (Res) {
1031        Res->setName(TypeName);
1032        TypeList[NumRecords] = nullptr;
1033      } else  // Otherwise, create a new struct.
1034        Res = createIdentifiedStructType(Context, TypeName);
1035      TypeName.clear();
1036
1037      SmallVector<Type*, 8> EltTys;
1038      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1039        if (Type *T = getTypeByID(Record[i]))
1040          EltTys.push_back(T);
1041        else
1042          break;
1043      }
1044      if (EltTys.size() != Record.size()-1)
1045        return Error("Invalid record");
1046      Res->setBody(EltTys, Record[0]);
1047      ResultTy = Res;
1048      break;
1049    }
1050    case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
1051      if (Record.size() != 1)
1052        return Error("Invalid record");
1053
1054      if (NumRecords >= TypeList.size())
1055        return Error("Invalid TYPE table");
1056
1057      // Check to see if this was forward referenced, if so fill in the temp.
1058      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1059      if (Res) {
1060        Res->setName(TypeName);
1061        TypeList[NumRecords] = nullptr;
1062      } else  // Otherwise, create a new struct with no body.
1063        Res = createIdentifiedStructType(Context, TypeName);
1064      TypeName.clear();
1065      ResultTy = Res;
1066      break;
1067    }
1068    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1069      if (Record.size() < 2)
1070        return Error("Invalid record");
1071      if ((ResultTy = getTypeByID(Record[1])))
1072        ResultTy = ArrayType::get(ResultTy, Record[0]);
1073      else
1074        return Error("Invalid type");
1075      break;
1076    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1077      if (Record.size() < 2)
1078        return Error("Invalid record");
1079      if ((ResultTy = getTypeByID(Record[1])))
1080        ResultTy = VectorType::get(ResultTy, Record[0]);
1081      else
1082        return Error("Invalid type");
1083      break;
1084    }
1085
1086    if (NumRecords >= TypeList.size())
1087      return Error("Invalid TYPE table");
1088    assert(ResultTy && "Didn't read a type?");
1089    assert(!TypeList[NumRecords] && "Already read type?");
1090    TypeList[NumRecords++] = ResultTy;
1091  }
1092}
1093
1094// FIXME: Remove in LLVM 3.1
1095std::error_code BitcodeReader::ParseOldTypeTable() {
1096  if (Stream.EnterSubBlock(TYPE_BLOCK_ID_OLD_3_0))
1097    return Error("Malformed block");
1098
1099  if (!TypeList.empty())
1100    return Error("Invalid TYPE table");
1101
1102
1103  // While horrible, we have no good ordering of types in the bc file.  Just
1104  // iteratively parse types out of the bc file in multiple passes until we get
1105  // them all.  Do this by saving a cursor for the start of the type block.
1106  BitstreamCursor StartOfTypeBlockCursor(Stream);
1107
1108  unsigned NumTypesRead = 0;
1109
1110  SmallVector<uint64_t, 64> Record;
1111RestartScan:
1112  unsigned NextTypeID = 0;
1113  bool ReadAnyTypes = false;
1114
1115  // Read all the records for this type table.
1116  while (1) {
1117    unsigned Code = Stream.ReadCode();
1118    if (Code == bitc::END_BLOCK) {
1119      if (NextTypeID != TypeList.size())
1120        return Error("Invalid TYPE table");
1121
1122      // If we haven't read all of the types yet, iterate again.
1123      if (NumTypesRead != TypeList.size()) {
1124        // If we didn't successfully read any types in this pass, then we must
1125        // have an unhandled forward reference.
1126        if (!ReadAnyTypes)
1127          return Error("Invalid TYPE table");
1128
1129        Stream = StartOfTypeBlockCursor;
1130        goto RestartScan;
1131      }
1132
1133      if (Stream.ReadBlockEnd())
1134        return Error("Invalid TYPE table");
1135      return std::error_code();
1136    }
1137
1138    if (Code == bitc::ENTER_SUBBLOCK) {
1139      // No known subblocks, always skip them.
1140      Stream.ReadSubBlockID();
1141      if (Stream.SkipBlock())
1142        return Error("Malformed block");
1143      continue;
1144    }
1145
1146    if (Code == bitc::DEFINE_ABBREV) {
1147      Stream.ReadAbbrevRecord();
1148      continue;
1149    }
1150
1151    // Read a record.
1152    Record.clear();
1153    Type *ResultTy = nullptr;
1154    switch (Stream.readRecord(Code, Record)) {
1155    default: return Error("Invalid TYPE table");
1156    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1157      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1158      // type list.  This allows us to reserve space.
1159      if (Record.size() < 1)
1160        return Error("Invalid TYPE table");
1161      TypeList.resize(Record[0]);
1162      continue;
1163    case bitc::TYPE_CODE_VOID:      // VOID
1164      ResultTy = Type::getVoidTy(Context);
1165      break;
1166    case bitc::TYPE_CODE_FLOAT:     // FLOAT
1167      ResultTy = Type::getFloatTy(Context);
1168      break;
1169    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
1170      ResultTy = Type::getDoubleTy(Context);
1171      break;
1172    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
1173      ResultTy = Type::getX86_FP80Ty(Context);
1174      break;
1175    case bitc::TYPE_CODE_FP128:     // FP128
1176      ResultTy = Type::getFP128Ty(Context);
1177      break;
1178    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
1179      ResultTy = Type::getPPC_FP128Ty(Context);
1180      break;
1181    case bitc::TYPE_CODE_LABEL:     // LABEL
1182      ResultTy = Type::getLabelTy(Context);
1183      break;
1184    case bitc::TYPE_CODE_METADATA:  // METADATA
1185      ResultTy = Type::getMetadataTy(Context);
1186      break;
1187    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
1188      ResultTy = Type::getX86_MMXTy(Context);
1189      break;
1190    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
1191      if (Record.size() < 1)
1192        return Error("Invalid TYPE table");
1193      ResultTy = IntegerType::get(Context, Record[0]);
1194      break;
1195    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
1196      if (NextTypeID < TypeList.size() && TypeList[NextTypeID] == 0)
1197        ResultTy = StructType::create(Context, "");
1198      break;
1199    case TYPE_CODE_STRUCT_OLD_3_0: {// STRUCT_OLD
1200      if (NextTypeID >= TypeList.size()) break;
1201      // If we already read it, don't reprocess.
1202      if (TypeList[NextTypeID] &&
1203          !cast<StructType>(TypeList[NextTypeID])->isOpaque())
1204        break;
1205
1206      // Set a type.
1207      if (TypeList[NextTypeID] == 0)
1208        TypeList[NextTypeID] = StructType::create(Context, "");
1209
1210      std::vector<Type*> EltTys;
1211      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1212        if (Type *Elt = getTypeByIDOrNull(Record[i]))
1213          EltTys.push_back(Elt);
1214        else
1215          break;
1216      }
1217
1218      if (EltTys.size() != Record.size()-1)
1219        break;      // Not all elements are ready.
1220
1221      cast<StructType>(TypeList[NextTypeID])->setBody(EltTys, Record[0]);
1222      ResultTy = TypeList[NextTypeID];
1223      TypeList[NextTypeID] = 0;
1224      break;
1225    }
1226    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
1227      //          [pointee type, address space]
1228      if (Record.size() < 1)
1229        return Error("Invalid TYPE table");
1230      unsigned AddressSpace = 0;
1231      if (Record.size() == 2)
1232        AddressSpace = Record[1];
1233      if ((ResultTy = getTypeByIDOrNull(Record[0])))
1234        ResultTy = PointerType::get(ResultTy, AddressSpace);
1235      break;
1236    }
1237    case bitc::TYPE_CODE_FUNCTION_OLD: {
1238      // FIXME: attrid is dead, remove it in LLVM 3.0
1239      // FUNCTION: [vararg, attrid, retty, paramty x N]
1240      if (Record.size() < 3)
1241        return Error("Invalid TYPE table");
1242      std::vector<Type*> ArgTys;
1243      for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1244        if (Type *Elt = getTypeByIDOrNull(Record[i]))
1245          ArgTys.push_back(Elt);
1246        else
1247          break;
1248      }
1249      if (ArgTys.size()+3 != Record.size())
1250        break;  // Something was null.
1251      if ((ResultTy = getTypeByIDOrNull(Record[2])))
1252        ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1253      break;
1254    }
1255    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
1256      if (Record.size() < 2)
1257        return Error("Invalid TYPE table");
1258      if ((ResultTy = getTypeByIDOrNull(Record[1])))
1259        ResultTy = ArrayType::get(ResultTy, Record[0]);
1260      break;
1261    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
1262      if (Record.size() < 2)
1263        return Error("Invalid TYPE table");
1264      if ((ResultTy = getTypeByIDOrNull(Record[1])))
1265        ResultTy = VectorType::get(ResultTy, Record[0]);
1266      break;
1267    }
1268
1269    if (NextTypeID >= TypeList.size())
1270      return Error("Invalid TYPE table");
1271
1272    if (ResultTy && TypeList[NextTypeID] == 0) {
1273      ++NumTypesRead;
1274      ReadAnyTypes = true;
1275
1276      TypeList[NextTypeID] = ResultTy;
1277    }
1278
1279    ++NextTypeID;
1280  }
1281}
1282
1283
1284std::error_code BitcodeReader::ParseOldTypeSymbolTable() {
1285  if (Stream.EnterSubBlock(TYPE_SYMTAB_BLOCK_ID_OLD_3_0))
1286    return Error("Malformed block");
1287
1288  SmallVector<uint64_t, 64> Record;
1289
1290  // Read all the records for this type table.
1291  std::string TypeName;
1292  while (1) {
1293    unsigned Code = Stream.ReadCode();
1294    if (Code == bitc::END_BLOCK) {
1295      if (Stream.ReadBlockEnd())
1296        return Error("Malformed block");
1297      return std::error_code();
1298    }
1299
1300    if (Code == bitc::ENTER_SUBBLOCK) {
1301      // No known subblocks, always skip them.
1302      Stream.ReadSubBlockID();
1303      if (Stream.SkipBlock())
1304        return Error("Malformed block");
1305      continue;
1306    }
1307
1308    if (Code == bitc::DEFINE_ABBREV) {
1309      Stream.ReadAbbrevRecord();
1310      continue;
1311    }
1312
1313    // Read a record.
1314    Record.clear();
1315    switch (Stream.readRecord(Code, Record)) {
1316    default:  // Default behavior: unknown type.
1317      break;
1318    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
1319      if (ConvertToString(Record, 1, TypeName))
1320        return Error("Invalid record");
1321      unsigned TypeID = Record[0];
1322      if (TypeID >= TypeList.size())
1323        return Error("Invalid record");
1324
1325      // Only apply the type name to a struct type with no name.
1326      if (StructType *STy = dyn_cast<StructType>(TypeList[TypeID]))
1327        if (!STy->isLiteral() && !STy->hasName())
1328          STy->setName(TypeName);
1329      TypeName.clear();
1330      break;
1331    }
1332  }
1333}
1334
1335std::error_code BitcodeReader::ParseValueSymbolTable() {
1336  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1337    return Error("Invalid record");
1338
1339  SmallVector<uint64_t, 64> Record;
1340
1341  // Read all the records for this value table.
1342  SmallString<128> ValueName;
1343  while (1) {
1344    unsigned Code = Stream.ReadCode();
1345    if (Code == bitc::END_BLOCK) {
1346      if (Stream.ReadBlockEnd())
1347        return Error("Malformed block");
1348      return std::error_code();
1349    }
1350    if (Code == bitc::ENTER_SUBBLOCK) {
1351      // No known subblocks, always skip them.
1352      Stream.ReadSubBlockID();
1353      if (Stream.SkipBlock())
1354        return Error("Malformed block");
1355      continue;
1356    }
1357
1358    if (Code == bitc::DEFINE_ABBREV) {
1359      Stream.ReadAbbrevRecord();
1360      continue;
1361    }
1362
1363    // Read a record.
1364    Record.clear();
1365    switch (Stream.readRecord(Code, Record)) {
1366    default:  // Default behavior: unknown type.
1367      break;
1368    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
1369      if (ConvertToString(Record, 1, ValueName))
1370        return Error("Invalid record");
1371      unsigned ValueID = Record[0];
1372      if (ValueID >= ValueList.size())
1373        return Error("Invalid record");
1374      Value *V = ValueList[ValueID];
1375
1376      V->setName(StringRef(ValueName.data(), ValueName.size()));
1377      ValueName.clear();
1378      break;
1379    }
1380    case bitc::VST_CODE_BBENTRY: {
1381      if (ConvertToString(Record, 1, ValueName))
1382        return Error("Invalid record");
1383      BasicBlock *BB = getBasicBlock(Record[0]);
1384      if (!BB)
1385        return Error("Invalid record");
1386
1387      BB->setName(StringRef(ValueName.data(), ValueName.size()));
1388      ValueName.clear();
1389      break;
1390    }
1391    }
1392  }
1393}
1394
1395std::error_code BitcodeReader::ParseMetadata() {
1396  unsigned NextMDValueNo = MDValueList.size();
1397
1398  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1399    return Error("Invalid record");
1400
1401  SmallVector<uint64_t, 64> Record;
1402
1403  // Read all the records.
1404  while (1) {
1405    unsigned Code = Stream.ReadCode();
1406    if (Code == bitc::END_BLOCK) {
1407      if (Stream.ReadBlockEnd())
1408        return Error("Malformed block");
1409      return std::error_code();
1410    }
1411
1412    if (Code == bitc::ENTER_SUBBLOCK) {
1413      // No known subblocks, always skip them.
1414      Stream.ReadSubBlockID();
1415      if (Stream.SkipBlock())
1416        return Error("Malformed block");
1417      continue;
1418    }
1419
1420    if (Code == bitc::DEFINE_ABBREV) {
1421      Stream.ReadAbbrevRecord();
1422      continue;
1423    }
1424
1425    bool IsFunctionLocal = false;
1426    // Read a record.
1427    Record.clear();
1428    Code = Stream.readRecord(Code, Record);
1429    switch (Code) {
1430    default:  // Default behavior: ignore.
1431      break;
1432    case bitc::METADATA_NAME: {
1433      // Read named of the named metadata.
1434      unsigned NameLength = Record.size();
1435      SmallString<8> Name;
1436      Name.resize(NameLength);
1437      for (unsigned i = 0; i != NameLength; ++i)
1438        Name[i] = Record[i];
1439      Record.clear();
1440      Code = Stream.ReadCode();
1441
1442      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1443      unsigned NextBitCode = Stream.readRecord(Code, Record);
1444      if (NextBitCode == METADATA_NAMED_NODE_2_7) {
1445        LLVM2_7MetadataDetected = true;
1446      } else if (NextBitCode != bitc::METADATA_NAMED_NODE) {
1447        assert(!"Invalid Named Metadata record.");  (void)NextBitCode;
1448      }
1449
1450      // Read named metadata elements.
1451      unsigned Size = Record.size();
1452      NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1453      for (unsigned i = 0; i != Size; ++i) {
1454        MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1455        if (!MD)
1456          return Error("Invalid record");
1457        NMD->addOperand(MD);
1458      }
1459
1460      if (LLVM2_7MetadataDetected) {
1461        MDValueList.AssignValue(0, NextMDValueNo++);
1462      }
1463      break;
1464    }
1465    case METADATA_FN_NODE_2_7:
1466    case bitc::METADATA_OLD_FN_NODE:
1467      IsFunctionLocal = true;
1468      // fall-through
1469    case METADATA_NODE_2_7:
1470    case bitc::METADATA_OLD_NODE: {
1471      if (Code == METADATA_FN_NODE_2_7 ||
1472          Code == METADATA_NODE_2_7) {
1473        LLVM2_7MetadataDetected = true;
1474      }
1475
1476      if (Record.size() % 2 == 1)
1477        return Error("Invalid record");
1478
1479      unsigned Size = Record.size();
1480      SmallVector<Metadata *, 8> Elts;
1481      for (unsigned i = 0; i != Size; i += 2) {
1482        Type *Ty = getTypeByID(Record[i]);
1483        if (!Ty)
1484          return Error("Invalid record");
1485        if (Ty->isMetadataTy())
1486          Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1487        else if (!Ty->isVoidTy()) {
1488          auto *MD =
1489              ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1490          assert(isa<ConstantAsMetadata>(MD) &&
1491                 "Expected non-function-local metadata");
1492          Elts.push_back(MD);
1493        } else
1494          Elts.push_back(nullptr);
1495      }
1496      MDValueList.AssignValue(MDNode::get(Context, Elts), NextMDValueNo++);
1497      break;
1498    }
1499    case bitc::METADATA_STRING: {
1500      std::string String(Record.begin(), Record.end());
1501      llvm::UpgradeMDStringConstant(String);
1502      Metadata *MD = MDString::get(Context, String);
1503      MDValueList.AssignValue(MD, NextMDValueNo++);
1504      break;
1505    }
1506    case bitc::METADATA_KIND: {
1507      if (Record.size() < 2)
1508        return Error("Invalid record");
1509
1510      unsigned Kind = Record[0];
1511      SmallString<8> Name(Record.begin()+1, Record.end());
1512
1513      unsigned NewKind = TheModule->getMDKindID(Name.str());
1514      if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1515        return Error("Conflicting METADATA_KIND records");
1516      break;
1517    }
1518    }
1519  }
1520}
1521
1522/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1523/// the LSB for dense VBR encoding.
1524uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1525  if ((V & 1) == 0)
1526    return V >> 1;
1527  if (V != 1)
1528    return -(V >> 1);
1529  // There is no such thing as -0 with integers.  "-0" really means MININT.
1530  return 1ULL << 63;
1531}
1532
1533// FIXME: Delete this in LLVM 4.0 and just assert that the aliasee is a
1534// GlobalObject.
1535static GlobalObject &
1536getGlobalObjectInExpr(const DenseMap<GlobalAlias *, Constant *> &Map,
1537                      Constant &C) {
1538  auto *GO = dyn_cast<GlobalObject>(&C);
1539  if (GO)
1540    return *GO;
1541
1542  auto *GA = dyn_cast<GlobalAlias>(&C);
1543  if (GA)
1544    return getGlobalObjectInExpr(Map, *Map.find(GA)->second);
1545
1546  auto &CE = cast<ConstantExpr>(C);
1547  assert(CE.getOpcode() == Instruction::BitCast ||
1548         CE.getOpcode() == Instruction::GetElementPtr ||
1549         CE.getOpcode() == Instruction::AddrSpaceCast);
1550  if (CE.getOpcode() == Instruction::GetElementPtr)
1551    assert(cast<GEPOperator>(CE).hasAllZeroIndices());
1552  return getGlobalObjectInExpr(Map, *CE.getOperand(0));
1553}
1554
1555/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1556/// values and aliases that we can.
1557std::error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1558  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1559  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1560
1561  GlobalInitWorklist.swap(GlobalInits);
1562  AliasInitWorklist.swap(AliasInits);
1563
1564  while (!GlobalInitWorklist.empty()) {
1565    unsigned ValID = GlobalInitWorklist.back().second;
1566    if (ValID >= ValueList.size()) {
1567      // Not ready to resolve this yet, it requires something later in the file.
1568      GlobalInits.push_back(GlobalInitWorklist.back());
1569    } else {
1570      if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1571        GlobalInitWorklist.back().first->setInitializer(C);
1572      else
1573        return Error("Expected a constant");
1574    }
1575    GlobalInitWorklist.pop_back();
1576  }
1577
1578  // FIXME: Delete this in LLVM 4.0
1579  // Older versions of llvm could write an alias pointing to another. We cannot
1580  // construct those aliases, so we first collect an alias to aliasee expression
1581  // and then compute the actual aliasee.
1582  DenseMap<GlobalAlias *, Constant *> AliasInit;
1583
1584  while (!AliasInitWorklist.empty()) {
1585    unsigned ValID = AliasInitWorklist.back().second;
1586    if (ValID >= ValueList.size()) {
1587      AliasInits.push_back(AliasInitWorklist.back());
1588    } else {
1589      if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
1590        AliasInit.insert(std::make_pair(AliasInitWorklist.back().first, C));
1591      else
1592        return Error("Expected a constant");
1593    }
1594    AliasInitWorklist.pop_back();
1595  }
1596
1597  for (auto &Pair : AliasInit) {
1598    auto &GO = getGlobalObjectInExpr(AliasInit, *Pair.second);
1599    Pair.first->setAliasee(&GO);
1600  }
1601
1602  return std::error_code();
1603}
1604
1605static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1606  SmallVector<uint64_t, 8> Words(Vals.size());
1607  std::transform(Vals.begin(), Vals.end(), Words.begin(),
1608                 BitcodeReader::decodeSignRotatedValue);
1609
1610  return APInt(TypeBits, Words);
1611}
1612
1613std::error_code BitcodeReader::ParseConstants() {
1614  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1615    return Error("Invalid record");
1616
1617  SmallVector<uint64_t, 64> Record;
1618
1619  // Read all the records for this value table.
1620  Type *CurTy = Type::getInt32Ty(Context);
1621  unsigned NextCstNo = ValueList.size();
1622  while (1) {
1623    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1624
1625    switch (Entry.Kind) {
1626    case BitstreamEntry::SubBlock: // Handled for us already.
1627    case BitstreamEntry::Error:
1628      return Error("Malformed block");
1629    case BitstreamEntry::EndBlock:
1630      if (NextCstNo != ValueList.size())
1631        return Error("Invalid constant reference");
1632
1633      // Once all the constants have been read, go through and resolve forward
1634      // references.
1635      ValueList.ResolveConstantForwardRefs();
1636      return std::error_code();
1637    case BitstreamEntry::Record:
1638      // The interesting case.
1639      break;
1640    }
1641
1642    // Read a record.
1643    Record.clear();
1644    Value *V = nullptr;
1645    unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1646    switch (BitCode) {
1647    default:  // Default behavior: unknown constant
1648    case bitc::CST_CODE_UNDEF:     // UNDEF
1649      V = UndefValue::get(CurTy);
1650      break;
1651    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1652      if (Record.empty())
1653        return Error("Invalid record");
1654      if (Record[0] >= TypeList.size())
1655        return Error("Invalid record");
1656      CurTy = TypeList[Record[0]];
1657      continue;  // Skip the ValueList manipulation.
1658    case bitc::CST_CODE_NULL:      // NULL
1659      V = Constant::getNullValue(CurTy);
1660      break;
1661    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1662      if (!CurTy->isIntegerTy() || Record.empty())
1663        return Error("Invalid record");
1664      V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1665      break;
1666    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1667      if (!CurTy->isIntegerTy() || Record.empty())
1668        return Error("Invalid record");
1669
1670      APInt VInt = ReadWideAPInt(Record,
1671                                 cast<IntegerType>(CurTy)->getBitWidth());
1672      V = ConstantInt::get(Context, VInt);
1673
1674      break;
1675    }
1676    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1677      if (Record.empty())
1678        return Error("Invalid record");
1679      if (CurTy->isHalfTy())
1680        V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1681                                             APInt(16, (uint16_t)Record[0])));
1682      else if (CurTy->isFloatTy())
1683        V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1684                                             APInt(32, (uint32_t)Record[0])));
1685      else if (CurTy->isDoubleTy())
1686        V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1687                                             APInt(64, Record[0])));
1688      else if (CurTy->isX86_FP80Ty()) {
1689        // Bits are not stored the same way as a normal i80 APInt, compensate.
1690        uint64_t Rearrange[2];
1691        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1692        Rearrange[1] = Record[0] >> 48;
1693        V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1694                                             APInt(80, Rearrange)));
1695      } else if (CurTy->isFP128Ty())
1696        V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1697                                             APInt(128, Record)));
1698      else if (CurTy->isPPC_FP128Ty())
1699        V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1700                                             APInt(128, Record)));
1701      else
1702        V = UndefValue::get(CurTy);
1703      break;
1704    }
1705
1706    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1707      if (Record.empty())
1708        return Error("Invalid record");
1709
1710      unsigned Size = Record.size();
1711      SmallVector<Constant*, 16> Elts;
1712
1713      if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1714        for (unsigned i = 0; i != Size; ++i)
1715          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1716                                                     STy->getElementType(i)));
1717        V = ConstantStruct::get(STy, Elts);
1718      } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1719        Type *EltTy = ATy->getElementType();
1720        for (unsigned i = 0; i != Size; ++i)
1721          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1722        V = ConstantArray::get(ATy, Elts);
1723      } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1724        Type *EltTy = VTy->getElementType();
1725        for (unsigned i = 0; i != Size; ++i)
1726          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1727        V = ConstantVector::get(Elts);
1728      } else {
1729        V = UndefValue::get(CurTy);
1730      }
1731      break;
1732    }
1733    case bitc::CST_CODE_STRING: { // STRING: [values]
1734      if (Record.empty())
1735        return Error("Invalid record");
1736
1737      ArrayType *ATy = cast<ArrayType>(CurTy);
1738      Type *EltTy = ATy->getElementType();
1739
1740      unsigned Size = Record.size();
1741      std::vector<Constant*> Elts;
1742      for (unsigned i = 0; i != Size; ++i)
1743        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1744      V = ConstantArray::get(ATy, Elts);
1745      break;
1746    }
1747    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1748      if (Record.empty())
1749        return Error("Invalid record");
1750
1751      ArrayType *ATy = cast<ArrayType>(CurTy);
1752      Type *EltTy = ATy->getElementType();
1753
1754      unsigned Size = Record.size();
1755      std::vector<Constant*> Elts;
1756      for (unsigned i = 0; i != Size; ++i)
1757        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1758      Elts.push_back(Constant::getNullValue(EltTy));
1759      V = ConstantArray::get(ATy, Elts);
1760      break;
1761    }
1762    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1763      if (Record.size() < 3)
1764        return Error("Invalid record");
1765      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1766      if (Opc < 0) {
1767        V = UndefValue::get(CurTy);  // Unknown binop.
1768      } else {
1769        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1770        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1771        unsigned Flags = 0;
1772        if (Record.size() >= 4) {
1773          if (Opc == Instruction::Add ||
1774              Opc == Instruction::Sub ||
1775              Opc == Instruction::Mul ||
1776              Opc == Instruction::Shl) {
1777            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1778              Flags |= OverflowingBinaryOperator::NoSignedWrap;
1779            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1780              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1781          } else if (Opc == Instruction::SDiv ||
1782                     Opc == Instruction::UDiv ||
1783                     Opc == Instruction::LShr ||
1784                     Opc == Instruction::AShr) {
1785            if (Record[3] & (1 << bitc::PEO_EXACT))
1786              Flags |= SDivOperator::IsExact;
1787          }
1788        }
1789        V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1790      }
1791      break;
1792    }
1793    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1794      if (Record.size() < 3)
1795        return Error("Invalid record");
1796      int Opc = GetDecodedCastOpcode(Record[0]);
1797      if (Opc < 0) {
1798        V = UndefValue::get(CurTy);  // Unknown cast.
1799      } else {
1800        Type *OpTy = getTypeByID(Record[1]);
1801        if (!OpTy)
1802          return Error("Invalid record");
1803        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1804        V = ConstantExpr::getCast(Opc, Op, CurTy);
1805      }
1806      break;
1807    }
1808    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1809    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1810      Type *PointeeType = nullptr;
1811      if (Record.size() & 1)
1812        return Error("Invalid record");
1813      SmallVector<Constant*, 16> Elts;
1814      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1815        Type *ElTy = getTypeByID(Record[i]);
1816        if (!ElTy)
1817          return Error("Invalid record");
1818        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1819      }
1820      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1821      V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
1822                                         BitCode ==
1823                                           bitc::CST_CODE_CE_INBOUNDS_GEP);
1824      break;
1825    }
1826    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1827      if (Record.size() < 3)
1828        return Error("Invalid record");
1829      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1830                                                              Type::getInt1Ty(Context)),
1831                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1832                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1833      break;
1834    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1835      if (Record.size() < 3)
1836        return Error("Invalid record");
1837      VectorType *OpTy =
1838        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1839      if (!OpTy)
1840        return Error("Invalid record");
1841      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1842      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1843      V = ConstantExpr::getExtractElement(Op0, Op1);
1844      break;
1845    }
1846    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1847      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1848      if (Record.size() < 3 || !OpTy)
1849        return Error("Invalid record");
1850      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1851      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1852                                                  OpTy->getElementType());
1853      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1854      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1855      break;
1856    }
1857    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1858      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1859      if (Record.size() < 3 || !OpTy)
1860        return Error("Invalid record");
1861      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1862      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1863      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1864                                                 OpTy->getNumElements());
1865      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1866      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1867      break;
1868    }
1869    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1870      VectorType *RTy = dyn_cast<VectorType>(CurTy);
1871      VectorType *OpTy =
1872        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1873      if (Record.size() < 4 || !RTy || !OpTy)
1874        return Error("Invalid record");
1875      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1876      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1877      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1878                                                 RTy->getNumElements());
1879      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1880      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1881      break;
1882    }
1883    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1884      if (Record.size() < 4)
1885        return Error("Invalid record");
1886      Type *OpTy = getTypeByID(Record[0]);
1887      if (!OpTy)
1888        return Error("Invalid record");
1889      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1890      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1891
1892      if (OpTy->isFPOrFPVectorTy())
1893        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1894      else
1895        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1896      break;
1897    }
1898    case bitc::CST_CODE_INLINEASM:
1899    case bitc::CST_CODE_INLINEASM_OLD: {
1900      if (Record.size() < 2)
1901        return Error("Invalid record");
1902      std::string AsmStr, ConstrStr;
1903      bool HasSideEffects = Record[0] & 1;
1904      bool IsAlignStack = Record[0] >> 1;
1905      unsigned AsmStrSize = Record[1];
1906      if (2+AsmStrSize >= Record.size())
1907        return Error("Invalid record");
1908      unsigned ConstStrSize = Record[2+AsmStrSize];
1909      if (3+AsmStrSize+ConstStrSize > Record.size())
1910        return Error("Invalid record");
1911
1912      for (unsigned i = 0; i != AsmStrSize; ++i)
1913        AsmStr += (char)Record[2+i];
1914      for (unsigned i = 0; i != ConstStrSize; ++i)
1915        ConstrStr += (char)Record[3+AsmStrSize+i];
1916      PointerType *PTy = cast<PointerType>(CurTy);
1917      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1918                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1919      break;
1920    }
1921    case bitc::CST_CODE_BLOCKADDRESS:{
1922      if (Record.size() < 3)
1923        return Error("Invalid record");
1924      Type *FnTy = getTypeByID(Record[0]);
1925      if (!FnTy)
1926        return Error("Invalid record");
1927      Function *Fn =
1928        dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1929      if (!Fn)
1930        return Error("Invalid record");
1931
1932      GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1933                                                  Type::getInt8Ty(Context),
1934                                            false, GlobalValue::InternalLinkage,
1935                                                  0, "");
1936      BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1937      V = FwdRef;
1938      break;
1939    }
1940    }
1941
1942    ValueList.AssignValue(V, NextCstNo);
1943    ++NextCstNo;
1944  }
1945
1946  if (NextCstNo != ValueList.size())
1947    return Error("Invalid constant reference");
1948
1949  if (Stream.ReadBlockEnd())
1950    return Error("Expected a constant");
1951
1952  // Once all the constants have been read, go through and resolve forward
1953  // references.
1954  ValueList.ResolveConstantForwardRefs();
1955  return std::error_code();
1956}
1957
1958std::error_code BitcodeReader::materializeMetadata() {
1959  return std::error_code();
1960}
1961
1962void BitcodeReader::setStripDebugInfo() { }
1963
1964/// RememberAndSkipFunctionBody - When we see the block for a function body,
1965/// remember where it is and then skip it.  This lets us lazily deserialize the
1966/// functions.
1967std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
1968  // Get the function we are talking about.
1969  if (FunctionsWithBodies.empty())
1970    return Error("Insufficient function protos");
1971
1972  Function *Fn = FunctionsWithBodies.back();
1973  FunctionsWithBodies.pop_back();
1974
1975  // Save the current stream state.
1976  uint64_t CurBit = Stream.GetCurrentBitNo();
1977  DeferredFunctionInfo[Fn] = CurBit;
1978
1979  // Skip over the function block for now.
1980  if (Stream.SkipBlock())
1981    return Error("Invalid record");
1982  return std::error_code();
1983}
1984
1985std::error_code BitcodeReader::GlobalCleanup() {
1986  // Patch the initializers for globals and aliases up.
1987  ResolveGlobalAndAliasInits();
1988  if (!GlobalInits.empty() || !AliasInits.empty())
1989    return Error("Malformed global initializer set");
1990
1991  // Look for intrinsic functions which need to be upgraded at some point
1992  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1993       FI != FE; ++FI) {
1994    Function *NewFn;
1995    if (UpgradeIntrinsicFunction(FI, NewFn))
1996      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1997  }
1998
1999  // Look for global variables which need to be renamed.
2000  for (Module::global_iterator
2001         GI = TheModule->global_begin(), GE = TheModule->global_end();
2002       GI != GE;) {
2003    GlobalVariable *GV = GI++;
2004    UpgradeGlobalVariable(GV);
2005  }
2006
2007  // Force deallocation of memory for these vectors to favor the client that
2008  // want lazy deserialization.
2009  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2010  std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2011  return std::error_code();
2012}
2013
2014std::error_code BitcodeReader::ParseModule(bool Resume) {
2015  if (Resume)
2016    Stream.JumpToBit(NextUnreadBit);
2017  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2018    return Error("Invalid record");
2019
2020  SmallVector<uint64_t, 64> Record;
2021  std::vector<std::string> SectionTable;
2022  std::vector<std::string> GCTable;
2023
2024  // Read all the records for this module.
2025  while (!Stream.AtEndOfStream()) {
2026    unsigned Code = Stream.ReadCode();
2027    if (Code == bitc::END_BLOCK) {
2028      if (Stream.ReadBlockEnd())
2029        return Error("Malformed block");
2030
2031      // Patch the initializers for globals and aliases up.
2032      ResolveGlobalAndAliasInits();
2033      if (!GlobalInits.empty() || !AliasInits.empty())
2034        return Error("Malformed global initializer set");
2035      if (!FunctionsWithBodies.empty())
2036        return Error("Insufficient function protos");
2037
2038      // Look for intrinsic functions which need to be upgraded at some point
2039      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
2040           FI != FE; ++FI) {
2041        Function* NewFn;
2042        if (UpgradeIntrinsicFunction(FI, NewFn))
2043          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
2044      }
2045
2046      // Look for global variables which need to be renamed.
2047      for (Module::global_iterator
2048             GI = TheModule->global_begin(), GE = TheModule->global_end();
2049           GI != GE; ++GI)
2050        UpgradeGlobalVariable(GI);
2051
2052      // Force deallocation of memory for these vectors to favor the client that
2053      // want lazy deserialization.
2054      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2055      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
2056      std::vector<Function*>().swap(FunctionsWithBodies);
2057      return std::error_code();
2058    }
2059
2060    if (Code == bitc::ENTER_SUBBLOCK) {
2061      switch (Stream.ReadSubBlockID()) {
2062      default:  // Skip unknown content.
2063        if (Stream.SkipBlock())
2064          return Error("Invalid record");
2065        break;
2066      case bitc::BLOCKINFO_BLOCK_ID:
2067        if (Stream.ReadBlockInfoBlock())
2068          return Error("Malformed block");
2069        break;
2070      case bitc::PARAMATTR_BLOCK_ID:
2071        if (std::error_code EC = ParseAttributeBlock())
2072          return EC;
2073        break;
2074      case bitc::TYPE_BLOCK_ID_NEW:
2075        if (std::error_code EC = ParseTypeTable())
2076          return EC;
2077        break;
2078      case TYPE_BLOCK_ID_OLD_3_0:
2079        if (std::error_code EC = ParseOldTypeTable())
2080          return EC;
2081        break;
2082      case TYPE_SYMTAB_BLOCK_ID_OLD_3_0:
2083        if (std::error_code EC = ParseOldTypeSymbolTable())
2084          return EC;
2085        break;
2086      case bitc::VALUE_SYMTAB_BLOCK_ID:
2087        if (std::error_code EC = ParseValueSymbolTable())
2088          return EC;
2089        SeenValueSymbolTable = true;
2090        break;
2091      case bitc::CONSTANTS_BLOCK_ID:
2092        if (std::error_code EC = ParseConstants())
2093          return EC;
2094        if (std::error_code EC = ResolveGlobalAndAliasInits())
2095          return EC;
2096        break;
2097      case bitc::METADATA_BLOCK_ID:
2098        if (std::error_code EC = ParseMetadata())
2099          return EC;
2100        break;
2101      case bitc::FUNCTION_BLOCK_ID:
2102        // If this is the first function body we've seen, reverse the
2103        // FunctionsWithBodies list.
2104        if (!SeenFirstFunctionBody) {
2105          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
2106          if (std::error_code EC = GlobalCleanup())
2107            return EC;
2108          SeenFirstFunctionBody = true;
2109        }
2110
2111        if (std::error_code EC = RememberAndSkipFunctionBody())
2112          return EC;
2113        // For streaming bitcode, suspend parsing when we reach the function
2114        // bodies. Subsequent materialization calls will resume it when
2115        // necessary. For streaming, the function bodies must be at the end of
2116        // the bitcode. If the bitcode file is old, the symbol table will be
2117        // at the end instead and will not have been seen yet. In this case,
2118        // just finish the parse now.
2119        if (LazyStreamer && SeenValueSymbolTable) {
2120          NextUnreadBit = Stream.GetCurrentBitNo();
2121          return std::error_code();
2122        }
2123        break;
2124        break;
2125      }
2126      continue;
2127    }
2128
2129    if (Code == bitc::DEFINE_ABBREV) {
2130      Stream.ReadAbbrevRecord();
2131      continue;
2132    }
2133
2134    // Read a record.
2135    switch (Stream.readRecord(Code, Record)) {
2136    default: break;  // Default behavior, ignore unknown content.
2137    case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
2138      if (Record.size() < 1)
2139        return Error("Invalid record");
2140      // Only version #0 is supported so far.
2141      if (Record[0] != 0)
2142        return Error("Invalid value");
2143      break;
2144    }
2145    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2146      std::string S;
2147      if (ConvertToString(Record, 0, S))
2148        return Error("Invalid record");
2149      TheModule->setTargetTriple(S);
2150      break;
2151    }
2152    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
2153      std::string S;
2154      if (ConvertToString(Record, 0, S))
2155        return Error("Invalid record");
2156      TheModule->setDataLayout(S);
2157      break;
2158    }
2159    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
2160      std::string S;
2161      if (ConvertToString(Record, 0, S))
2162        return Error("Invalid record");
2163      TheModule->setModuleInlineAsm(S);
2164      break;
2165    }
2166    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
2167      std::string S;
2168      if (ConvertToString(Record, 0, S))
2169        return Error("Invalid record");
2170      // ANDROID: Ignore value, since we never used it anyways.
2171      // TheModule->addLibrary(S);
2172      break;
2173    }
2174    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
2175      std::string S;
2176      if (ConvertToString(Record, 0, S))
2177        return Error("Invalid record");
2178      SectionTable.push_back(S);
2179      break;
2180    }
2181    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
2182      std::string S;
2183      if (ConvertToString(Record, 0, S))
2184        return Error("Invalid record");
2185      GCTable.push_back(S);
2186      break;
2187    }
2188    // GLOBALVAR: [pointer type, isconst, initid,
2189    //             linkage, alignment, section, visibility, threadlocal,
2190    //             unnamed_addr]
2191    case bitc::MODULE_CODE_GLOBALVAR: {
2192      if (Record.size() < 6)
2193        return Error("Invalid record");
2194      Type *Ty = getTypeByID(Record[0]);
2195      if (!Ty)
2196        return Error("Invalid record");
2197      if (!Ty->isPointerTy())
2198        return Error("Invalid type for value");
2199      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
2200      Ty = cast<PointerType>(Ty)->getElementType();
2201
2202      bool isConstant = Record[1];
2203      uint64_t RawLinkage = Record[3];
2204      GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
2205      unsigned Alignment = (1 << Record[4]) >> 1;
2206      std::string Section;
2207      if (Record[5]) {
2208        if (Record[5]-1 >= SectionTable.size())
2209          return Error("Invalid ID");
2210        Section = SectionTable[Record[5]-1];
2211      }
2212      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
2213      if (Record.size() > 6)
2214        Visibility = GetDecodedVisibility(Record[6]);
2215
2216      GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
2217      if (Record.size() > 7)
2218        TLM = GetDecodedThreadLocalMode(Record[7]);
2219
2220      bool UnnamedAddr = false;
2221      if (Record.size() > 8)
2222        UnnamedAddr = Record[8];
2223
2224      GlobalVariable *NewGV =
2225        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
2226                           TLM, AddressSpace);
2227      NewGV->setAlignment(Alignment);
2228      if (!Section.empty())
2229        NewGV->setSection(Section);
2230      NewGV->setVisibility(Visibility);
2231      NewGV->setUnnamedAddr(UnnamedAddr);
2232
2233      ValueList.push_back(NewGV);
2234
2235      // Remember which value to use for the global initializer.
2236      if (unsigned InitID = Record[2])
2237        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
2238      break;
2239    }
2240    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
2241    //             alignment, section, visibility, gc, unnamed_addr]
2242    case bitc::MODULE_CODE_FUNCTION: {
2243      if (Record.size() < 8)
2244        return Error("Invalid record");
2245      Type *Ty = getTypeByID(Record[0]);
2246      if (!Ty)
2247        return Error("Invalid record");
2248      if (!Ty->isPointerTy())
2249        return Error("Invalid type for value");
2250      FunctionType *FTy =
2251        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2252      if (!FTy)
2253        return Error("Invalid type for value");
2254
2255      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
2256                                        "", TheModule);
2257
2258      Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
2259      bool isProto = Record[2];
2260      uint64_t RawLinkage = Record[3];
2261      Func->setLinkage(getDecodedLinkage(RawLinkage));
2262      Func->setAttributes(getAttributes(Record[4]));
2263
2264      Func->setAlignment((1 << Record[5]) >> 1);
2265      if (Record[6]) {
2266        if (Record[6]-1 >= SectionTable.size())
2267          return Error("Invalid ID");
2268        Func->setSection(SectionTable[Record[6]-1]);
2269      }
2270      Func->setVisibility(GetDecodedVisibility(Record[7]));
2271      if (Record.size() > 8 && Record[8]) {
2272        if (Record[8]-1 > GCTable.size())
2273          return Error("Invalid ID");
2274        Func->setGC(GCTable[Record[8]-1].c_str());
2275      }
2276      bool UnnamedAddr = false;
2277      if (Record.size() > 9)
2278        UnnamedAddr = Record[9];
2279      Func->setUnnamedAddr(UnnamedAddr);
2280      ValueList.push_back(Func);
2281
2282      // If this is a function with a body, remember the prototype we are
2283      // creating now, so that we can match up the body with them later.
2284      if (!isProto) {
2285        Func->setIsMaterializable(true);
2286        FunctionsWithBodies.push_back(Func);
2287        if (LazyStreamer)
2288          DeferredFunctionInfo[Func] = 0;
2289      }
2290      break;
2291    }
2292    // ALIAS: [alias type, aliasee val#, linkage]
2293    // ALIAS: [alias type, aliasee val#, linkage, visibility]
2294    case bitc::MODULE_CODE_ALIAS: {
2295      if (Record.size() < 3)
2296        return Error("Invalid record");
2297      Type *Ty = getTypeByID(Record[0]);
2298      if (!Ty)
2299        return Error("Invalid record");
2300      auto *PTy = dyn_cast<PointerType>(Ty);
2301      if (!PTy)
2302        return Error("Invalid type for value");
2303
2304      auto *NewGA =
2305          GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
2306      // Old bitcode files didn't have visibility field.
2307      if (Record.size() > 3)
2308        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
2309      ValueList.push_back(NewGA);
2310      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
2311      break;
2312    }
2313    /// MODULE_CODE_PURGEVALS: [numvals]
2314    case bitc::MODULE_CODE_PURGEVALS:
2315      // Trim down the value list to the specified size.
2316      if (Record.size() < 1 || Record[0] > ValueList.size())
2317        return Error("Invalid record");
2318      ValueList.shrinkTo(Record[0]);
2319      break;
2320    }
2321    Record.clear();
2322  }
2323
2324  return Error("Invalid bitcode signature");
2325}
2326
2327std::error_code BitcodeReader::ParseBitcodeInto(Module *M) {
2328  TheModule = nullptr;
2329
2330  if (std::error_code EC = InitStream())
2331    return EC;
2332
2333  // Sniff for the signature.
2334  if (Stream.Read(8) != 'B' ||
2335      Stream.Read(8) != 'C' ||
2336      Stream.Read(4) != 0x0 ||
2337      Stream.Read(4) != 0xC ||
2338      Stream.Read(4) != 0xE ||
2339      Stream.Read(4) != 0xD)
2340    return Error("Invalid bitcode signature");
2341
2342  // We expect a number of well-defined blocks, though we don't necessarily
2343  // need to understand them all.
2344  while (1) {
2345    if (Stream.AtEndOfStream())
2346      return std::error_code();
2347
2348    BitstreamEntry Entry =
2349      Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
2350
2351    switch (Entry.Kind) {
2352    case BitstreamEntry::Error:
2353      return Error("Malformed block");
2354    case BitstreamEntry::EndBlock:
2355      return std::error_code();
2356
2357    case BitstreamEntry::SubBlock:
2358      switch (Entry.ID) {
2359      case bitc::BLOCKINFO_BLOCK_ID:
2360        if (Stream.ReadBlockInfoBlock())
2361          return Error("Malformed block");
2362        break;
2363      case bitc::MODULE_BLOCK_ID:
2364        // Reject multiple MODULE_BLOCK's in a single bitstream.
2365        if (TheModule)
2366          return Error("Invalid multiple blocks");
2367        TheModule = M;
2368        if (std::error_code EC = ParseModule(false))
2369          return EC;
2370        if (LazyStreamer)
2371          return std::error_code();
2372        break;
2373      default:
2374        if (Stream.SkipBlock())
2375          return Error("Invalid record");
2376        break;
2377      }
2378      continue;
2379    case BitstreamEntry::Record:
2380      // There should be no records in the top-level of blocks.
2381
2382      // The ranlib in Xcode 4 will align archive members by appending newlines
2383      // to the end of them. If this file size is a multiple of 4 but not 8, we
2384      // have to read and ignore these final 4 bytes :-(
2385      if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 &&
2386          Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
2387          Stream.AtEndOfStream())
2388        return std::error_code();
2389
2390      return Error("Invalid record");
2391    }
2392  }
2393}
2394
2395llvm::ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
2396  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2397    return Error("Invalid record");
2398
2399  SmallVector<uint64_t, 64> Record;
2400
2401  std::string Triple;
2402  // Read all the records for this module.
2403  while (1) {
2404    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2405
2406    switch (Entry.Kind) {
2407    case BitstreamEntry::SubBlock: // Handled for us already.
2408    case BitstreamEntry::Error:
2409      return Error("Malformed block");
2410    case BitstreamEntry::EndBlock:
2411      return Triple;
2412    case BitstreamEntry::Record:
2413      // The interesting case.
2414      break;
2415    }
2416
2417    // Read a record.
2418    switch (Stream.readRecord(Entry.ID, Record)) {
2419    default: break;  // Default behavior, ignore unknown content.
2420    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
2421      if (Record.size() < 1)
2422        return Error("Invalid record");
2423      // Only version #0 is supported so far.
2424      if (Record[0] != 0)
2425        return Error("Invalid record");
2426      break;
2427    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
2428      std::string S;
2429      if (ConvertToString(Record, 0, S))
2430        return Error("Invalid record");
2431      Triple = S;
2432      break;
2433    }
2434    }
2435    Record.clear();
2436  }
2437
2438  return Error("Invalid bitcode signature");
2439}
2440
2441llvm::ErrorOr<std::string> BitcodeReader::parseTriple() {
2442  if (std::error_code EC = InitStream())
2443    return EC;
2444
2445  // Sniff for the signature.
2446  if (Stream.Read(8) != 'B' ||
2447      Stream.Read(8) != 'C' ||
2448      Stream.Read(4) != 0x0 ||
2449      Stream.Read(4) != 0xC ||
2450      Stream.Read(4) != 0xE ||
2451      Stream.Read(4) != 0xD)
2452    return Error("Invalid bitcode signature");
2453
2454  // We expect a number of well-defined blocks, though we don't necessarily
2455  // need to understand them all.
2456  while (1) {
2457    BitstreamEntry Entry = Stream.advance();
2458
2459    switch (Entry.Kind) {
2460    case BitstreamEntry::Error:
2461      return Error("Malformed block");
2462    case BitstreamEntry::EndBlock:
2463      return std::error_code();
2464
2465    case BitstreamEntry::SubBlock:
2466      if (Entry.ID == bitc::MODULE_BLOCK_ID)
2467        return parseModuleTriple();
2468
2469      // Ignore other sub-blocks.
2470      if (Stream.SkipBlock())
2471        return Error("Malformed block");
2472      continue;
2473
2474    case BitstreamEntry::Record:
2475      Stream.skipRecord(Entry.ID);
2476      continue;
2477    }
2478  }
2479}
2480
2481/// ParseMetadataAttachment - Parse metadata attachments.
2482std::error_code BitcodeReader::ParseMetadataAttachment() {
2483  if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2484    return Error("Invalid record");
2485
2486  SmallVector<uint64_t, 64> Record;
2487  while (1) {
2488    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2489
2490    switch (Entry.Kind) {
2491    case BitstreamEntry::SubBlock: // Handled for us already.
2492    case BitstreamEntry::Error:
2493      return Error("Malformed block");
2494    case BitstreamEntry::EndBlock:
2495      return std::error_code();
2496    case BitstreamEntry::Record:
2497      // The interesting case.
2498      break;
2499    }
2500
2501    // Read a metadata attachment record.
2502    Record.clear();
2503    switch (Stream.readRecord(Entry.ID, Record)) {
2504    default:  // Default behavior: ignore.
2505      break;
2506    case METADATA_ATTACHMENT_2_7:
2507      LLVM2_7MetadataDetected = true;
2508    case bitc::METADATA_ATTACHMENT: {
2509      unsigned RecordLength = Record.size();
2510      if (Record.empty() || (RecordLength - 1) % 2 == 1)
2511        return Error("Invalid record");
2512      Instruction *Inst = InstructionList[Record[0]];
2513      for (unsigned i = 1; i != RecordLength; i = i+2) {
2514        unsigned Kind = Record[i];
2515        DenseMap<unsigned, unsigned>::iterator I =
2516          MDKindMap.find(Kind);
2517        if (I == MDKindMap.end())
2518          return Error("Invalid ID");
2519        Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
2520        Inst->setMetadata(I->second, cast<MDNode>(Node));
2521      }
2522      break;
2523    }
2524    }
2525  }
2526}
2527
2528/// ParseFunctionBody - Lazily parse the specified function body block.
2529std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
2530  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2531    return Error("Invalid record");
2532
2533  InstructionList.clear();
2534  unsigned ModuleValueListSize = ValueList.size();
2535  unsigned ModuleMDValueListSize = MDValueList.size();
2536
2537  // Add all the function arguments to the value table.
2538  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
2539    ValueList.push_back(I);
2540
2541  unsigned NextValueNo = ValueList.size();
2542  BasicBlock *CurBB = nullptr;
2543  unsigned CurBBNo = 0;
2544
2545  DebugLoc LastLoc;
2546
2547  // Read all the records.
2548  SmallVector<uint64_t, 64> Record;
2549  while (1) {
2550    unsigned Code = Stream.ReadCode();
2551    if (Code == bitc::END_BLOCK) {
2552      if (Stream.ReadBlockEnd())
2553        return Error("Malformed block");
2554      break;
2555    }
2556
2557    if (Code == bitc::ENTER_SUBBLOCK) {
2558      switch (Stream.ReadSubBlockID()) {
2559      default:  // Skip unknown content.
2560        if (Stream.SkipBlock())
2561          return Error("Invalid record");
2562        break;
2563      case bitc::CONSTANTS_BLOCK_ID:
2564        if (std::error_code EC = ParseConstants())
2565          return EC;
2566        NextValueNo = ValueList.size();
2567        break;
2568      case bitc::VALUE_SYMTAB_BLOCK_ID:
2569        if (std::error_code EC = ParseValueSymbolTable())
2570          return EC;
2571        break;
2572      case bitc::METADATA_ATTACHMENT_ID:
2573        if (std::error_code EC = ParseMetadataAttachment())
2574          return EC;
2575        break;
2576      case bitc::METADATA_BLOCK_ID:
2577        if (std::error_code EC = ParseMetadata())
2578          return EC;
2579        break;
2580      }
2581      continue;
2582    }
2583
2584    if (Code == bitc::DEFINE_ABBREV) {
2585      Stream.ReadAbbrevRecord();
2586      continue;
2587    }
2588
2589    // Read a record.
2590    Record.clear();
2591    Instruction *I = nullptr;
2592    unsigned BitCode = Stream.readRecord(Code, Record);
2593    switch (BitCode) {
2594    default: // Default behavior: reject
2595      return Error("Invalid value");
2596    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
2597      if (Record.size() < 1 || Record[0] == 0)
2598        return Error("Invalid record");
2599      // Create all the basic blocks for the function.
2600      FunctionBBs.resize(Record[0]);
2601      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
2602        FunctionBBs[i] = BasicBlock::Create(Context, "", F);
2603      CurBB = FunctionBBs[0];
2604      continue;
2605
2606    case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
2607      // This record indicates that the last instruction is at the same
2608      // location as the previous instruction with a location.
2609      I = nullptr;
2610
2611      // Get the last instruction emitted.
2612      if (CurBB && !CurBB->empty())
2613        I = &CurBB->back();
2614      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2615               !FunctionBBs[CurBBNo-1]->empty())
2616        I = &FunctionBBs[CurBBNo-1]->back();
2617
2618      if (!I)
2619        return Error("Invalid record");
2620      I->setDebugLoc(LastLoc);
2621      I = nullptr;
2622      continue;
2623
2624    case FUNC_CODE_DEBUG_LOC_2_7:
2625      LLVM2_7MetadataDetected = true;
2626    case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
2627      I = nullptr;     // Get the last instruction emitted.
2628      if (CurBB && !CurBB->empty())
2629        I = &CurBB->back();
2630      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
2631               !FunctionBBs[CurBBNo-1]->empty())
2632        I = &FunctionBBs[CurBBNo-1]->back();
2633      if (!I || Record.size() < 4)
2634        return Error("Invalid record");
2635
2636      unsigned Line = Record[0], Col = Record[1];
2637      unsigned ScopeID = Record[2], IAID = Record[3];
2638
2639      MDNode *Scope = nullptr, *IA = nullptr;
2640      if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2641      if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2642      LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2643      I->setDebugLoc(LastLoc);
2644      I = nullptr;
2645      continue;
2646    }
2647
2648    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2649      unsigned OpNum = 0;
2650      Value *LHS, *RHS;
2651      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2652          getValue(Record, OpNum, LHS->getType(), RHS) ||
2653          OpNum+1 > Record.size())
2654        return Error("Invalid record");
2655
2656      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2657      if (Opc == -1)
2658        return Error("Invalid record");
2659      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2660      InstructionList.push_back(I);
2661      if (OpNum < Record.size()) {
2662        if (Opc == Instruction::Add ||
2663            Opc == Instruction::Sub ||
2664            Opc == Instruction::Mul ||
2665            Opc == Instruction::Shl) {
2666          if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2667            cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2668          if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2669            cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2670        } else if (Opc == Instruction::SDiv ||
2671                   Opc == Instruction::UDiv ||
2672                   Opc == Instruction::LShr ||
2673                   Opc == Instruction::AShr) {
2674          if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2675            cast<BinaryOperator>(I)->setIsExact(true);
2676        }
2677      }
2678      break;
2679    }
2680    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2681      unsigned OpNum = 0;
2682      Value *Op;
2683      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2684          OpNum+2 != Record.size())
2685        return Error("Invalid record");
2686
2687      Type *ResTy = getTypeByID(Record[OpNum]);
2688      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2689      if (Opc == -1 || !ResTy)
2690        return Error("Invalid record");
2691      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2692      InstructionList.push_back(I);
2693      break;
2694    }
2695    case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
2696    case bitc::FUNC_CODE_INST_GEP_OLD: // GEP: [n x operands]
2697    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2698      unsigned OpNum = 0;
2699
2700      Type *Ty;
2701      bool InBounds;
2702
2703      if (BitCode == bitc::FUNC_CODE_INST_GEP) {
2704        InBounds = Record[OpNum++];
2705        Ty = getTypeByID(Record[OpNum++]);
2706      } else {
2707        InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
2708        Ty = nullptr;
2709      }
2710
2711      Value *BasePtr;
2712      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2713        return Error("Invalid record");
2714
2715      if (Ty &&
2716          Ty !=
2717              cast<SequentialType>(BasePtr->getType()->getScalarType())
2718                  ->getElementType())
2719        return Error(
2720            "Explicit gep type does not match pointee type of pointer operand");
2721
2722      SmallVector<Value*, 16> GEPIdx;
2723      while (OpNum != Record.size()) {
2724        Value *Op;
2725        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2726          return Error("Invalid record");
2727        GEPIdx.push_back(Op);
2728      }
2729
2730      I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
2731
2732      InstructionList.push_back(I);
2733      if (InBounds)
2734        cast<GetElementPtrInst>(I)->setIsInBounds(true);
2735      break;
2736    }
2737
2738    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2739                                       // EXTRACTVAL: [opty, opval, n x indices]
2740      unsigned OpNum = 0;
2741      Value *Agg;
2742      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2743        return Error("Invalid record");
2744
2745      SmallVector<unsigned, 4> EXTRACTVALIdx;
2746      for (unsigned RecSize = Record.size();
2747           OpNum != RecSize; ++OpNum) {
2748        uint64_t Index = Record[OpNum];
2749        if ((unsigned)Index != Index)
2750          return Error("Invalid value");
2751        EXTRACTVALIdx.push_back((unsigned)Index);
2752      }
2753
2754      I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2755      InstructionList.push_back(I);
2756      break;
2757    }
2758
2759    case bitc::FUNC_CODE_INST_INSERTVAL: {
2760                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
2761      unsigned OpNum = 0;
2762      Value *Agg;
2763      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2764        return Error("Invalid record");
2765      Value *Val;
2766      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2767        return Error("Invalid record");
2768
2769      SmallVector<unsigned, 4> INSERTVALIdx;
2770      for (unsigned RecSize = Record.size();
2771           OpNum != RecSize; ++OpNum) {
2772        uint64_t Index = Record[OpNum];
2773        if ((unsigned)Index != Index)
2774          return Error("Invalid value");
2775        INSERTVALIdx.push_back((unsigned)Index);
2776      }
2777
2778      I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2779      InstructionList.push_back(I);
2780      break;
2781    }
2782
2783    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2784      // obsolete form of select
2785      // handles select i1 ... in old bitcode
2786      unsigned OpNum = 0;
2787      Value *TrueVal, *FalseVal, *Cond;
2788      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2789          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2790          getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2791        return Error("Invalid record");
2792
2793      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2794      InstructionList.push_back(I);
2795      break;
2796    }
2797
2798    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2799      // new form of select
2800      // handles select i1 or select [N x i1]
2801      unsigned OpNum = 0;
2802      Value *TrueVal, *FalseVal, *Cond;
2803      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2804          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2805          getValueTypePair(Record, OpNum, NextValueNo, Cond))
2806        return Error("Invalid record");
2807
2808      // select condition can be either i1 or [N x i1]
2809      if (VectorType* vector_type =
2810          dyn_cast<VectorType>(Cond->getType())) {
2811        // expect <n x i1>
2812        if (vector_type->getElementType() != Type::getInt1Ty(Context))
2813          return Error("Invalid type for value");
2814      } else {
2815        // expect i1
2816        if (Cond->getType() != Type::getInt1Ty(Context))
2817          return Error("Invalid type for value");
2818      }
2819
2820      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2821      InstructionList.push_back(I);
2822      break;
2823    }
2824
2825    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2826      unsigned OpNum = 0;
2827      Value *Vec, *Idx;
2828      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2829          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2830        return Error("Invalid record");
2831      I = ExtractElementInst::Create(Vec, Idx);
2832      InstructionList.push_back(I);
2833      break;
2834    }
2835
2836    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2837      unsigned OpNum = 0;
2838      Value *Vec, *Elt, *Idx;
2839      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2840          getValue(Record, OpNum,
2841                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2842          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2843        return Error("Invalid record");
2844      I = InsertElementInst::Create(Vec, Elt, Idx);
2845      InstructionList.push_back(I);
2846      break;
2847    }
2848
2849    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2850      unsigned OpNum = 0;
2851      Value *Vec1, *Vec2, *Mask;
2852      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2853          getValue(Record, OpNum, Vec1->getType(), Vec2))
2854        return Error("Invalid record");
2855
2856      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2857        return Error("Invalid record");
2858      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2859      InstructionList.push_back(I);
2860      break;
2861    }
2862
2863    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2864      // Old form of ICmp/FCmp returning bool
2865      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2866      // both legal on vectors but had different behaviour.
2867    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2868      // FCmp/ICmp returning bool or vector of bool
2869
2870      unsigned OpNum = 0;
2871      Value *LHS, *RHS;
2872      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2873          getValue(Record, OpNum, LHS->getType(), RHS) ||
2874          OpNum+1 != Record.size())
2875        return Error("Invalid record");
2876
2877      if (LHS->getType()->isFPOrFPVectorTy())
2878        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2879      else
2880        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2881      InstructionList.push_back(I);
2882      break;
2883    }
2884
2885    case FUNC_CODE_INST_GETRESULT_2_7: {
2886      if (Record.size() != 2) {
2887        return Error("Invalid record");
2888      }
2889      unsigned OpNum = 0;
2890      Value *Op;
2891      getValueTypePair(Record, OpNum, NextValueNo, Op);
2892      unsigned Index = Record[1];
2893      I = ExtractValueInst::Create(Op, Index);
2894      InstructionList.push_back(I);
2895      break;
2896    }
2897
2898    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2899      {
2900        unsigned Size = Record.size();
2901        if (Size == 0) {
2902          I = ReturnInst::Create(Context);
2903          InstructionList.push_back(I);
2904          break;
2905        }
2906
2907        unsigned OpNum = 0;
2908        Value *Op = nullptr;
2909        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2910          return Error("Invalid record");
2911        if (OpNum != Record.size())
2912          return Error("Invalid record");
2913
2914        I = ReturnInst::Create(Context, Op);
2915        InstructionList.push_back(I);
2916        break;
2917      }
2918    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2919      if (Record.size() != 1 && Record.size() != 3)
2920        return Error("Invalid record");
2921      BasicBlock *TrueDest = getBasicBlock(Record[0]);
2922      if (!TrueDest)
2923        return Error("Invalid record");
2924
2925      if (Record.size() == 1) {
2926        I = BranchInst::Create(TrueDest);
2927        InstructionList.push_back(I);
2928      }
2929      else {
2930        BasicBlock *FalseDest = getBasicBlock(Record[1]);
2931        Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2932        if (!FalseDest || !Cond)
2933          return Error("Invalid record");
2934        I = BranchInst::Create(TrueDest, FalseDest, Cond);
2935        InstructionList.push_back(I);
2936      }
2937      break;
2938    }
2939    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2940      if (Record.size() < 3 || (Record.size() & 1) == 0)
2941        return Error("Invalid record");
2942      Type *OpTy = getTypeByID(Record[0]);
2943      Value *Cond = getFnValueByID(Record[1], OpTy);
2944      BasicBlock *Default = getBasicBlock(Record[2]);
2945      if (!OpTy || !Cond || !Default)
2946        return Error("Invalid record");
2947      unsigned NumCases = (Record.size()-3)/2;
2948      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2949      InstructionList.push_back(SI);
2950      for (unsigned i = 0, e = NumCases; i != e; ++i) {
2951        ConstantInt *CaseVal =
2952          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2953        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2954        if (!CaseVal || !DestBB) {
2955          delete SI;
2956          return Error("Invalid record");
2957        }
2958        SI->addCase(CaseVal, DestBB);
2959      }
2960      I = SI;
2961      break;
2962    }
2963    case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2964      if (Record.size() < 2)
2965        return Error("Invalid record");
2966      Type *OpTy = getTypeByID(Record[0]);
2967      Value *Address = getFnValueByID(Record[1], OpTy);
2968      if (!OpTy || !Address)
2969        return Error("Invalid record");
2970      unsigned NumDests = Record.size()-2;
2971      IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2972      InstructionList.push_back(IBI);
2973      for (unsigned i = 0, e = NumDests; i != e; ++i) {
2974        if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2975          IBI->addDestination(DestBB);
2976        } else {
2977          delete IBI;
2978          return Error("Invalid record");
2979        }
2980      }
2981      I = IBI;
2982      break;
2983    }
2984
2985    case bitc::FUNC_CODE_INST_INVOKE: {
2986      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2987      if (Record.size() < 4)
2988        return Error("Invalid record");
2989      AttributeSet PAL = getAttributes(Record[0]);
2990      unsigned CCInfo = Record[1];
2991      BasicBlock *NormalBB = getBasicBlock(Record[2]);
2992      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2993
2994      unsigned OpNum = 4;
2995      Value *Callee;
2996      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2997        return Error("Invalid record");
2998
2999      PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
3000      FunctionType *FTy = !CalleeTy ? nullptr :
3001        dyn_cast<FunctionType>(CalleeTy->getElementType());
3002
3003      // Check that the right number of fixed parameters are here.
3004      if (!FTy || !NormalBB || !UnwindBB ||
3005          Record.size() < OpNum+FTy->getNumParams())
3006        return Error("Invalid record");
3007
3008      SmallVector<Value*, 16> Ops;
3009      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3010        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
3011        if (!Ops.back())
3012          return Error("Invalid record");
3013      }
3014
3015      if (!FTy->isVarArg()) {
3016        if (Record.size() != OpNum)
3017          return Error("Invalid record");
3018      } else {
3019        // Read type/value pairs for varargs params.
3020        while (OpNum != Record.size()) {
3021          Value *Op;
3022          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3023            return Error("Invalid record");
3024          Ops.push_back(Op);
3025        }
3026      }
3027
3028      I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
3029      InstructionList.push_back(I);
3030      cast<InvokeInst>(I)->setCallingConv(
3031        static_cast<CallingConv::ID>(CCInfo));
3032      cast<InvokeInst>(I)->setAttributes(PAL);
3033      break;
3034    }
3035    case FUNC_CODE_INST_UNWIND_2_7: { // UNWIND_OLD
3036      // 'unwind' instruction has been removed in LLVM 3.1
3037      // Replace 'unwind' with 'landingpad' and 'resume'.
3038      Type *ExnTy = StructType::get(Type::getInt8PtrTy(Context),
3039                                    Type::getInt32Ty(Context), nullptr);
3040      Constant *PersFn =
3041        F->getParent()->
3042        getOrInsertFunction("__gcc_personality_v0",
3043                          FunctionType::get(Type::getInt32Ty(Context), true));
3044
3045      LandingPadInst *LP = LandingPadInst::Create(ExnTy, PersFn, 1);
3046      LP->setCleanup(true);
3047
3048      CurBB->getInstList().push_back(LP);
3049      I = ResumeInst::Create(LP);
3050      InstructionList.push_back(I);
3051      break;
3052    }
3053    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
3054      I = new UnreachableInst(Context);
3055      InstructionList.push_back(I);
3056      break;
3057    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
3058      if (Record.size() < 1 || ((Record.size()-1)&1))
3059        return Error("Invalid record");
3060      Type *Ty = getTypeByID(Record[0]);
3061      if (!Ty)
3062        return Error("Invalid record");
3063
3064      PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
3065      InstructionList.push_back(PN);
3066
3067      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
3068        Value *V = getFnValueByID(Record[1+i], Ty);
3069        BasicBlock *BB = getBasicBlock(Record[2+i]);
3070        if (!V || !BB)
3071          return Error("Invalid record");
3072        PN->addIncoming(V, BB);
3073      }
3074      I = PN;
3075      break;
3076    }
3077
3078    case FUNC_CODE_INST_MALLOC_2_7: { // MALLOC: [instty, op, align]
3079      // Autoupgrade malloc instruction to malloc call.
3080      // FIXME: Remove in LLVM 3.0.
3081      if (Record.size() < 3) {
3082        return Error("Invalid record");
3083      }
3084      PointerType *Ty =
3085          dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
3086      Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
3087      if (!Ty || !Size)
3088        return Error("Invalid record");
3089      if (!CurBB)
3090        return Error("Invalid instruction with no BB");
3091      Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
3092      Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
3093      AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
3094      I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
3095                                 AllocSize, Size, nullptr);
3096      InstructionList.push_back(I);
3097      break;
3098    }
3099    case FUNC_CODE_INST_FREE_2_7: { // FREE: [op, opty]
3100      unsigned OpNum = 0;
3101      Value *Op;
3102      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3103          OpNum != Record.size()) {
3104        return Error("Invalid record");
3105      }
3106      if (!CurBB)
3107        return Error("Invalid instruction with no BB");
3108      I = CallInst::CreateFree(Op, CurBB);
3109      InstructionList.push_back(I);
3110      break;
3111    }
3112
3113    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
3114      // For backward compatibility, tolerate a lack of an opty, and use i32.
3115      // Remove this in LLVM 3.0.
3116      if (Record.size() < 3 || Record.size() > 4) {
3117        return Error("Invalid record");
3118      }
3119      unsigned OpNum = 0;
3120      PointerType *Ty =
3121        dyn_cast_or_null<PointerType>(getTypeByID(Record[OpNum++]));
3122      Type *OpTy = Record.size() == 4 ? getTypeByID(Record[OpNum++]) :
3123                                              Type::getInt32Ty(Context);
3124      Value *Size = getFnValueByID(Record[OpNum++], OpTy);
3125      unsigned Align = Record[OpNum++];
3126      if (!Ty || !Size)
3127        return Error("Invalid record");
3128      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
3129      InstructionList.push_back(I);
3130      break;
3131    }
3132    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
3133      unsigned OpNum = 0;
3134      Value *Op;
3135      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3136          OpNum+2 != Record.size())
3137        return Error("Invalid record");
3138
3139      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3140      InstructionList.push_back(I);
3141      break;
3142    }
3143    case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
3144      unsigned OpNum = 0;
3145      Value *Val, *Ptr;
3146      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
3147          getValue(Record, OpNum,
3148                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
3149          OpNum+2 != Record.size())
3150        return Error("Invalid record");
3151
3152      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3153      InstructionList.push_back(I);
3154      break;
3155    }
3156    case FUNC_CODE_INST_STORE_2_7: {
3157      unsigned OpNum = 0;
3158      Value *Val, *Ptr;
3159      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
3160          getValue(Record, OpNum,
3161                   PointerType::getUnqual(Val->getType()), Ptr)||
3162          OpNum+2 != Record.size()) {
3163        return Error("Invalid record");
3164      }
3165      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
3166      InstructionList.push_back(I);
3167      break;
3168    }
3169    case FUNC_CODE_INST_CALL_2_7:
3170      LLVM2_7MetadataDetected = true;
3171    case bitc::FUNC_CODE_INST_CALL: {
3172      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
3173      if (Record.size() < 3)
3174        return Error("Invalid record");
3175
3176      AttributeSet PAL = getAttributes(Record[0]);
3177      unsigned CCInfo = Record[1];
3178
3179      unsigned OpNum = 2;
3180      Value *Callee;
3181      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3182        return Error("Invalid record");
3183
3184      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
3185      FunctionType *FTy = nullptr;
3186      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
3187      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3188        return Error("Invalid record");
3189
3190      SmallVector<Value*, 16> Args;
3191      // Read the fixed params.
3192      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
3193        if (FTy->getParamType(i)->isLabelTy())
3194          Args.push_back(getBasicBlock(Record[OpNum]));
3195        else
3196          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
3197        if (!Args.back())
3198          return Error("Invalid record");
3199      }
3200
3201      // Read type/value pairs for varargs params.
3202      if (!FTy->isVarArg()) {
3203        if (OpNum != Record.size())
3204          return Error("Invalid record");
3205      } else {
3206        while (OpNum != Record.size()) {
3207          Value *Op;
3208          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3209            return Error("Invalid record");
3210          Args.push_back(Op);
3211        }
3212      }
3213
3214      I = CallInst::Create(Callee, Args);
3215      InstructionList.push_back(I);
3216      cast<CallInst>(I)->setCallingConv(
3217        static_cast<CallingConv::ID>(CCInfo>>1));
3218      cast<CallInst>(I)->setTailCall(CCInfo & 1);
3219      cast<CallInst>(I)->setAttributes(PAL);
3220      break;
3221    }
3222    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
3223      if (Record.size() < 3)
3224        return Error("Invalid record");
3225      Type *OpTy = getTypeByID(Record[0]);
3226      Value *Op = getFnValueByID(Record[1], OpTy);
3227      Type *ResTy = getTypeByID(Record[2]);
3228      if (!OpTy || !Op || !ResTy)
3229        return Error("Invalid record");
3230      I = new VAArgInst(Op, ResTy);
3231      InstructionList.push_back(I);
3232      break;
3233    }
3234    }
3235
3236    // Add instruction to end of current BB.  If there is no current BB, reject
3237    // this file.
3238    if (!CurBB) {
3239      delete I;
3240      return Error("Invalid instruction with no BB");
3241    }
3242    CurBB->getInstList().push_back(I);
3243
3244    // If this was a terminator instruction, move to the next block.
3245    if (isa<TerminatorInst>(I)) {
3246      ++CurBBNo;
3247      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
3248    }
3249
3250    // Non-void values get registered in the value table for future use.
3251    if (I && !I->getType()->isVoidTy())
3252      ValueList.AssignValue(I, NextValueNo++);
3253  }
3254
3255  // Check the function list for unresolved values.
3256  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
3257    if (!A->getParent()) {
3258      // We found at least one unresolved value.  Nuke them all to avoid leaks.
3259      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
3260        if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
3261          A->replaceAllUsesWith(UndefValue::get(A->getType()));
3262          delete A;
3263        }
3264      }
3265      return Error("Never resolved value found in function");
3266    }
3267  }
3268
3269  // FIXME: Check for unresolved forward-declared metadata references
3270  // and clean up leaks.
3271
3272  // See if anything took the address of blocks in this function.  If so,
3273  // resolve them now.
3274  DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
3275    BlockAddrFwdRefs.find(F);
3276  if (BAFRI != BlockAddrFwdRefs.end()) {
3277    std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
3278    for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
3279      unsigned BlockIdx = RefList[i].first;
3280      if (BlockIdx >= FunctionBBs.size())
3281        return Error("Invalid ID");
3282
3283      GlobalVariable *FwdRef = RefList[i].second;
3284      FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
3285      FwdRef->eraseFromParent();
3286    }
3287
3288    BlockAddrFwdRefs.erase(BAFRI);
3289  }
3290
3291  unsigned NewMDValueListSize = MDValueList.size();
3292  // Trim the value list down to the size it was before we parsed this function.
3293  ValueList.shrinkTo(ModuleValueListSize);
3294  MDValueList.shrinkTo(ModuleMDValueListSize);
3295
3296  if (LLVM2_7MetadataDetected) {
3297    MDValueList.resize(NewMDValueListSize);
3298  }
3299
3300  std::vector<BasicBlock*>().swap(FunctionBBs);
3301  return std::error_code();
3302}
3303
3304//===----------------------------------------------------------------------===//
3305// GVMaterializer implementation
3306//===----------------------------------------------------------------------===//
3307
3308void BitcodeReader::releaseBuffer() { Buffer.release(); }
3309
3310std::error_code BitcodeReader::materialize(GlobalValue *GV) {
3311  if (std::error_code EC = materializeMetadata())
3312    return EC;
3313
3314  Function *F = dyn_cast<Function>(GV);
3315  // If it's not a function or is already material, ignore the request.
3316  if (!F || !F->isMaterializable())
3317    return std::error_code();
3318
3319  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
3320  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
3321
3322  // Move the bit stream to the saved position of the deferred function body.
3323  Stream.JumpToBit(DFII->second);
3324
3325  if (std::error_code EC = ParseFunctionBody(F))
3326    return EC;
3327  F->setIsMaterializable(false);
3328
3329  // Upgrade any old intrinsic calls in the function.
3330  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
3331       E = UpgradedIntrinsics.end(); I != E; ++I) {
3332    if (I->first != I->second) {
3333      for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3334           UI != UE;) {
3335        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3336          UpgradeIntrinsicCall(CI, I->second);
3337      }
3338    }
3339  }
3340
3341  return std::error_code();
3342}
3343
3344bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
3345  const Function *F = dyn_cast<Function>(GV);
3346  if (!F || F->isDeclaration())
3347    return false;
3348  return DeferredFunctionInfo.count(const_cast<Function*>(F));
3349}
3350
3351void BitcodeReader::dematerialize(GlobalValue *GV) {
3352  Function *F = dyn_cast<Function>(GV);
3353  // If this function isn't dematerializable, this is a noop.
3354  if (!F || !isDematerializable(F))
3355    return;
3356
3357  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
3358
3359  // Just forget the function body, we can remat it later.
3360  F->deleteBody();
3361  F->setIsMaterializable(true);
3362}
3363
3364std::error_code BitcodeReader::materializeModule(Module *M) {
3365  assert(M == TheModule &&
3366         "Can only Materialize the Module this BitcodeReader is attached to.");
3367  // Iterate over the module, deserializing any functions that are still on
3368  // disk.
3369  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
3370       F != E; ++F) {
3371    if (std::error_code EC = materialize(F))
3372      return EC;
3373  }
3374  // At this point, if there are any function bodies, the current bit is
3375  // pointing to the END_BLOCK record after them. Now make sure the rest
3376  // of the bits in the module have been read.
3377  if (NextUnreadBit)
3378    ParseModule(true);
3379
3380  // Upgrade any intrinsic calls that slipped through (should not happen!) and
3381  // delete the old functions to clean up. We can't do this unless the entire
3382  // module is materialized because there could always be another function body
3383  // with calls to the old function.
3384  for (std::vector<std::pair<Function*, Function*> >::iterator I =
3385       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
3386    if (I->first != I->second) {
3387      for (auto UI = I->first->user_begin(), UE = I->first->user_end();
3388           UI != UE;) {
3389        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
3390          UpgradeIntrinsicCall(CI, I->second);
3391      }
3392      if (!I->first->use_empty())
3393        I->first->replaceAllUsesWith(I->second);
3394      I->first->eraseFromParent();
3395    }
3396  }
3397  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
3398
3399  // Check debug info intrinsics.
3400  CheckDebugInfoIntrinsics(TheModule);
3401
3402  return std::error_code();
3403}
3404
3405std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
3406  return IdentifiedStructTypes;
3407}
3408
3409std::error_code BitcodeReader::InitStream() {
3410  if (LazyStreamer)
3411    return InitLazyStream();
3412  return InitStreamFromBuffer();
3413}
3414
3415std::error_code BitcodeReader::InitStreamFromBuffer() {
3416  const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
3417  const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
3418
3419  if (Buffer->getBufferSize() & 3)
3420    return Error("Invalid bitcode signature");
3421
3422  // If we have a wrapper header, parse it and ignore the non-bc file contents.
3423  // The magic number is 0x0B17C0DE stored in little endian.
3424  if (isBitcodeWrapper(BufPtr, BufEnd))
3425    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3426      return Error("Invalid bitcode wrapper header");
3427
3428  StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
3429  Stream.init(&*StreamFile);
3430
3431  return std::error_code();
3432}
3433
3434std::error_code BitcodeReader::InitLazyStream() {
3435  // Check and strip off the bitcode wrapper; BitstreamReader expects never to
3436  // see it.
3437  auto OwnedBytes = llvm::make_unique<StreamingMemoryObject>(LazyStreamer);
3438  StreamingMemoryObject &Bytes = *OwnedBytes;
3439  StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
3440  Stream.init(&*StreamFile);
3441
3442  unsigned char buf[16];
3443  if (Bytes.readBytes(buf, 16, 0) != 16)
3444    return Error("Invalid bitcode signature");
3445
3446  if (!isBitcode(buf, buf + 16))
3447    return Error("Invalid bitcode signature");
3448
3449  if (isBitcodeWrapper(buf, buf + 4)) {
3450    const unsigned char *bitcodeStart = buf;
3451    const unsigned char *bitcodeEnd = buf + 16;
3452    SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
3453    Bytes.dropLeadingBytes(bitcodeStart - buf);
3454    Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
3455  }
3456  return std::error_code();
3457}
3458
3459namespace {
3460class BitcodeErrorCategoryType : public std::error_category {
3461  const char *name() const LLVM_NOEXCEPT override {
3462    return "llvm.bitcode";
3463  }
3464  std::string message(int IE) const override {
3465    BitcodeError E = static_cast<BitcodeError>(IE);
3466    switch (E) {
3467    case BitcodeError::InvalidBitcodeSignature:
3468      return "Invalid bitcode signature";
3469    case BitcodeError::CorruptedBitcode:
3470      return "Corrupted bitcode";
3471    }
3472    llvm_unreachable("Unknown error type!");
3473  }
3474};
3475}
3476
3477static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
3478
3479const std::error_category &BitcodeReader::BitcodeErrorCategory() {
3480  return *ErrorCategory;
3481}
3482
3483//===----------------------------------------------------------------------===//
3484// External interface
3485//===----------------------------------------------------------------------===//
3486
3487/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
3488///
3489static llvm::ErrorOr<llvm::Module *>
3490getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
3491                         LLVMContext &Context, bool WillMaterializeAll,
3492                         DiagnosticHandlerFunction DiagnosticHandler) {
3493  Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3494  BitcodeReader *R =
3495      new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
3496  M->setMaterializer(R);
3497
3498  auto cleanupOnError = [&](std::error_code EC) {
3499    R->releaseBuffer(); // Never take ownership on error.
3500    delete M;  // Also deletes R.
3501    return EC;
3502  };
3503
3504  if (std::error_code EC = R->ParseBitcodeInto(M))
3505    return cleanupOnError(EC);
3506
3507  Buffer.release(); // The BitcodeReader owns it now.
3508  return M;
3509}
3510
3511llvm::ErrorOr<Module *>
3512llvm_2_7::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
3513                           LLVMContext &Context,
3514                           DiagnosticHandlerFunction DiagnosticHandler) {
3515  return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3516                                  DiagnosticHandler);
3517}
3518
3519/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
3520/// If an error occurs, return null and fill in *ErrMsg if non-null.
3521llvm::ErrorOr<llvm::Module *>
3522llvm_2_7::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3523                       DiagnosticHandlerFunction DiagnosticHandler) {
3524  std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3525  ErrorOr<Module *> ModuleOrErr = getLazyBitcodeModuleImpl(
3526      std::move(Buf), Context, true, DiagnosticHandler);
3527  if (!ModuleOrErr)
3528    return ModuleOrErr;
3529  Module *M = ModuleOrErr.get();
3530  // Read in the entire module, and destroy the BitcodeReader.
3531  if (std::error_code EC = M->materializeAllPermanently()) {
3532    delete M;
3533    return EC;
3534  }
3535
3536  return M;
3537}
3538
3539std::string
3540llvm_2_7::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3541                             DiagnosticHandlerFunction DiagnosticHandler) {
3542  std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3543  auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
3544                                            DiagnosticHandler);
3545  ErrorOr<std::string> Triple = R->parseTriple();
3546  if (Triple.getError())
3547    return "";
3548  return Triple.get();
3549}
3550