Check in two changes:
[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 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 #if 0
101   // FIXME: Empirically, this causes the bytecode files to get BIGGER, because
102   // it explodes the operand size numbers to be bigger than can be handled
103   // compactly, which offsets the ~40% savings in constant sizes.  Whoops.
104
105   // If we are emitting a bytecode file, scan all of the functions for their
106   // constants, which allows us to emit more compact modules.  This is optional,
107   // and is just used to compactify the constants used by different functions
108   // together.
109   if (!IgnoreNamedNodes) {
110     SC_DEBUG("Inserting function constants:\n");
111     for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
112          F != E; ++F)
113       for_each(constant_begin(F), constant_end(F),
114                bind_obj(this, &SlotCalculator::getOrCreateSlot));
115   }
116 #endif
117
118   // Insert constants that are named at module level into the slot pool so that
119   // the module symbol table can refer to them...
120   //
121   if (!IgnoreNamedNodes) {
122     SC_DEBUG("Inserting SymbolTable values:\n");
123     processSymbolTable(&TheModule->getSymbolTable());
124   }
125
126   // Now that we have collected together all of the information relevant to the
127   // module, compactify the type table if it is particularly big and outputting
128   // a bytecode file.  The basic problem we run into is that some programs have
129   // a large number of types, which causes the type field to overflow its size,
130   // which causes instructions to explode in size (particularly call
131   // instructions).  To avoid this behavior, we "sort" the type table so that
132   // all non-value types are pushed to the end of the type table, giving nice
133   // low numbers to the types that can be used by instructions, thus reducing
134   // the amount of explodage we suffer.
135   if (!IgnoreNamedNodes && Table[Type::TypeTyID].size() >= 64) {
136     // Scan through the type table moving value types to the start of the table.
137     TypePlane &Types = Table[Type::TypeTyID];
138     unsigned FirstNonValueTypeID = 0;
139     for (unsigned i = 0, e = Types.size(); i != e; ++i)
140       if (cast<Type>(Types[i])->isFirstClassType() ||
141           cast<Type>(Types[i])->isPrimitiveType()) {
142         // Check to see if we have to shuffle this type around.  If not, don't
143         // do anything.
144         if (i != FirstNonValueTypeID) {
145           // Swap the type ID's.
146           std::swap(Types[i], Types[FirstNonValueTypeID]);
147
148           // Keep the NodeMap up to date.
149           std::swap(NodeMap[Types[i]], NodeMap[Types[FirstNonValueTypeID]]);
150
151           // When we move a type, make sure to move its value plane as needed.
152           std::swap(Table[i], Table[FirstNonValueTypeID]);
153         }
154         ++FirstNonValueTypeID;
155       }
156   }
157
158   SC_DEBUG("end processModule!\n");
159 }
160
161 // processSymbolTable - Insert all of the values in the specified symbol table
162 // into the values table...
163 //
164 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
165   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
166     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
167            TE = I->second.end(); TI != TE; ++TI)
168       getOrCreateSlot(TI->second);
169 }
170
171 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
172   for (SymbolTable::const_iterator I = ST->begin(), E = ST->end(); I != E; ++I)
173     for (SymbolTable::type_const_iterator TI = I->second.begin(), 
174            TE = I->second.end(); TI != TE; ++TI)
175       if (isa<Constant>(TI->second))
176         getOrCreateSlot(TI->second);
177 }
178
179
180 void SlotCalculator::incorporateFunction(const Function *F) {
181   assert(ModuleLevel.size() == 0 && "Module already incorporated!");
182
183   SC_DEBUG("begin processFunction!\n");
184
185   // Save the Table state before we process the function...
186   for (unsigned i = 0; i < Table.size(); ++i)
187     ModuleLevel.push_back(Table[i].size());
188
189   SC_DEBUG("Inserting function arguments\n");
190
191   // Iterate over function arguments, adding them to the value table...
192   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
193     getOrCreateSlot(I);
194
195   // Iterate over all of the instructions in the function, looking for constant
196   // values that are referenced.  Add these to the value pools before any
197   // nonconstant values.  This will be turned into the constant pool for the
198   // bytecode writer.
199   //
200   if (!IgnoreNamedNodes) {                // Assembly writer does not need this!
201     SC_DEBUG("Inserting function constants:\n";
202              for (constant_iterator I = constant_begin(F), E = constant_end(F);
203                   I != E; ++I) {
204                std::cerr << "  " << *I->getType() << " " << *I << "\n";
205              });
206
207     // Emit all of the constants that are being used by the instructions in the
208     // function...
209     for_each(constant_begin(F), constant_end(F),
210              bind_obj(this, &SlotCalculator::getOrCreateSlot));
211
212     // If there is a symbol table, it is possible that the user has names for
213     // constants that are not being used.  In this case, we will have problems
214     // if we don't emit the constants now, because otherwise we will get 
215     // symbol table references to constants not in the output.  Scan for these
216     // constants now.
217     //
218     processSymbolTableConstants(&F->getSymbolTable());
219   }
220
221   SC_DEBUG("Inserting Labels:\n");
222
223   // Iterate over basic blocks, adding them to the value table...
224   for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
225     getOrCreateSlot(I);
226
227   SC_DEBUG("Inserting Instructions:\n");
228
229   // Add all of the instructions to the type planes...
230   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
231     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
232       getOrCreateSlot(I);
233       if (const VANextInst *VAN = dyn_cast<VANextInst>(I))
234         getOrCreateSlot(VAN->getArgType());
235     }
236
237   if (!IgnoreNamedNodes) {
238     SC_DEBUG("Inserting SymbolTable values:\n");
239     processSymbolTable(&F->getSymbolTable());
240   }
241
242   SC_DEBUG("end processFunction!\n");
243 }
244
245 void SlotCalculator::purgeFunction() {
246   assert(ModuleLevel.size() != 0 && "Module not incorporated!");
247   unsigned NumModuleTypes = ModuleLevel.size();
248
249   SC_DEBUG("begin purgeFunction!\n");
250
251   // First, remove values from existing type planes
252   for (unsigned i = 0; i < NumModuleTypes; ++i) {
253     unsigned ModuleSize = ModuleLevel[i];  // Size of plane before function came
254     TypePlane &CurPlane = Table[i];
255     //SC_DEBUG("Processing Plane " <<i<< " of size " << CurPlane.size() <<"\n");
256              
257     while (CurPlane.size() != ModuleSize) {
258       //SC_DEBUG("  Removing [" << i << "] Value=" << CurPlane.back() << "\n");
259       std::map<const Value *, unsigned>::iterator NI =
260         NodeMap.find(CurPlane.back());
261       assert(NI != NodeMap.end() && "Node not in nodemap?");
262       NodeMap.erase(NI);   // Erase from nodemap
263       CurPlane.pop_back();                            // Shrink plane
264     }
265   }
266
267   // We don't need this state anymore, free it up.
268   ModuleLevel.clear();
269
270   // Next, remove any type planes defined by the function...
271   while (NumModuleTypes != Table.size()) {
272     TypePlane &Plane = Table.back();
273     SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
274              << Plane.size() << "\n");
275     while (Plane.size()) {
276       NodeMap.erase(NodeMap.find(Plane.back()));   // Erase from nodemap
277       Plane.pop_back();                            // Shrink plane
278     }
279
280     Table.pop_back();                      // Nuke the plane, we don't like it.
281   }
282
283   SC_DEBUG("end purgeFunction!\n");
284 }
285
286 int SlotCalculator::getSlot(const Value *D) const {
287   std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(D);
288   if (I == NodeMap.end()) return -1;
289  
290   return (int)I->second;
291 }
292
293
294 int SlotCalculator::getOrCreateSlot(const Value *V) {
295   int SlotNo = getSlot(V);        // Check to see if it's already in!
296   if (SlotNo != -1) return SlotNo;
297
298   if (!isa<GlobalValue>(V))
299     if (const Constant *C = dyn_cast<Constant>(V)) {
300       // This makes sure that if a constant has uses (for example an array of
301       // const ints), that they are inserted also.
302       //
303       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
304            I != E; ++I)
305         getOrCreateSlot(*I);
306     }
307
308   return insertValue(V);
309 }
310
311
312 int SlotCalculator::insertValue(const Value *D, bool dontIgnore) {
313   assert(D && "Can't insert a null value!");
314   assert(getSlot(D) == -1 && "Value is already in the table!");
315
316   // If this node does not contribute to a plane, or if the node has a 
317   // name and we don't want names, then ignore the silly node... Note that types
318   // do need slot numbers so that we can keep track of where other values land.
319   //
320   if (!dontIgnore)                               // Don't ignore nonignorables!
321     if (D->getType() == Type::VoidTy ||          // Ignore void type nodes
322         (IgnoreNamedNodes &&                     // Ignore named and constants
323          (D->hasName() || isa<Constant>(D)) && !isa<Type>(D))) {
324       SC_DEBUG("ignored value " << *D << "\n");
325       return -1;                  // We do need types unconditionally though
326     }
327
328   // If it's a type, make sure that all subtypes of the type are included...
329   if (const Type *TheTy = dyn_cast<Type>(D)) {
330
331     // Insert the current type before any subtypes.  This is important because
332     // recursive types elements are inserted in a bottom up order.  Changing
333     // this here can break things.  For example:
334     //
335     //    global { \2 * } { { \2 }* null }
336     //
337     int ResultSlot = doInsertValue(TheTy);
338     SC_DEBUG("  Inserted type: " << TheTy->getDescription() << " slot=" <<
339              ResultSlot << "\n");
340
341     // Loop over any contained types in the definition... in post
342     // order.
343     //
344     for (po_iterator<const Type*> I = po_begin(TheTy), E = po_end(TheTy);
345          I != E; ++I) {
346       if (*I != TheTy) {
347         const Type *SubTy = *I;
348         // If we haven't seen this sub type before, add it to our type table!
349         if (getSlot(SubTy) == -1) {
350           SC_DEBUG("  Inserting subtype: " << SubTy->getDescription() << "\n");
351           int Slot = doInsertValue(SubTy);
352           SC_DEBUG("  Inserted subtype: " << SubTy->getDescription() << 
353                    " slot=" << Slot << "\n");
354         }
355       }
356     }
357     return ResultSlot;
358   }
359
360   // Okay, everything is happy, actually insert the silly value now...
361   return doInsertValue(D);
362 }
363
364
365 // doInsertValue - This is a small helper function to be called only
366 // be insertValue.
367 //
368 int SlotCalculator::doInsertValue(const Value *D) {
369   const Type *Typ = D->getType();
370   unsigned Ty;
371
372   // Used for debugging DefSlot=-1 assertion...
373   //if (Typ == Type::TypeTy)
374   //  cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
375
376   if (Typ->isDerivedType()) {
377     int ValSlot = getSlot(Typ);
378     if (ValSlot == -1) {                // Have we already entered this type?
379       // Nope, this is the first we have seen the type, process it.
380       ValSlot = insertValue(Typ, true);
381       assert(ValSlot != -1 && "ProcessType returned -1 for a type?");
382     }
383     Ty = (unsigned)ValSlot;
384   } else {
385     Ty = Typ->getPrimitiveID();
386   }
387   
388   if (Table.size() <= Ty)    // Make sure we have the type plane allocated...
389     Table.resize(Ty+1, TypePlane());
390
391   // If this is the first value to get inserted into the type plane, make sure
392   // to insert the implicit null value...
393   if (Table[Ty].empty() && Ty >= Type::FirstDerivedTyID && !IgnoreNamedNodes) {
394     Value *ZeroInitializer = Constant::getNullValue(Typ);
395
396     // If we are pushing zeroinit, it will be handled below.
397     if (D != ZeroInitializer) {
398       Table[Ty].push_back(ZeroInitializer);
399       NodeMap[ZeroInitializer] = 0;
400     }
401   }
402
403   // Insert node into table and NodeMap...
404   unsigned DestSlot = NodeMap[D] = Table[Ty].size();
405   Table[Ty].push_back(D);
406
407   SC_DEBUG("  Inserting value [" << Ty << "] = " << D << " slot=" << 
408            DestSlot << " [");
409   // G = Global, C = Constant, T = Type, F = Function, o = other
410   SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" : 
411            (isa<Type>(D) ? "T" : (isa<Function>(D) ? "F" : "o")))));
412   SC_DEBUG("]\n");
413   return (int)DestSlot;
414 }