Non-functional change
[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/Bytecode/Primitives.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/Function.h"
13 #include "llvm/Constant.h"
14 #include <utility>
15 #include <map>
16
17 // Enable to trace to figure out what the heck is going on when parsing fails
18 //#define TRACE_LEVEL 10
19
20 #if TRACE_LEVEL    // ByteCodeReading_TRACEer
21 #define BCR_TRACE(n, X) \
22     if (n < TRACE_LEVEL) std::cerr << std::string(n*2, ' ') << X
23 #else
24 #define BCR_TRACE(n, X)
25 #endif
26
27 struct RawInst {       // The raw fields out of the bytecode stream...
28   unsigned NumOperands;
29   unsigned Opcode;
30   const Type *Ty;
31   unsigned Arg1, Arg2;
32   union {
33     unsigned Arg3;
34     std::vector<unsigned> *VarArgs; // Contains arg #3,4,5... if NumOperands > 3
35   };
36 };
37
38 class BytecodeParser : public AbstractTypeUser {
39   std::string Error;     // Error message string goes here...
40   BytecodeParser(const BytecodeParser &);  // DO NOT IMPLEMENT
41   void operator=(const BytecodeParser &);  // DO NOT IMPLEMENT
42 public:
43   BytecodeParser() {
44     // Define this in case we don't see a ModuleGlobalInfo block.
45     FirstDerivedTyID = Type::FirstDerivedTyID;
46   }
47   ~BytecodeParser() {
48     freeState();
49   }
50   void freeState() {
51     freeTable(Values);
52     freeTable(LateResolveValues);
53     freeTable(ModuleValues);
54   }
55
56   Module *ParseBytecode(const unsigned char *Buf, const unsigned char *EndBuf,
57                         const std::string &ModuleID);
58
59   std::string getError() const { return Error; }
60
61   void dump() const {
62     std::cerr << "BytecodeParser instance!\n";
63   }
64
65 private:          // All of this data is transient across calls to ParseBytecode
66   struct ValueList : public User {
67     ValueList() : User(Type::TypeTy, Value::TypeVal) {
68     }
69     ~ValueList() {}
70
71     // vector compatibility methods
72     unsigned size() const { return getNumOperands(); }
73     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
74     Value *back() const { return Operands.back(); }
75     void pop_back() { Operands.pop_back(); }
76     bool empty() const { return Operands.empty(); }
77
78     virtual void print(std::ostream& OS) const {
79       OS << "Bytecode Reader UseHandle!";
80     }
81   };
82
83   Module *TheModule;   // Current Module being read into...
84   
85   // Information about the module, extracted from the bytecode revision number.
86   unsigned char RevisionNum;        // The rev # itself
87   unsigned char FirstDerivedTyID;   // First variable index to use for type
88   bool HasImplicitZeroInitializer;  // Is entry 0 of every slot implicity zeros?
89   bool hasInternalMarkerOnly;       // Only types of linkage are intern/external
90
91   typedef std::vector<ValueList*> ValueTable;
92   ValueTable Values, LateResolveValues;
93   ValueTable ModuleValues;
94
95   // GlobalRefs - This maintains a mapping between <Type, Slot #>'s and forward
96   // references to global values or constants.  Such values may be referenced
97   // before they are defined, and if so, the temporary object that they
98   // represent is held here.
99   //
100   typedef std::map<std::pair<const Type *, unsigned>, Value*>  GlobalRefsType;
101   GlobalRefsType GlobalRefs;
102
103   // TypesLoaded - This vector mirrors the Values[TypeTyID] plane.  It is used
104   // to deal with forward references to types.
105   //
106   typedef std::vector<PATypeHandle> TypeValuesListTy;
107   TypeValuesListTy ModuleTypeValues;
108   TypeValuesListTy FunctionTypeValues;
109
110   // When the ModuleGlobalInfo section is read, we create a function object for
111   // each function in the module.  When the function is loaded, this function is
112   // filled in.
113   //
114   std::vector<std::pair<Function*, unsigned> > FunctionSignatureList;
115
116   // Constant values are read in after global variables.  Because of this, we
117   // must defer setting the initializers on global variables until after module
118   // level constants have been read.  In the mean time, this list keeps track of
119   // what we must do.
120   //
121   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
122
123 private:
124   void freeTable(ValueTable &Tab) {
125     while (!Tab.empty()) {
126       delete Tab.back();
127       Tab.pop_back();
128     }
129   }
130
131   bool ParseModule        (const unsigned char * Buf, const unsigned char *End);
132   bool ParseVersionInfo   (const unsigned char *&Buf, const unsigned char *End);
133   bool ParseModuleGlobalInfo(const unsigned char *&Buf, const unsigned char *E);
134   bool ParseSymbolTable   (const unsigned char *&Buf, const unsigned char *End,
135                            SymbolTable *);
136   bool ParseFunction      (const unsigned char *&Buf, const unsigned char *End);
137   bool ParseBasicBlock    (const unsigned char *&Buf, const unsigned char *End,
138                            BasicBlock *&);
139   bool ParseInstruction   (const unsigned char *&Buf, const unsigned char *End,
140                            Instruction *&, BasicBlock *BB /*HACK*/);
141   bool ParseRawInst       (const unsigned char *&Buf, const unsigned char *End,
142                            RawInst &);
143
144   bool ParseGlobalTypes(const unsigned char *&Buf, const unsigned char *EndBuf);
145   bool ParseConstantPool(const unsigned char *&Buf, const unsigned char *EndBuf,
146                          ValueTable &Tab, TypeValuesListTy &TypeTab);
147   bool parseConstantValue(const unsigned char *&Buf, const unsigned char *End,
148                           const Type *Ty, Constant *&V);
149   bool parseTypeConstants(const unsigned char *&Buf,
150                           const unsigned char *EndBuf,
151                           TypeValuesListTy &Tab, unsigned NumEntries);
152   const Type *parseTypeConstant(const unsigned char *&Buf,
153                                 const unsigned char *EndBuf);
154
155   Value      *getValue(const Type *Ty, unsigned num, bool Create = true);
156   const Type *getType(unsigned ID);
157   Constant   *getConstantValue(const Type *Ty, unsigned num);
158
159   int insertValue(Value *V, ValueTable &Table);  // -1 = Failure
160   void setValueTo(ValueTable &D, unsigned Slot, Value *V);
161   bool postResolveValues(ValueTable &ValTab);
162
163   bool getTypeSlot(const Type *Ty, unsigned &Slot);
164
165   // resolve all references to the placeholder (if any) for the given value
166   void ResolveReferencesToValue(Value *Val, unsigned Slot);
167
168   
169   // refineAbstractType - The callback method is invoked when one of the
170   // elements of TypeValues becomes more concrete...
171   //
172   virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
173 };
174
175 template<class SuperType>
176 class PlaceholderDef : public SuperType {
177   unsigned ID;
178   PlaceholderDef();                       // DO NOT IMPLEMENT
179   void operator=(const PlaceholderDef &); // DO NOT IMPLEMENT
180 public:
181   PlaceholderDef(const Type *Ty, unsigned id) : SuperType(Ty), ID(id) {}
182   unsigned getID() { return ID; }
183 };
184
185 struct InstPlaceHolderHelper : public Instruction {
186   InstPlaceHolderHelper(const Type *Ty) : Instruction(Ty, UserOp1, "") {}
187   virtual const char *getOpcodeName() const { return "placeholder"; }
188
189   virtual Instruction *clone() const { abort(); return 0; }
190 };
191
192 struct BBPlaceHolderHelper : public BasicBlock {
193   BBPlaceHolderHelper(const Type *Ty) : BasicBlock() {
194     assert(Ty == Type::LabelTy);
195   }
196 };
197
198 struct ConstantPlaceHolderHelper : public Constant {
199   ConstantPlaceHolderHelper(const Type *Ty)
200     : Constant(Ty) {}
201   virtual bool isNullValue() const { return false; }
202 };
203
204 typedef PlaceholderDef<InstPlaceHolderHelper>  ValPHolder;
205 typedef PlaceholderDef<BBPlaceHolderHelper>    BBPHolder;
206 typedef PlaceholderDef<ConstantPlaceHolderHelper>  ConstPHolder;
207
208
209 static inline unsigned getValueIDNumberFromPlaceHolder(Value *Val) {
210   if (isa<Constant>(Val))
211     return ((ConstPHolder*)Val)->getID();
212   
213   // else discriminate by type
214   switch (Val->getType()->getPrimitiveID()) {
215   case Type::LabelTyID:    return ((BBPHolder*)Val)->getID();
216   default:                 return ((ValPHolder*)Val)->getID();
217   }
218 }
219
220 static inline bool readBlock(const unsigned char *&Buf,
221                              const unsigned char *EndBuf, 
222                              unsigned &Type, unsigned &Size) {
223 #if DEBUG_OUTPUT
224   bool Result = read(Buf, EndBuf, Type) || read(Buf, EndBuf, Size);
225   std::cerr << "StartLoc = " << ((unsigned)Buf & 4095)
226        << " Type = " << Type << " Size = " << Size << endl;
227   return Result;
228 #else
229   return read(Buf, EndBuf, Type) || read(Buf, EndBuf, Size);
230 #endif
231 }
232
233 #endif