b182f6dbfaa3745efe748086da542fe243eaf505
[oota-llvm.git] / lib / Bytecode / Writer / SlotCalculator.cpp
1 //===-- SlotCalculator.cpp - Calculate what slots values land in ----------===//
2 //
3 // This file implements a useful analysis step to figure out what numbered 
4 // slots values in a program will land in (keeping track of per plane
5 // information as required.
6 //
7 // This is used primarily for when writing a file to disk, either in bytecode
8 // or source format.
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/SlotCalculator.h"
13 #include "llvm/Analysis/ConstantsScanner.h"
14 #include "llvm/Module.h"
15 #include "llvm/iOther.h"
16 #include "llvm/Constant.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/SymbolTable.h"
19 #include "Support/DepthFirstIterator.h"
20 #include "Support/STLExtras.h"
21 #include <algorithm>
22
23 #if 0
24 #define SC_DEBUG(X) std::cerr << X
25 #else
26 #define SC_DEBUG(X)
27 #endif
28
29 SlotCalculator::SlotCalculator(const Module *M, bool IgnoreNamed) {
30   IgnoreNamedNodes = IgnoreNamed;
31   TheModule = M;
32
33   // Preload table... Make sure that all of the primitive types are in the table
34   // and that their Primitive ID is equal to their slot #
35   //
36   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
37     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
38     insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
39   }
40
41   if (M == 0) return;   // Empty table...
42   processModule();
43 }
44
45 SlotCalculator::SlotCalculator(const Function *M, bool IgnoreNamed) {
46   IgnoreNamedNodes = IgnoreNamed;
47   TheModule = M ? M->getParent() : 0;
48
49   // Preload table... Make sure that all of the primitive types are in the table
50   // and that their Primitive ID is equal to their slot #
51   //
52   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
53     assert(Type::getPrimitiveType((Type::PrimitiveID)i));
54     insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
55   }
56
57   if (TheModule == 0) return;   // Empty table...
58
59   processModule();              // Process module level stuff
60   incorporateFunction(M);         // Start out in incorporated state
61 }
62
63
64 // processModule - Process all of the module level function declarations and
65 // types that are available.
66 //
67 void SlotCalculator::processModule() {
68   SC_DEBUG("begin processModule!\n");
69
70   // Add all of the global variables to the value table...
71   //
72   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
73        I != E; ++I)
74     getOrCreateSlot(I);
75
76   // Scavenge the types out of the functions, then add the functions themselves
77   // to the value table...
78   //
79   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
80        I != E; ++I)
81     getOrCreateSlot(I);
82
83   // Add all of the module level constants used as initializers
84   //
85   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
86        I != E; ++I)
87     if (I->hasInitializer())
88       getOrCreateSlot(I->getInitializer());
89
90   // Insert constants that are named at module level into the slot pool so that
91   // the module symbol table can refer to them...
92   //
93   if (!IgnoreNamedNodes) {
94     SC_DEBUG("Inserting SymbolTable values:\n");
95     processSymbolTable(&TheModule->getSymbolTable());
96   }
97
98   SC_DEBUG("end processModule!\n");
99 }
100
101 // processSymbolTable - Insert all of the values in the specified symbol table
102 // into the values table...
103 //
104 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
105   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
106     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
107            TE = I->second.end(); TI != TE; ++TI)
108       getOrCreateSlot(TI->second);
109 }
110
111 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
112   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
113     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
114            TE = I->second.end(); TI != TE; ++TI)
115       if (isa<Constant>(TI->second))
116         getOrCreateSlot(TI->second);
117 }
118
119
120 void SlotCalculator::incorporateFunction(const Function *F) {
121   assert(ModuleLevel.size() == 0 && "Module already incorporated!");
122
123   SC_DEBUG("begin processFunction!\n");
124
125   // Save the Table state before we process the function...
126   for (unsigned i = 0; i < Table.size(); ++i)
127     ModuleLevel.push_back(Table[i].size());
128
129   SC_DEBUG("Inserting function arguments\n");
130
131   // Iterate over function arguments, adding them to the value table...
132   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
133     getOrCreateSlot(I);
134
135   // Iterate over all of the instructions in the function, looking for constant
136   // values that are referenced.  Add these to the value pools before any
137   // nonconstant values.  This will be turned into the constant pool for the
138   // bytecode writer.
139   //
140   if (!IgnoreNamedNodes) {                // Assembly writer does not need this!
141     SC_DEBUG("Inserting function constants:\n";
142              for (constant_iterator I = constant_begin(F), E = constant_end(F);
143                   I != E; ++I) {
144                std::cerr << "  " << *I->getType() << " " << *I << "\n";
145              });
146
147     // Emit all of the constants that are being used by the instructions in the
148     // function...
149     for_each(constant_begin(F), constant_end(F),
150              bind_obj(this, &SlotCalculator::getOrCreateSlot));
151
152     // If there is a symbol table, it is possible that the user has names for
153     // constants that are not being used.  In this case, we will have problems
154     // if we don't emit the constants now, because otherwise we will get 
155     // symboltable references to constants not in the output.  Scan for these
156     // constants now.
157     //
158     processSymbolTableConstants(&F->getSymbolTable());
159   }
160
161   SC_DEBUG("Inserting Labels:\n");
162
163   // Iterate over basic blocks, adding them to the value table...
164   for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
165     getOrCreateSlot(I);
166
167   SC_DEBUG("Inserting Instructions:\n");
168
169   // Add all of the instructions to the type planes...
170   for_each(inst_begin(F), inst_end(F),
171            bind_obj(this, &SlotCalculator::getOrCreateSlot));
172
173   if (!IgnoreNamedNodes) {
174     SC_DEBUG("Inserting SymbolTable values:\n");
175     processSymbolTable(&F->getSymbolTable());
176   }
177
178   SC_DEBUG("end processFunction!\n");
179 }
180
181 void SlotCalculator::purgeFunction() {
182   assert(ModuleLevel.size() != 0 && "Module not incorporated!");
183   unsigned NumModuleTypes = ModuleLevel.size();
184
185   SC_DEBUG("begin purgeFunction!\n");
186
187   // First, remove values from existing type planes
188   for (unsigned i = 0; i < NumModuleTypes; ++i) {
189     unsigned ModuleSize = ModuleLevel[i];  // Size of plane before function came
190     TypePlane &CurPlane = Table[i];
191     //SC_DEBUG("Processing Plane " <<i<< " of size " << CurPlane.size() <<"\n");
192              
193     while (CurPlane.size() != ModuleSize) {
194       //SC_DEBUG("  Removing [" << i << "] Value=" << CurPlane.back() << "\n");
195       std::map<const Value *, unsigned>::iterator NI =
196         NodeMap.find(CurPlane.back());
197       assert(NI != NodeMap.end() && "Node not in nodemap?");
198       NodeMap.erase(NI);   // Erase from nodemap
199       CurPlane.pop_back();                            // Shrink plane
200     }
201   }
202
203   // We don't need this state anymore, free it up.
204   ModuleLevel.clear();
205
206   // Next, remove any type planes defined by the function...
207   while (NumModuleTypes != Table.size()) {
208     TypePlane &Plane = Table.back();
209     SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
210              << Plane.size() << "\n");
211     while (Plane.size()) {
212       NodeMap.erase(NodeMap.find(Plane.back()));   // Erase from nodemap
213       Plane.pop_back();                            // Shrink plane
214     }
215
216     Table.pop_back();                      // Nuke the plane, we don't like it.
217   }
218
219   SC_DEBUG("end purgeFunction!\n");
220 }
221
222 int SlotCalculator::getSlot(const Value *D) const {
223   std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
224   if (I == NodeMap.end()) return -1;
225  
226   return (int)I->second;
227 }
228
229
230 int SlotCalculator::getOrCreateSlot(const Value *V) {
231   int SlotNo = getSlot(V);        // Check to see if it's already in!
232   if (SlotNo != -1) return SlotNo;
233
234   if (!isa<GlobalValue>(V))
235     if (const Constant *C = dyn_cast<Constant>(V)) {
236       // This makes sure that if a constant has uses (for example an array of
237       // const ints), that they are inserted also.
238       //
239       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
240            I != E; ++I)
241         getOrCreateSlot(*I);
242     }
243
244   return insertValue(V);
245 }
246
247
248 int SlotCalculator::insertValue(const Value *D, bool dontIgnore) {
249   assert(D && "Can't insert a null value!");
250   assert(getSlot(D) == -1 && "Value is already in the table!");
251
252   // If this node does not contribute to a plane, or if the node has a 
253   // name and we don't want names, then ignore the silly node... Note that types
254   // do need slot numbers so that we can keep track of where other values land.
255   //
256   if (!dontIgnore)                               // Don't ignore nonignorables!
257     if (D->getType() == Type::VoidTy ||          // Ignore void type nodes
258         (IgnoreNamedNodes &&                     // Ignore named and constants
259          (D->hasName() || isa<Constant>(D)) && !isa<Type>(D))) {
260       SC_DEBUG("ignored value " << *D << "\n");
261       return -1;                  // We do need types unconditionally though
262     }
263
264   // If it's a type, make sure that all subtypes of the type are included...
265   if (const Type *TheTy = dyn_cast<Type>(D)) {
266
267     // Insert the current type before any subtypes.  This is important because
268     // recursive types elements are inserted in a bottom up order.  Changing
269     // this here can break things.  For example:
270     //
271     //    global { \2 * } { { \2 }* null }
272     //
273     int ResultSlot = doInsertValue(TheTy);
274     SC_DEBUG("  Inserted type: " << TheTy->getDescription() << " slot=" <<
275              ResultSlot << "\n");
276
277     // Loop over any contained types in the definition... in depth first order.
278     //
279     for (df_iterator<const Type*> I = df_begin(TheTy), E = df_end(TheTy);
280          I != E; ++I)
281       if (*I != TheTy) {
282         // If we haven't seen this sub type before, add it to our type table!
283         const Type *SubTy = *I;
284         if (getSlot(SubTy) == -1) {
285           SC_DEBUG("  Inserting subtype: " << SubTy->getDescription() << "\n");
286           int Slot = doInsertValue(SubTy);
287           SC_DEBUG("  Inserted subtype: " << SubTy->getDescription() << 
288                    " slot=" << Slot << "\n");
289         }
290       }
291     return ResultSlot;
292   }
293
294   // Okay, everything is happy, actually insert the silly value now...
295   return doInsertValue(D);
296 }
297
298
299 // doInsertValue - This is a small helper function to be called only
300 // be insertValue.
301 //
302 int SlotCalculator::doInsertValue(const Value *D) {
303   const Type *Typ = D->getType();
304   unsigned Ty;
305
306   // Used for debugging DefSlot=-1 assertion...
307   //if (Typ == Type::TypeTy)
308   //  cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
309
310   if (Typ->isDerivedType()) {
311     int ValSlot = getSlot(Typ);
312     if (ValSlot == -1) {                // Have we already entered this type?
313       // Nope, this is the first we have seen the type, process it.
314       ValSlot = insertValue(Typ, true);
315       assert(ValSlot != -1 && "ProcessType returned -1 for a type?");
316     }
317     Ty = (unsigned)ValSlot;
318   } else {
319     Ty = Typ->getPrimitiveID();
320   }
321   
322   if (Table.size() <= Ty)    // Make sure we have the type plane allocated...
323     Table.resize(Ty+1, TypePlane());
324
325   // If this is the first value to get inserted into the type plane, make sure
326   // to insert the implicit null value...
327   if (Table[Ty].empty() && Ty >= Type::FirstDerivedTyID && !IgnoreNamedNodes) {
328     Value *ZeroInitializer = Constant::getNullValue(Typ);
329
330     // If we are pushing zeroinit, it will be handled below.
331     if (D != ZeroInitializer) {
332       Table[Ty].push_back(ZeroInitializer);
333       NodeMap[ZeroInitializer] = 0;
334     }
335   }
336
337   // Insert node into table and NodeMap...
338   unsigned DestSlot = NodeMap[D] = Table[Ty].size();
339   Table[Ty].push_back(D);
340
341   SC_DEBUG("  Inserting value [" << Ty << "] = " << D << " slot=" << 
342            DestSlot << " [");
343   // G = Global, C = Constant, T = Type, F = Function, o = other
344   SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" : 
345            (isa<Type>(D) ? "T" : (isa<Function>(D) ? "F" : "o")))));
346   SC_DEBUG("]\n");
347   return (int)DestSlot;
348 }