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