Pass a vector around to reduce dynamic allocation
[oota-llvm.git] / lib / Bytecode / Reader / ReaderInternals.h
1 //===-- ReaderInternals.h - Definitions internal to the reader ---*- C++ -*--=//
2 //
3 //  This header file defines various stuff that is used by the bytecode reader.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #ifndef READER_INTERNALS_H
8 #define READER_INTERNALS_H
9
10 #include "llvm/Constant.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Function.h"
13 #include "llvm/ModuleProvider.h"
14 #include "llvm/Bytecode/Primitives.h"
15 #include <utility>
16 #include <map>
17
18 // Enable to trace to figure out what the heck is going on when parsing fails
19 //#define TRACE_LEVEL 10
20
21 #if TRACE_LEVEL    // ByteCodeReading_TRACEr
22 #define BCR_TRACE(n, X) \
23     if (n < TRACE_LEVEL) std::cerr << std::string(n*2, ' ') << X
24 #else
25 #define BCR_TRACE(n, X)
26 #endif
27
28 struct LazyFunctionInfo {
29   const unsigned char *Buf, *EndBuf;
30   unsigned FunctionSlot;
31 };
32
33 class BytecodeParser : public ModuleProvider {
34   BytecodeParser(const BytecodeParser &);  // DO NOT IMPLEMENT
35   void operator=(const BytecodeParser &);  // DO NOT IMPLEMENT
36 public:
37   BytecodeParser() {
38     // Define this in case we don't see a ModuleGlobalInfo block.
39     FirstDerivedTyID = Type::FirstDerivedTyID;
40   }
41   
42   ~BytecodeParser() {
43     freeState();
44   }
45   void freeState() {
46     freeTable(Values);
47     freeTable(ModuleValues);
48   }
49
50   Module* releaseModule() {
51     // Since we're losing control of this Module, we must hand it back complete
52     Module *M = ModuleProvider::releaseModule();
53     freeState();
54     return M;
55   }
56
57   void ParseBytecode(const unsigned char *Buf, unsigned Length,
58                      const std::string &ModuleID);
59
60   void dump() const {
61     std::cerr << "BytecodeParser instance!\n";
62   }
63
64 private:
65   struct ValueList : public User {
66     ValueList() : User(Type::TypeTy, Value::TypeVal) {}
67
68     // vector compatibility methods
69     unsigned size() const { return getNumOperands(); }
70     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
71     Value *back() const { return Operands.back(); }
72     void pop_back() { Operands.pop_back(); }
73     bool empty() const { return Operands.empty(); }
74
75     virtual void print(std::ostream& OS) const {
76       OS << "Bytecode Reader UseHandle!";
77     }
78   };
79
80   // Information about the module, extracted from the bytecode revision number.
81   unsigned char RevisionNum;        // The rev # itself
82   unsigned char FirstDerivedTyID;   // First variable index to use for type
83   bool HasImplicitZeroInitializer;  // Is entry 0 of every slot implicity zeros?
84   bool hasInternalMarkerOnly;       // Only types of linkage are intern/external
85
86   typedef std::vector<ValueList*> ValueTable;
87   ValueTable Values;
88   ValueTable ModuleValues;
89   std::map<std::pair<unsigned,unsigned>, Value*> ForwardReferences;
90
91   std::vector<BasicBlock*> ParsedBasicBlocks;
92
93   // GlobalRefs - This maintains a mapping between <Type, Slot #>'s and forward
94   // references to global values or constants.  Such values may be referenced
95   // before they are defined, and if so, the temporary object that they
96   // represent is held here.
97   //
98   typedef std::map<std::pair<const Type *, unsigned>, Value*>  GlobalRefsType;
99   GlobalRefsType GlobalRefs;
100
101   // TypesLoaded - This vector mirrors the Values[TypeTyID] plane.  It is used
102   // to deal with forward references to types.
103   //
104   typedef std::vector<PATypeHolder> TypeValuesListTy;
105   TypeValuesListTy ModuleTypeValues;
106   TypeValuesListTy FunctionTypeValues;
107
108   // When the ModuleGlobalInfo section is read, we create a function object for
109   // each function in the module.  When the function is loaded, this function is
110   // filled in.
111   //
112   std::vector<std::pair<Function*, unsigned> > FunctionSignatureList;
113
114   // Constant values are read in after global variables.  Because of this, we
115   // must defer setting the initializers on global variables until after module
116   // level constants have been read.  In the mean time, this list keeps track of
117   // what we must do.
118   //
119   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
120
121   // For lazy reading-in of functions, we need to save away several pieces of
122   // information about each function: its begin and end pointer in the buffer
123   // and its FunctionSlot.
124   // 
125   std::map<Function*, LazyFunctionInfo*> LazyFunctionLoadMap;
126   
127 private:
128   void freeTable(ValueTable &Tab) {
129     while (!Tab.empty()) {
130       delete Tab.back();
131       Tab.pop_back();
132     }
133   }
134
135 public:
136   void ParseModule(const unsigned char * Buf, const unsigned char *End);
137   void materializeFunction(Function *F);
138
139 private:
140   void ParseVersionInfo   (const unsigned char *&Buf, const unsigned char *End);
141   void ParseModuleGlobalInfo(const unsigned char *&Buf, const unsigned char *E);
142   void ParseSymbolTable(const unsigned char *&Buf, const unsigned char *End,
143                         SymbolTable *, Function *CurrentFunction);
144   void ParseFunction(const unsigned char *&Buf, const unsigned char *End);
145   void ParseGlobalTypes(const unsigned char *&Buf, const unsigned char *EndBuf);
146
147   BasicBlock *ParseBasicBlock(const unsigned char *&Buf,
148                               const unsigned char *End,
149                               unsigned BlockNo);
150
151   Instruction *ParseInstruction(const unsigned char *&Buf,
152                                 const unsigned char *End,
153                                 std::vector<unsigned> &Args);
154
155   void ParseConstantPool(const unsigned char *&Buf, const unsigned char *EndBuf,
156                          ValueTable &Tab, TypeValuesListTy &TypeTab);
157   Constant *parseConstantValue(const unsigned char *&Buf,
158                                const unsigned char *End,
159                                const Type *Ty);
160   void parseTypeConstants(const unsigned char *&Buf,
161                           const unsigned char *EndBuf,
162                           TypeValuesListTy &Tab, unsigned NumEntries);
163   const Type *parseTypeConstant(const unsigned char *&Buf,
164                                 const unsigned char *EndBuf);
165
166   Value      *getValue(const Type *Ty, unsigned num, bool Create = true);
167   Value      *getValue(unsigned TypeID, unsigned num, bool Create = true);
168   const Type *getType(unsigned ID);
169   BasicBlock *getBasicBlock(unsigned ID);
170   Constant   *getConstantValue(const Type *Ty, unsigned num);
171
172   unsigned insertValue(Value *V, ValueTable &Table);
173
174   unsigned getTypeSlot(const Type *Ty);
175
176   // resolve all references to the placeholder (if any) for the given value
177   void ResolveReferencesToValue(Value *Val, unsigned Slot);
178 };
179
180 template<class SuperType>
181 class PlaceholderDef : public SuperType {
182   unsigned ID;
183   PlaceholderDef();                       // DO NOT IMPLEMENT
184   void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
185 public:
186   PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
187   unsigned getID() { return ID; }
188 };
189
190 struct ConstantPlaceHolderHelper : public Constant {
191   ConstantPlaceHolderHelper(const Type *Ty)
192     : Constant(Ty) {}
193   virtual bool isNullValue() const { return false; }
194 };
195
196 typedef PlaceholderDef<ConstantPlaceHolderHelper>  ConstPHolder;
197
198 // Some common errors we find
199 static const std::string Error_readvbr   = "read_vbr(): error reading.";
200 static const std::string Error_read      = "read(): error reading.";
201 static const std::string Error_inputdata = "input_data(): error reading.";
202 static const std::string Error_DestSlot  = "No destination slot found.";
203
204 static inline void readBlock(const unsigned char *&Buf,
205                              const unsigned char *EndBuf, 
206                              unsigned &Type, unsigned &Size) {
207 #if DEBUG_OUTPUT
208   bool Result = read(Buf, EndBuf, Type) || read(Buf, EndBuf, Size);
209   std::cerr << "StartLoc = " << ((unsigned)Buf & 4095)
210        << " Type = " << Type << " Size = " << Size << endl;
211   if (Result) throw Error_read;
212 #else
213   if (read(Buf, EndBuf, Type) || read(Buf, EndBuf, Size)) throw Error_read;
214 #endif
215 }
216
217 #endif