ff28e25db61d04e435296e16c8b45b3aab0a770d
[oota-llvm.git] / lib / Bytecode / Reader / ReaderInternals.h
1 //===-- ReaderInternals.h - Definitions internal to the reader --*- C++ -*-===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 //  This header file defines various stuff that is used by the bytecode reader.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef READER_INTERNALS_H
15 #define READER_INTERNALS_H
16
17 #include "ReaderPrimitives.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/ModuleProvider.h"
22 #include <utility>
23 #include <map>
24
25 namespace llvm {
26
27 // Enable to trace to figure out what the heck is going on when parsing fails
28 //#define TRACE_LEVEL 10
29 //#define DEBUG_OUTPUT
30
31 #if TRACE_LEVEL    // ByteCodeReading_TRACEr
32 #define BCR_TRACE(n, X) \
33     if (n < TRACE_LEVEL) std::cerr << std::string(n*2, ' ') << X
34 #else
35 #define BCR_TRACE(n, X)
36 #endif
37
38 struct LazyFunctionInfo {
39   const unsigned char *Buf, *EndBuf;
40   LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
41     : Buf(B), EndBuf(EB) {}
42 };
43
44 class BytecodeParser : public ModuleProvider {
45   BytecodeParser(const BytecodeParser &);  // DO NOT IMPLEMENT
46   void operator=(const BytecodeParser &);  // DO NOT IMPLEMENT
47 public:
48   BytecodeParser() {}
49   
50   ~BytecodeParser() {
51     freeState();
52   }
53   void freeState() {
54     freeTable(Values);
55     freeTable(ModuleValues);
56   }
57
58   Module* materializeModule() {
59     while (! LazyFunctionLoadMap.empty()) {
60       std::map<Function*, LazyFunctionInfo>::iterator i = 
61         LazyFunctionLoadMap.begin();
62       materializeFunction((*i).first);
63     }
64
65     return TheModule;
66   }
67
68   Module* releaseModule() {
69     // Since we're losing control of this Module, we must hand it back complete
70     Module *M = ModuleProvider::releaseModule();
71     freeState();
72     return M;
73   }
74
75   void ParseBytecode(const unsigned char *Buf, unsigned Length,
76                      const std::string &ModuleID);
77
78   void dump() const {
79     std::cerr << "BytecodeParser instance!\n";
80   }
81
82 private:
83   struct ValueList : public User {
84     ValueList() : User(Type::TypeTy, Value::TypeVal) {}
85
86     // vector compatibility methods
87     unsigned size() const { return getNumOperands(); }
88     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
89     Value *back() const { return Operands.back(); }
90     void pop_back() { Operands.pop_back(); }
91     bool empty() const { return Operands.empty(); }
92
93     virtual void print(std::ostream& OS) const {
94       OS << "Bytecode Reader UseHandle!";
95     }
96   };
97
98   // Information about the module, extracted from the bytecode revision number.
99   unsigned char RevisionNum;        // The rev # itself
100   bool hasExtendedLinkageSpecs;     // Supports more than 4 linkage types
101   bool hasOldStyleVarargs;          // Has old version of varargs intrinsics?
102   bool hasVarArgCallPadding;        // Bytecode has extra padding in vararg call
103
104   bool usesOldStyleVarargs;         // Does this module USE old style varargs?
105
106   // Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
107
108   // Revision #0 had an explicit alignment of data only for the ModuleGlobalInfo
109   // block.  This was fixed to be like all other blocks in 1.2
110   bool hasInconsistentModuleGlobalInfo;
111
112   // Revision #0 also explicitly encoded zero values for primitive types like
113   // int/sbyte/etc.
114   bool hasExplicitPrimitiveZeros;
115
116   typedef std::vector<ValueList*> ValueTable;
117   ValueTable Values;
118   ValueTable ModuleValues;
119   std::map<std::pair<unsigned,unsigned>, Value*> ForwardReferences;
120
121   /// CompactionTable - If a compaction table is active in the current function,
122   /// this is the mapping that it contains.
123   std::vector<std::vector<Value*> > CompactionTable;
124
125   std::vector<BasicBlock*> ParsedBasicBlocks;
126
127   // ConstantFwdRefs - This maintains a mapping between <Type, Slot #>'s and
128   // forward references to constants.  Such values may be referenced before they
129   // are defined, and if so, the temporary object that they represent is held
130   // here.
131   //
132   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
133   ConstantRefsType ConstantFwdRefs;
134
135   // TypesLoaded - This vector mirrors the Values[TypeTyID] plane.  It is used
136   // to deal with forward references to types.
137   //
138   typedef std::vector<PATypeHolder> TypeValuesListTy;
139   TypeValuesListTy ModuleTypeValues;
140   TypeValuesListTy FunctionTypeValues;
141
142   // When the ModuleGlobalInfo section is read, we create a function object for
143   // each function in the module.  When the function is loaded, this function is
144   // filled in.
145   //
146   std::vector<Function*> FunctionSignatureList;
147
148   // Constant values are read in after global variables.  Because of this, we
149   // must defer setting the initializers on global variables until after module
150   // level constants have been read.  In the mean time, this list keeps track of
151   // what we must do.
152   //
153   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
154
155   // For lazy reading-in of functions, we need to save away several pieces of
156   // information about each function: its begin and end pointer in the buffer
157   // and its FunctionSlot.
158   // 
159   std::map<Function*, LazyFunctionInfo> LazyFunctionLoadMap;
160   
161 private:
162   void freeTable(ValueTable &Tab) {
163     while (!Tab.empty()) {
164       delete Tab.back();
165       Tab.pop_back();
166     }
167   }
168
169   /// getGlobalTableType - This is just like getType, but when a compaction
170   /// table is in use, it is ignored.  Also, no forward references or other
171   /// fancy features are supported.
172   const Type *getGlobalTableType(unsigned Slot) {
173     if (Slot < Type::FirstDerivedTyID) {
174       const Type *Ty = Type::getPrimitiveType((Type::PrimitiveID)Slot);
175       assert(Ty && "Not a primitive type ID?");
176       return Ty;
177     }
178     Slot -= Type::FirstDerivedTyID;
179     if (Slot >= ModuleTypeValues.size())
180       throw std::string("Illegal compaction table type reference!");
181     return ModuleTypeValues[Slot];
182   }
183
184   unsigned getGlobalTableTypeSlot(const Type *Ty) {
185     if (Ty->isPrimitiveType())
186       return Ty->getPrimitiveID();
187     TypeValuesListTy::iterator I = find(ModuleTypeValues.begin(),
188                                         ModuleTypeValues.end(), Ty);
189     if (I == ModuleTypeValues.end())
190       throw std::string("Didn't find type in ModuleTypeValues.");
191     return Type::FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
192   }
193
194   /// getGlobalTableValue - This is just like getValue, but when a compaction
195   /// table is in use, it is ignored.  Also, no forward references or other
196   /// fancy features are supported.
197   Value *getGlobalTableValue(const Type *Ty, unsigned SlotNo) {
198     // FIXME: getTypeSlot is inefficient!
199     unsigned TyID = getGlobalTableTypeSlot(Ty);
200     
201     if (TyID != Type::LabelTyID) {
202       if (SlotNo == 0)
203         return Constant::getNullValue(Ty);
204       --SlotNo;
205     }
206
207     if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
208         SlotNo >= ModuleValues[TyID]->getNumOperands()) {
209       std::cerr << TyID << ", " << SlotNo << ": " << ModuleValues.size() << ", "
210                 << (void*)ModuleValues[TyID] << ", "
211                 << ModuleValues[TyID]->getNumOperands() << "\n";
212       throw std::string("Corrupt compaction table entry!");
213     }
214     return ModuleValues[TyID]->getOperand(SlotNo);
215   }
216
217 public:
218   void ParseModule(const unsigned char * Buf, const unsigned char *End);
219   void materializeFunction(Function *F);
220
221 private:
222   void ParseVersionInfo   (const unsigned char *&Buf, const unsigned char *End);
223   void ParseModuleGlobalInfo(const unsigned char *&Buf, const unsigned char *E);
224   void ParseSymbolTable(const unsigned char *&Buf, const unsigned char *End,
225                         SymbolTable *, Function *CurrentFunction);
226   void ParseFunction(const unsigned char *&Buf, const unsigned char *End);
227   void ParseCompactionTable(const unsigned char *&Buf,const unsigned char *End);
228   void ParseGlobalTypes(const unsigned char *&Buf, const unsigned char *EndBuf);
229
230   BasicBlock *ParseBasicBlock(const unsigned char *&Buf,
231                               const unsigned char *End,
232                               unsigned BlockNo);
233   unsigned ParseInstructionList(Function *F, const unsigned char *&Buf,
234                                 const unsigned char *EndBuf);
235   
236   void ParseInstruction(const unsigned char *&Buf, const unsigned char *End,
237                         std::vector<unsigned> &Args, BasicBlock *BB);
238
239   void ParseConstantPool(const unsigned char *&Buf, const unsigned char *EndBuf,
240                          ValueTable &Tab, TypeValuesListTy &TypeTab);
241   Constant *parseConstantValue(const unsigned char *&Buf,
242                                const unsigned char *End,
243                                unsigned TypeID);
244   void parseTypeConstants(const unsigned char *&Buf,
245                           const unsigned char *EndBuf,
246                           TypeValuesListTy &Tab, unsigned NumEntries);
247   const Type *parseTypeConstant(const unsigned char *&Buf,
248                                 const unsigned char *EndBuf);
249   void parseStringConstants(const unsigned char *&Buf,
250                             const unsigned char *EndBuf,
251                             unsigned NumEntries, ValueTable &Tab);
252
253   Value      *getValue(unsigned TypeID, unsigned num, bool Create = true);
254   const Type *getType(unsigned ID);
255   BasicBlock *getBasicBlock(unsigned ID);
256   Constant   *getConstantValue(unsigned TypeID, unsigned num);
257   Constant   *getConstantValue(const Type *Ty, unsigned num) {
258     return getConstantValue(getTypeSlot(Ty), num);
259   }
260
261   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
262
263   unsigned getTypeSlot(const Type *Ty);
264
265   // resolve all references to the placeholder (if any) for the given constant
266   void ResolveReferencesToConstant(Constant *C, unsigned Slot);
267 };
268
269 template<class SuperType>
270 class PlaceholderDef : public SuperType {
271   unsigned ID;
272   PlaceholderDef();                       // DO NOT IMPLEMENT
273   void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
274 public:
275   PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
276   unsigned getID() { return ID; }
277 };
278
279 struct ConstantPlaceHolderHelper : public ConstantExpr {
280   ConstantPlaceHolderHelper(const Type *Ty)
281     : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty) {}
282 };
283
284 typedef PlaceholderDef<ConstantPlaceHolderHelper>  ConstPHolder;
285
286 static inline void readBlock(const unsigned char *&Buf,
287                              const unsigned char *EndBuf, 
288                              unsigned &Type, unsigned &Size) {
289   Type = read(Buf, EndBuf);
290   Size = read(Buf, EndBuf);
291 }
292
293 } // End llvm namespace
294
295 #endif