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