Bytecode format for LLVM 1.2 no longer explicitly encodes zeros in primitive
[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     // Define this in case we don't see a ModuleGlobalInfo block.
50     FirstDerivedTyID = Type::FirstDerivedTyID;
51   }
52   
53   ~BytecodeParser() {
54     freeState();
55   }
56   void freeState() {
57     freeTable(Values);
58     freeTable(ModuleValues);
59   }
60
61   Module* releaseModule() {
62     // Since we're losing control of this Module, we must hand it back complete
63     Module *M = ModuleProvider::releaseModule();
64     freeState();
65     return M;
66   }
67
68   void ParseBytecode(const unsigned char *Buf, unsigned Length,
69                      const std::string &ModuleID);
70
71   void dump() const {
72     std::cerr << "BytecodeParser instance!\n";
73   }
74
75 private:
76   struct ValueList : public User {
77     ValueList() : User(Type::TypeTy, Value::TypeVal) {}
78
79     // vector compatibility methods
80     unsigned size() const { return getNumOperands(); }
81     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
82     Value *back() const { return Operands.back(); }
83     void pop_back() { Operands.pop_back(); }
84     bool empty() const { return Operands.empty(); }
85
86     virtual void print(std::ostream& OS) const {
87       OS << "Bytecode Reader UseHandle!";
88     }
89   };
90
91   // Information about the module, extracted from the bytecode revision number.
92   unsigned char RevisionNum;        // The rev # itself
93   unsigned char FirstDerivedTyID;   // First variable index to use for type
94   bool hasExtendedLinkageSpecs;     // Supports more than 4 linkage types
95   bool hasOldStyleVarargs;          // Has old version of varargs intrinsics?
96   bool hasVarArgCallPadding;        // Bytecode has extra padding in vararg call
97
98   bool usesOldStyleVarargs;         // Does this module USE old style varargs?
99
100   // Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
101
102   // Revision #0 had an explicit alignment of data only for the ModuleGlobalInfo
103   // block.  This was fixed to be like all other blocks in 1.2
104   bool hasInconsistentModuleGlobalInfo;
105
106   // Revision #0 also explicitly encoded zero values for primitive types like
107   // int/sbyte/etc.
108   bool hasExplicitPrimitiveZeros;
109
110   typedef std::vector<ValueList*> ValueTable;
111   ValueTable Values;
112   ValueTable ModuleValues;
113   std::map<std::pair<unsigned,unsigned>, Value*> ForwardReferences;
114
115   std::vector<BasicBlock*> ParsedBasicBlocks;
116
117   // ConstantFwdRefs - This maintains a mapping between <Type, Slot #>'s and
118   // forward references to constants.  Such values may be referenced before they
119   // are defined, and if so, the temporary object that they represent is held
120   // here.
121   //
122   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
123   ConstantRefsType ConstantFwdRefs;
124
125   // TypesLoaded - This vector mirrors the Values[TypeTyID] plane.  It is used
126   // to deal with forward references to types.
127   //
128   typedef std::vector<PATypeHolder> TypeValuesListTy;
129   TypeValuesListTy ModuleTypeValues;
130   TypeValuesListTy FunctionTypeValues;
131
132   // When the ModuleGlobalInfo section is read, we create a function object for
133   // each function in the module.  When the function is loaded, this function is
134   // filled in.
135   //
136   std::vector<Function*> FunctionSignatureList;
137
138   // Constant values are read in after global variables.  Because of this, we
139   // must defer setting the initializers on global variables until after module
140   // level constants have been read.  In the mean time, this list keeps track of
141   // what we must do.
142   //
143   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
144
145   // For lazy reading-in of functions, we need to save away several pieces of
146   // information about each function: its begin and end pointer in the buffer
147   // and its FunctionSlot.
148   // 
149   std::map<Function*, LazyFunctionInfo> LazyFunctionLoadMap;
150   
151 private:
152   void freeTable(ValueTable &Tab) {
153     while (!Tab.empty()) {
154       delete Tab.back();
155       Tab.pop_back();
156     }
157   }
158
159 public:
160   void ParseModule(const unsigned char * Buf, const unsigned char *End);
161   void materializeFunction(Function *F);
162
163 private:
164   void ParseVersionInfo   (const unsigned char *&Buf, const unsigned char *End);
165   void ParseModuleGlobalInfo(const unsigned char *&Buf, const unsigned char *E);
166   void ParseSymbolTable(const unsigned char *&Buf, const unsigned char *End,
167                         SymbolTable *, Function *CurrentFunction);
168   void ParseFunction(const unsigned char *&Buf, const unsigned char *End);
169   void ParseGlobalTypes(const unsigned char *&Buf, const unsigned char *EndBuf);
170
171   BasicBlock *ParseBasicBlock(const unsigned char *&Buf,
172                               const unsigned char *End,
173                               unsigned BlockNo);
174   unsigned ParseInstructionList(Function *F, const unsigned char *&Buf,
175                                 const unsigned char *EndBuf);
176   
177   void ParseInstruction(const unsigned char *&Buf, const unsigned char *End,
178                         std::vector<unsigned> &Args, BasicBlock *BB);
179
180   void ParseConstantPool(const unsigned char *&Buf, const unsigned char *EndBuf,
181                          ValueTable &Tab, TypeValuesListTy &TypeTab);
182   Constant *parseConstantValue(const unsigned char *&Buf,
183                                const unsigned char *End,
184                                unsigned TypeID);
185   void parseTypeConstants(const unsigned char *&Buf,
186                           const unsigned char *EndBuf,
187                           TypeValuesListTy &Tab, unsigned NumEntries);
188   const Type *parseTypeConstant(const unsigned char *&Buf,
189                                 const unsigned char *EndBuf);
190   void parseStringConstants(const unsigned char *&Buf,
191                             const unsigned char *EndBuf,
192                             unsigned NumEntries, ValueTable &Tab);
193
194   Value      *getValue(unsigned TypeID, unsigned num, bool Create = true);
195   const Type *getType(unsigned ID);
196   BasicBlock *getBasicBlock(unsigned ID);
197   Constant   *getConstantValue(unsigned TypeID, unsigned num);
198   Constant   *getConstantValue(const Type *Ty, unsigned num) {
199     return getConstantValue(getTypeSlot(Ty), num);
200   }
201
202   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
203
204   unsigned getTypeSlot(const Type *Ty);
205
206   // resolve all references to the placeholder (if any) for the given constant
207   void ResolveReferencesToConstant(Constant *C, unsigned Slot);
208 };
209
210 template<class SuperType>
211 class PlaceholderDef : public SuperType {
212   unsigned ID;
213   PlaceholderDef();                       // DO NOT IMPLEMENT
214   void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
215 public:
216   PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
217   unsigned getID() { return ID; }
218 };
219
220 struct ConstantPlaceHolderHelper : public ConstantExpr {
221   ConstantPlaceHolderHelper(const Type *Ty)
222     : ConstantExpr(Instruction::UserOp1, Constant::getNullValue(Ty), Ty) {}
223 };
224
225 typedef PlaceholderDef<ConstantPlaceHolderHelper>  ConstPHolder;
226
227 static inline void readBlock(const unsigned char *&Buf,
228                              const unsigned char *EndBuf, 
229                              unsigned &Type, unsigned &Size) {
230   Type = read(Buf, EndBuf);
231   Size = read(Buf, EndBuf);
232 }
233
234 } // End llvm namespace
235
236 #endif