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