BitcodeReader.h revision 9b10dfb7d6ffb0e4466f908cd7d18212a45cfdac
1//===- BitcodeReader.h - Internal BitcodeReader impl ------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef BITCODE_READER_H
15#define BITCODE_READER_H
16
17#include "llvm/GVMaterializer.h"
18#include "llvm/Attributes.h"
19#include "llvm/Type.h"
20#include "llvm/OperandTraits.h"
21#include "llvm/Bitcode/BitstreamReader.h"
22#include "llvm/Bitcode/LLVMBitCodes.h"
23#include "llvm/Support/ValueHandle.h"
24#include "llvm/ADT/DenseMap.h"
25#include <vector>
26
27namespace llvm {
28  class MemoryBuffer;
29  class LLVMContext;
30
31//===----------------------------------------------------------------------===//
32//                          BitcodeReaderValueList Class
33//===----------------------------------------------------------------------===//
34
35class BitcodeReaderValueList {
36  std::vector<WeakVH> ValuePtrs;
37
38  /// ResolveConstants - As we resolve forward-referenced constants, we add
39  /// information about them to this vector.  This allows us to resolve them in
40  /// bulk instead of resolving each reference at a time.  See the code in
41  /// ResolveConstantForwardRefs for more information about this.
42  ///
43  /// The key of this vector is the placeholder constant, the value is the slot
44  /// number that holds the resolved value.
45  typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
46  ResolveConstantsTy ResolveConstants;
47  LLVMContext& Context;
48public:
49  BitcodeReaderValueList(LLVMContext& C) : Context(C) {}
50  ~BitcodeReaderValueList() {
51    assert(ResolveConstants.empty() && "Constants not resolved?");
52  }
53
54  // vector compatibility methods
55  unsigned size() const { return ValuePtrs.size(); }
56  void resize(unsigned N) { ValuePtrs.resize(N); }
57  void push_back(Value *V) {
58    ValuePtrs.push_back(V);
59  }
60
61  void clear() {
62    assert(ResolveConstants.empty() && "Constants not resolved?");
63    ValuePtrs.clear();
64  }
65
66  Value *operator[](unsigned i) const {
67    assert(i < ValuePtrs.size());
68    return ValuePtrs[i];
69  }
70
71  Value *back() const { return ValuePtrs.back(); }
72    void pop_back() { ValuePtrs.pop_back(); }
73  bool empty() const { return ValuePtrs.empty(); }
74  void shrinkTo(unsigned N) {
75    assert(N <= size() && "Invalid shrinkTo request!");
76    ValuePtrs.resize(N);
77  }
78
79  Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
80  Value *getValueFwdRef(unsigned Idx, const Type *Ty);
81
82  void AssignValue(Value *V, unsigned Idx);
83
84  /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
85  /// resolves any forward references.
86  void ResolveConstantForwardRefs();
87};
88
89
90//===----------------------------------------------------------------------===//
91//                          BitcodeReaderMDValueList Class
92//===----------------------------------------------------------------------===//
93
94class BitcodeReaderMDValueList {
95  std::vector<WeakVH> MDValuePtrs;
96
97  LLVMContext &Context;
98public:
99  BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
100
101  // vector compatibility methods
102  unsigned size() const       { return MDValuePtrs.size(); }
103  void resize(unsigned N)     { MDValuePtrs.resize(N); }
104  void push_back(Value *V)    { MDValuePtrs.push_back(V);  }
105  void clear()                { MDValuePtrs.clear();  }
106  Value *back() const         { return MDValuePtrs.back(); }
107  void pop_back()             { MDValuePtrs.pop_back(); }
108  bool empty() const          { return MDValuePtrs.empty(); }
109
110  Value *operator[](unsigned i) const {
111    assert(i < MDValuePtrs.size());
112    return MDValuePtrs[i];
113  }
114
115  void shrinkTo(unsigned N) {
116    assert(N <= size() && "Invalid shrinkTo request!");
117    MDValuePtrs.resize(N);
118  }
119
120  Value *getValueFwdRef(unsigned Idx);
121  void AssignValue(Value *V, unsigned Idx);
122};
123
124class BitcodeReader : public GVMaterializer {
125  LLVMContext &Context;
126  Module *TheModule;
127  MemoryBuffer *Buffer;
128  bool BufferOwned;
129  BitstreamReader StreamFile;
130  BitstreamCursor Stream;
131
132  const char *ErrorString;
133
134  std::vector<PATypeHolder> TypeList;
135  BitcodeReaderValueList ValueList;
136  BitcodeReaderMDValueList MDValueList;
137  SmallVector<Instruction *, 64> InstructionList;
138
139  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
140  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
141
142  /// MAttributes - The set of attributes by index.  Index zero in the
143  /// file is for null, and is thus not represented here.  As such all indices
144  /// are off by one.
145  std::vector<AttrListPtr> MAttributes;
146
147  /// FunctionBBs - While parsing a function body, this is a list of the basic
148  /// blocks for the function.
149  std::vector<BasicBlock*> FunctionBBs;
150
151  // When reading the module header, this list is populated with functions that
152  // have bodies later in the file.
153  std::vector<Function*> FunctionsWithBodies;
154
155  // When intrinsic functions are encountered which require upgrading they are
156  // stored here with their replacement function.
157  typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
158  UpgradedIntrinsicMap UpgradedIntrinsics;
159
160  // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
161  DenseMap<unsigned, unsigned> MDKindMap;
162
163  // After the module header has been read, the FunctionsWithBodies list is
164  // reversed.  This keeps track of whether we've done this yet.
165  bool HasReversedFunctionsWithBodies;
166
167  /// DeferredFunctionInfo - When function bodies are initially scanned, this
168  /// map contains info about where to find deferred function body in the
169  /// stream.
170  DenseMap<Function*, uint64_t> DeferredFunctionInfo;
171
172  /// BlockAddrFwdRefs - These are blockaddr references to basic blocks.  These
173  /// are resolved lazily when functions are loaded.
174  typedef std::pair<unsigned, GlobalVariable*> BlockAddrRefTy;
175  DenseMap<Function*, std::vector<BlockAddrRefTy> > BlockAddrFwdRefs;
176
177  /// LLVM2_7MetadataDetected - True if metadata produced by LLVM 2.7 or
178  /// earlier was detected, in which case we behave slightly differently,
179  /// for compatibility.
180  /// FIXME: Remove in LLVM 3.0.
181  bool LLVM2_7MetadataDetected;
182
183public:
184  explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
185    : Context(C), TheModule(0), Buffer(buffer), BufferOwned(false),
186      ErrorString(0), ValueList(C), MDValueList(C),
187      LLVM2_7MetadataDetected(false) {
188    HasReversedFunctionsWithBodies = false;
189  }
190  ~BitcodeReader() {
191    FreeState();
192  }
193
194  void FreeState();
195
196  /// setBufferOwned - If this is true, the reader will destroy the MemoryBuffer
197  /// when the reader is destroyed.
198  void setBufferOwned(bool Owned) { BufferOwned = Owned; }
199
200  virtual bool isMaterializable(const GlobalValue *GV) const;
201  virtual bool isDematerializable(const GlobalValue *GV) const;
202  virtual bool Materialize(GlobalValue *GV, std::string *ErrInfo = 0);
203  virtual bool MaterializeModule(Module *M, std::string *ErrInfo = 0);
204  virtual void Dematerialize(GlobalValue *GV);
205
206  bool Error(const char *Str) {
207    ErrorString = Str;
208    return true;
209  }
210  const char *getErrorString() const { return ErrorString; }
211
212  /// @brief Main interface to parsing a bitcode buffer.
213  /// @returns true if an error occurred.
214  bool ParseBitcodeInto(Module *M);
215private:
216  const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
217  Value *getFnValueByID(unsigned ID, const Type *Ty) {
218    if (Ty == Type::getMetadataTy(Context))
219      return MDValueList.getValueFwdRef(ID);
220    else
221      return ValueList.getValueFwdRef(ID, Ty);
222  }
223  BasicBlock *getBasicBlock(unsigned ID) const {
224    if (ID >= FunctionBBs.size()) return 0; // Invalid ID
225    return FunctionBBs[ID];
226  }
227  AttrListPtr getAttributes(unsigned i) const {
228    if (i-1 < MAttributes.size())
229      return MAttributes[i-1];
230    return AttrListPtr();
231  }
232
233  /// getValueTypePair - Read a value/type pair out of the specified record from
234  /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
235  /// Return true on failure.
236  bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
237                        unsigned InstNum, Value *&ResVal) {
238    if (Slot == Record.size()) return true;
239    unsigned ValNo = (unsigned)Record[Slot++];
240    if (ValNo < InstNum) {
241      // If this is not a forward reference, just return the value we already
242      // have.
243      ResVal = getFnValueByID(ValNo, 0);
244      return ResVal == 0;
245    } else if (Slot == Record.size()) {
246      return true;
247    }
248
249    unsigned TypeNo = (unsigned)Record[Slot++];
250    ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
251    return ResVal == 0;
252  }
253  bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
254                const Type *Ty, Value *&ResVal) {
255    if (Slot == Record.size()) return true;
256    unsigned ValNo = (unsigned)Record[Slot++];
257    ResVal = getFnValueByID(ValNo, Ty);
258    return ResVal == 0;
259  }
260
261
262  bool ParseModule();
263  bool ParseAttributeBlock();
264  bool ParseTypeTable();
265  bool ParseTypeSymbolTable();
266  bool ParseValueSymbolTable();
267  bool ParseConstants();
268  bool RememberAndSkipFunctionBody();
269  bool ParseFunctionBody(Function *F);
270  bool ResolveGlobalAndAliasInits();
271  bool ParseMetadata();
272  bool ParseMetadataAttachment();
273};
274
275} // End llvm namespace
276
277#endif
278