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