BitcodeReader.h revision d67c632d968157e228cf42b588f8759059730ec0
1//===- BitcodeReader.h - Internal BitcodeReader impl ------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source 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/ModuleProvider.h"
18#include "llvm/Type.h"
19#include "llvm/User.h"
20#include "llvm/Bitcode/BitstreamReader.h"
21#include "llvm/Bitcode/LLVMBitCodes.h"
22#include "llvm/ADT/DenseMap.h"
23#include <vector>
24
25namespace llvm {
26  class MemoryBuffer;
27  class ParamAttrsList;
28
29class BitcodeReaderValueList : public User {
30  std::vector<Use> Uses;
31public:
32  BitcodeReaderValueList() : User(Type::VoidTy, Value::ArgumentVal, 0, 0) {}
33
34  // vector compatibility methods
35  unsigned size() const { return getNumOperands(); }
36  void push_back(Value *V) {
37    Uses.push_back(Use(V, this));
38    OperandList = &Uses[0];
39    ++NumOperands;
40  }
41
42  Value *operator[](unsigned i) const { return getOperand(i); }
43
44  Value *back() const { return Uses.back(); }
45  void pop_back() { Uses.pop_back(); --NumOperands; }
46  bool empty() const { return NumOperands == 0; }
47  void shrinkTo(unsigned N) {
48    assert(N <= NumOperands && "Invalid shrinkTo request!");
49    Uses.resize(N);
50    NumOperands = N;
51  }
52  virtual void print(std::ostream&) const {}
53
54  Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
55  Value *getValueFwdRef(unsigned Idx, const Type *Ty);
56
57  void AssignValue(Value *V, unsigned Idx) {
58    if (Idx == size()) {
59      push_back(V);
60    } else if (Value *OldV = getOperand(Idx)) {
61      // If there was a forward reference to this value, replace it.
62      setOperand(Idx, V);
63      OldV->replaceAllUsesWith(V);
64      delete OldV;
65    } else {
66      initVal(Idx, V);
67    }
68  }
69
70private:
71  void initVal(unsigned Idx, Value *V) {
72    assert(Uses[Idx] == 0 && "Cannot init an already init'd Use!");
73    Uses[Idx].init(V, this);
74  }
75};
76
77
78class BitcodeReader : public ModuleProvider {
79  MemoryBuffer *Buffer;
80  BitstreamReader Stream;
81
82  const char *ErrorString;
83
84  std::vector<PATypeHolder> TypeList;
85  BitcodeReaderValueList ValueList;
86  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
87  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
88
89  /// ParamAttrs - The set of parameter attributes by index.  Index zero in the
90  /// file is for null, and is thus not represented here.  As such all indices
91  /// are off by one.
92  std::vector<const ParamAttrsList*> ParamAttrs;
93
94  /// FunctionBBs - While parsing a function body, this is a list of the basic
95  /// blocks for the function.
96  std::vector<BasicBlock*> FunctionBBs;
97
98  // When reading the module header, this list is populated with functions that
99  // have bodies later in the file.
100  std::vector<Function*> FunctionsWithBodies;
101
102  // After the module header has been read, the FunctionsWithBodies list is
103  // reversed.  This keeps track of whether we've done this yet.
104  bool HasReversedFunctionsWithBodies;
105
106  /// DeferredFunctionInfo - When function bodies are initially scanned, this
107  /// map contains info about where to find deferred function body (in the
108  /// stream) and what linkage the original function had.
109  DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
110public:
111  BitcodeReader(MemoryBuffer *buffer) : Buffer(buffer), ErrorString(0) {
112    HasReversedFunctionsWithBodies = false;
113  }
114  ~BitcodeReader();
115
116
117  /// releaseMemoryBuffer - This causes the reader to completely forget about
118  /// the memory buffer it contains, which prevents the buffer from being
119  /// destroyed when it is deleted.
120  void releaseMemoryBuffer() {
121    Buffer = 0;
122  }
123
124  virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
125  virtual Module *materializeModule(std::string *ErrInfo = 0);
126  virtual void dematerializeFunction(Function *F);
127
128  bool Error(const char *Str) {
129    ErrorString = Str;
130    return true;
131  }
132  const char *getErrorString() const { return ErrorString; }
133
134  /// @brief Main interface to parsing a bitcode buffer.
135  /// @returns true if an error occurred.
136  bool ParseBitcode();
137private:
138  const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
139  Value *getFnValueByID(unsigned ID, const Type *Ty) {
140    return ValueList.getValueFwdRef(ID, Ty);
141  }
142  BasicBlock *getBasicBlock(unsigned ID) const {
143    if (ID >= FunctionBBs.size()) return 0; // Invalid ID
144    return FunctionBBs[ID];
145  }
146  const ParamAttrsList *getParamAttrs(unsigned i) const {
147    if (i-1 < ParamAttrs.size())
148      return ParamAttrs[i-1];
149    return 0;
150  }
151
152  /// getValueTypePair - Read a value/type pair out of the specified record from
153  /// slot 'Slot'.  Increment Slot past the number of slots used in the record.
154  /// Return true on failure.
155  bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
156                        unsigned InstNum, Value *&ResVal) {
157    if (Slot == Record.size()) return true;
158    unsigned ValNo = (unsigned)Record[Slot++];
159    if (ValNo < InstNum) {
160      // If this is not a forward reference, just return the value we already
161      // have.
162      ResVal = getFnValueByID(ValNo, 0);
163      return ResVal == 0;
164    } else if (Slot == Record.size()) {
165      return true;
166    }
167
168    unsigned TypeNo = (unsigned)Record[Slot++];
169    ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
170    return ResVal == 0;
171  }
172  bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
173                const Type *Ty, Value *&ResVal) {
174    if (Slot == Record.size()) return true;
175    unsigned ValNo = (unsigned)Record[Slot++];
176    ResVal = getFnValueByID(ValNo, Ty);
177    return ResVal == 0;
178  }
179
180
181  bool ParseModule(const std::string &ModuleID);
182  bool ParseParamAttrBlock();
183  bool ParseTypeTable();
184  bool ParseTypeSymbolTable();
185  bool ParseValueSymbolTable();
186  bool ParseConstants();
187  bool RememberAndSkipFunctionBody();
188  bool ParseFunctionBody(Function *F);
189  bool ResolveGlobalAndAliasInits();
190};
191
192} // End llvm namespace
193
194#endif
195