Be a bit more efficient when processing the active and inactive
[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 slots
11 // values in a program will land in (keeping track of per plane information).
12 //
13 // This is used when writing a file to disk, either in bytecode or assembly.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "SlotCalculator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/SymbolTable.h"
24 #include "llvm/Type.h"
25 #include "llvm/Analysis/ConstantsScanner.h"
26 #include "Support/PostOrderIterator.h"
27 #include "Support/STLExtras.h"
28 #include <algorithm>
29 #include <functional>
30
31 using namespace llvm;
32
33 #if 0
34 #include <iostream>
35 #define SC_DEBUG(X) std::cerr << X
36 #else
37 #define SC_DEBUG(X)
38 #endif
39
40 SlotCalculator::SlotCalculator(const Module *M ) {
41   ModuleContainsAllFunctionConstants = false;
42   ModuleTypeLevel = 0;
43   TheModule = M;
44
45   // Preload table... Make sure that all of the primitive types are in the table
46   // and that their Primitive ID is equal to their slot #
47   //
48   SC_DEBUG("Inserting primitive types:\n");
49   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
50     assert(Type::getPrimitiveType((Type::TypeID)i));
51     insertType(Type::getPrimitiveType((Type::TypeID)i), true);
52   }
53
54   if (M == 0) return;   // Empty table...
55   processModule();
56 }
57
58 SlotCalculator::SlotCalculator(const Function *M ) {
59   ModuleContainsAllFunctionConstants = false;
60   TheModule = M ? M->getParent() : 0;
61
62   // Preload table... Make sure that all of the primitive types are in the table
63   // and that their Primitive ID is equal to their slot #
64   //
65   SC_DEBUG("Inserting primitive types:\n");
66   for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
67     assert(Type::getPrimitiveType((Type::TypeID)i));
68     insertType(Type::getPrimitiveType((Type::TypeID)i), true);
69   }
70
71   if (TheModule == 0) return;   // Empty table...
72
73   processModule();              // Process module level stuff
74   incorporateFunction(M);       // Start out in incorporated state
75 }
76
77 unsigned SlotCalculator::getGlobalSlot(const Value *V) const {
78   assert(!CompactionTable.empty() &&
79          "This method can only be used when compaction is enabled!");
80   std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
81   assert(I != NodeMap.end() && "Didn't find global slot entry!");
82   return I->second;
83 }
84
85 unsigned SlotCalculator::getGlobalSlot(const Type* T) const {
86   std::map<const Type*, unsigned>::const_iterator I = TypeMap.find(T);
87   assert(I != TypeMap.end() && "Didn't find global slot entry!");
88   return I->second;
89 }
90
91 SlotCalculator::TypePlane &SlotCalculator::getPlane(unsigned Plane) {
92   if (CompactionTable.empty()) {                // No compaction table active?
93     // fall out
94   } else if (!CompactionTable[Plane].empty()) { // Compaction table active.
95     assert(Plane < CompactionTable.size());
96     return CompactionTable[Plane];
97   } else {
98     // Final case: compaction table active, but this plane is not
99     // compactified.  If the type plane is compactified, unmap back to the
100     // global type plane corresponding to "Plane".
101     if (!CompactionTypes.empty()) {
102       const Type *Ty = CompactionTypes[Plane];
103       TypeMapType::iterator It = TypeMap.find(Ty);
104       assert(It != TypeMap.end() && "Type not in global constant map?");
105       Plane = It->second;
106     }
107   }
108
109   // Okay we are just returning an entry out of the main Table.  Make sure the
110   // plane exists and return it.
111   if (Plane >= Table.size())
112     Table.resize(Plane+1);
113   return Table[Plane];
114 }
115
116 // processModule - Process all of the module level function declarations and
117 // types that are available.
118 //
119 void SlotCalculator::processModule() {
120   SC_DEBUG("begin processModule!\n");
121
122   // Add all of the global variables to the value table...
123   //
124   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
125        I != E; ++I)
126     getOrCreateSlot(I);
127
128   // Scavenge the types out of the functions, then add the functions themselves
129   // to the value table...
130   //
131   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
132        I != E; ++I)
133     getOrCreateSlot(I);
134
135   // Add all of the module level constants used as initializers
136   //
137   for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
138        I != E; ++I)
139     if (I->hasInitializer())
140       getOrCreateSlot(I->getInitializer());
141
142   // Now that all global constants have been added, rearrange constant planes
143   // that contain constant strings so that the strings occur at the start of the
144   // plane, not somewhere in the middle.
145   //
146   for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
147     if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
148       if (AT->getElementType() == Type::SByteTy ||
149           AT->getElementType() == Type::UByteTy) {
150         TypePlane &Plane = Table[plane];
151         unsigned FirstNonStringID = 0;
152         for (unsigned i = 0, e = Plane.size(); i != e; ++i)
153           if (isa<ConstantAggregateZero>(Plane[i]) ||
154               cast<ConstantArray>(Plane[i])->isString()) {
155             // Check to see if we have to shuffle this string around.  If not,
156             // don't do anything.
157             if (i != FirstNonStringID) {
158               // Swap the plane entries....
159               std::swap(Plane[i], Plane[FirstNonStringID]);
160               
161               // Keep the NodeMap up to date.
162               NodeMap[Plane[i]] = i;
163               NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
164             }
165             ++FirstNonStringID;
166           }
167       }
168   }
169   
170   // Scan all of the functions for their constants, which allows us to emit 
171   // more compact modules.  This is optional, and is just used to compactify 
172   // the constants used by different functions together.
173   //
174   // This functionality tends to produce smaller bytecode files.  This should 
175   // not be used in the future by clients that want to, for example, build and 
176   // emit functions on the fly.  For now, however, it is unconditionally 
177   // enabled.
178   ModuleContainsAllFunctionConstants = true;
179
180   SC_DEBUG("Inserting function constants:\n");
181   for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
182        F != E; ++F) {
183     for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I){
184       for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
185         if (isa<Constant>(I->getOperand(op)) && 
186             !isa<GlobalValue>(I->getOperand(op)))
187           getOrCreateSlot(I->getOperand(op));
188       getOrCreateSlot(I->getType());
189       if (const VANextInst *VAN = dyn_cast<VANextInst>(&*I))
190         getOrCreateSlot(VAN->getArgType());
191     }
192     processSymbolTableConstants(&F->getSymbolTable());
193   }
194
195   // Insert constants that are named at module level into the slot pool so that
196   // the module symbol table can refer to them...
197   SC_DEBUG("Inserting SymbolTable values:\n");
198   processSymbolTable(&TheModule->getSymbolTable());
199
200   // Now that we have collected together all of the information relevant to the
201   // module, compactify the type table if it is particularly big and outputting
202   // a bytecode file.  The basic problem we run into is that some programs have
203   // a large number of types, which causes the type field to overflow its size,
204   // which causes instructions to explode in size (particularly call
205   // instructions).  To avoid this behavior, we "sort" the type table so that
206   // all non-value types are pushed to the end of the type table, giving nice
207   // low numbers to the types that can be used by instructions, thus reducing
208   // the amount of explodage we suffer.
209   if (Types.size() >= 64) {
210     unsigned FirstNonValueTypeID = 0;
211     for (unsigned i = 0, e = Types.size(); i != e; ++i)
212       if (Types[i]->isFirstClassType() || Types[i]->isPrimitiveType()) {
213         // Check to see if we have to shuffle this type around.  If not, don't
214         // do anything.
215         if (i != FirstNonValueTypeID) {
216           // Swap the type ID's.
217           std::swap(Types[i], Types[FirstNonValueTypeID]);
218
219           // Keep the TypeMap up to date.
220           TypeMap[Types[i]] = i;
221           TypeMap[Types[FirstNonValueTypeID]] = FirstNonValueTypeID;
222
223           // When we move a type, make sure to move its value plane as needed.
224           if (Table.size() > FirstNonValueTypeID) {
225             if (Table.size() <= i) Table.resize(i+1);
226             std::swap(Table[i], Table[FirstNonValueTypeID]);
227           }
228         }
229         ++FirstNonValueTypeID;
230       }
231   }
232
233   SC_DEBUG("end processModule!\n");
234 }
235
236 // processSymbolTable - Insert all of the values in the specified symbol table
237 // into the values table...
238 //
239 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
240   // Do the types first.
241   for (SymbolTable::type_const_iterator TI = ST->type_begin(),
242        TE = ST->type_end(); TI != TE; ++TI )
243     getOrCreateSlot(TI->second);
244
245   // Now do the values.
246   for (SymbolTable::plane_const_iterator PI = ST->plane_begin(), 
247        PE = ST->plane_end(); PI != PE; ++PI)
248     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
249            VE = PI->second.end(); VI != VE; ++VI)
250       getOrCreateSlot(VI->second);
251 }
252
253 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
254   // Do the types first
255   for (SymbolTable::type_const_iterator TI = ST->type_begin(),
256        TE = ST->type_end(); TI != TE; ++TI )
257     getOrCreateSlot(TI->second);
258
259   // Now do the constant values in all planes
260   for (SymbolTable::plane_const_iterator PI = ST->plane_begin(), 
261        PE = ST->plane_end(); PI != PE; ++PI)
262     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
263            VE = PI->second.end(); VI != VE; ++VI)
264       if (isa<Constant>(VI->second) &&
265           !isa<GlobalValue>(VI->second))
266         getOrCreateSlot(VI->second);
267 }
268
269
270 void SlotCalculator::incorporateFunction(const Function *F) {
271   assert((ModuleLevel.size() == 0 ||
272           ModuleTypeLevel == 0) && "Module already incorporated!");
273
274   SC_DEBUG("begin processFunction!\n");
275
276   // If we emitted all of the function constants, build a compaction table.
277   if ( ModuleContainsAllFunctionConstants)
278     buildCompactionTable(F);
279
280   // Update the ModuleLevel entries to be accurate.
281   ModuleLevel.resize(getNumPlanes());
282   for (unsigned i = 0, e = getNumPlanes(); i != e; ++i)
283     ModuleLevel[i] = getPlane(i).size();
284   ModuleTypeLevel = Types.size();
285
286   // Iterate over function arguments, adding them to the value table...
287   for(Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
288     getOrCreateSlot(I);
289
290   if ( !ModuleContainsAllFunctionConstants ) {
291     // Iterate over all of the instructions in the function, looking for
292     // constant values that are referenced.  Add these to the value pools
293     // before any nonconstant values.  This will be turned into the constant
294     // pool for the bytecode writer.
295     //
296     
297     // Emit all of the constants that are being used by the instructions in
298     // the function...
299     constant_iterator CI = constant_begin(F);
300     constant_iterator CE = constant_end(F);
301     while ( CI != CE ) {
302       this->getOrCreateSlot(*CI);
303       ++CI;
304     }
305     
306     // If there is a symbol table, it is possible that the user has names for
307     // constants that are not being used.  In this case, we will have problems
308     // if we don't emit the constants now, because otherwise we will get 
309     // symbol table references to constants not in the output.  Scan for these
310     // constants now.
311     //
312     processSymbolTableConstants(&F->getSymbolTable());
313   }
314
315   SC_DEBUG("Inserting Instructions:\n");
316
317   // Add all of the instructions to the type planes...
318   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
319     getOrCreateSlot(BB);
320     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
321       getOrCreateSlot(I);
322       if (const VANextInst *VAN = dyn_cast<VANextInst>(I))
323         getOrCreateSlot(VAN->getArgType());
324     }
325   }
326
327   // If we are building a compaction table, prune out planes that do not benefit
328   // from being compactified.
329   if (!CompactionTable.empty())
330     pruneCompactionTable();
331
332   SC_DEBUG("end processFunction!\n");
333 }
334
335 void SlotCalculator::purgeFunction() {
336   assert((ModuleLevel.size() != 0 ||
337           ModuleTypeLevel != 0) && "Module not incorporated!");
338   unsigned NumModuleTypes = ModuleLevel.size();
339
340   SC_DEBUG("begin purgeFunction!\n");
341
342   // First, free the compaction map if used.
343   CompactionNodeMap.clear();
344   CompactionTypeMap.clear();
345
346   // Next, remove values from existing type planes
347   for (unsigned i = 0; i != NumModuleTypes; ++i) {
348     // Size of plane before function came
349     unsigned ModuleLev = getModuleLevel(i);
350     assert(int(ModuleLev) >= 0 && "BAD!");
351
352     TypePlane &Plane = getPlane(i);
353
354     assert(ModuleLev <= Plane.size() && "module levels higher than elements?");
355     while (Plane.size() != ModuleLev) {
356       assert(!isa<GlobalValue>(Plane.back()) &&
357              "Functions cannot define globals!");
358       NodeMap.erase(Plane.back());       // Erase from nodemap
359       Plane.pop_back();                  // Shrink plane
360     }
361   }
362
363   // We don't need this state anymore, free it up.
364   ModuleLevel.clear();
365   ModuleTypeLevel = 0;
366
367   // Finally, remove any type planes defined by the function...
368   CompactionTypes.clear();
369   if (!CompactionTable.empty()) {
370     CompactionTable.clear();
371   } else {
372     while (Table.size() > NumModuleTypes) {
373       TypePlane &Plane = Table.back();
374       SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
375                << Plane.size() << "\n");
376       while (Plane.size()) {
377         assert(!isa<GlobalValue>(Plane.back()) &&
378                "Functions cannot define globals!");
379         NodeMap.erase(Plane.back());   // Erase from nodemap
380         Plane.pop_back();              // Shrink plane
381       }
382       
383       Table.pop_back();                // Nuke the plane, we don't like it.
384     }
385   }
386
387   SC_DEBUG("end purgeFunction!\n");
388 }
389
390 static inline bool hasNullValue(unsigned TyID) {
391   return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
392 }
393
394 /// getOrCreateCompactionTableSlot - This method is used to build up the initial
395 /// approximation of the compaction table.
396 unsigned SlotCalculator::getOrCreateCompactionTableSlot(const Value *V) {
397   std::map<const Value*, unsigned>::iterator I =
398     CompactionNodeMap.lower_bound(V);
399   if (I != CompactionNodeMap.end() && I->first == V)
400     return I->second;  // Already exists?
401
402   // Make sure the type is in the table.
403   unsigned Ty;
404   if (!CompactionTypes.empty())
405     Ty = getOrCreateCompactionTableSlot(V->getType());
406   else    // If the type plane was decompactified, use the global plane ID
407     Ty = getSlot(V->getType());
408   if (CompactionTable.size() <= Ty)
409     CompactionTable.resize(Ty+1);
410
411   TypePlane &TyPlane = CompactionTable[Ty];
412
413   // Make sure to insert the null entry if the thing we are inserting is not a
414   // null constant.
415   if (TyPlane.empty() && hasNullValue(V->getType()->getTypeID())) {
416     Value *ZeroInitializer = Constant::getNullValue(V->getType());
417     if (V != ZeroInitializer) {
418       TyPlane.push_back(ZeroInitializer);
419       CompactionNodeMap[ZeroInitializer] = 0;
420     }
421   }
422
423   unsigned SlotNo = TyPlane.size();
424   TyPlane.push_back(V);
425   CompactionNodeMap.insert(std::make_pair(V, SlotNo));
426   return SlotNo;
427 }
428
429 /// getOrCreateCompactionTableSlot - This method is used to build up the initial
430 /// approximation of the compaction table.
431 unsigned SlotCalculator::getOrCreateCompactionTableSlot(const Type *T) {
432   std::map<const Type*, unsigned>::iterator I =
433     CompactionTypeMap.lower_bound(T);
434   if (I != CompactionTypeMap.end() && I->first == T)
435     return I->second;  // Already exists?
436
437   unsigned SlotNo = CompactionTypes.size();
438   SC_DEBUG("Inserting Compaction Type #" << SlotNo << ": " << T << "\n");
439   CompactionTypes.push_back(T);
440   CompactionTypeMap.insert(std::make_pair(T, SlotNo));
441   return SlotNo;
442 }
443
444 /// buildCompactionTable - Since all of the function constants and types are
445 /// stored in the module-level constant table, we don't need to emit a function
446 /// constant table.  Also due to this, the indices for various constants and
447 /// types might be very large in large programs.  In order to avoid blowing up
448 /// the size of instructions in the bytecode encoding, we build a compaction
449 /// table, which defines a mapping from function-local identifiers to global
450 /// identifiers.
451 void SlotCalculator::buildCompactionTable(const Function *F) {
452   assert(CompactionNodeMap.empty() && "Compaction table already built!");
453   assert(CompactionTypeMap.empty() && "Compaction types already built!");
454   // First step, insert the primitive types.
455   CompactionTable.resize(Type::LastPrimitiveTyID+1);
456   for (unsigned i = 0; i <= Type::LastPrimitiveTyID; ++i) {
457     const Type *PrimTy = Type::getPrimitiveType((Type::TypeID)i);
458     CompactionTypes.push_back(PrimTy);
459     CompactionTypeMap[PrimTy] = i;
460   }
461
462   // Next, include any types used by function arguments.
463   for (Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
464     getOrCreateCompactionTableSlot(I->getType());
465
466   // Next, find all of the types and values that are referred to by the
467   // instructions in the function.
468   for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
469     getOrCreateCompactionTableSlot(I->getType());
470     for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
471       if (isa<Constant>(I->getOperand(op)))
472         getOrCreateCompactionTableSlot(I->getOperand(op));
473     if (const VANextInst *VAN = dyn_cast<VANextInst>(&*I))
474       getOrCreateCompactionTableSlot(VAN->getArgType());
475   }
476
477   // Do the types in the symbol table
478   const SymbolTable &ST = F->getSymbolTable();
479   for (SymbolTable::type_const_iterator TI = ST.type_begin(),
480        TE = ST.type_end(); TI != TE; ++TI)
481     getOrCreateCompactionTableSlot(TI->second);
482
483   // Now do the constants and global values
484   for (SymbolTable::plane_const_iterator PI = ST.plane_begin(), 
485        PE = ST.plane_end(); PI != PE; ++PI)
486     for (SymbolTable::value_const_iterator VI = PI->second.begin(),
487            VE = PI->second.end(); VI != VE; ++VI)
488       if (isa<Constant>(VI->second) && !isa<GlobalValue>(VI->second))
489         getOrCreateCompactionTableSlot(VI->second);
490
491   // Now that we have all of the values in the table, and know what types are
492   // referenced, make sure that there is at least the zero initializer in any
493   // used type plane.  Since the type was used, we will be emitting instructions
494   // to the plane even if there are no constants in it.
495   CompactionTable.resize(CompactionTypes.size());
496   for (unsigned i = 0, e = CompactionTable.size(); i != e; ++i)
497     if (CompactionTable[i].empty() && (i != Type::VoidTyID) &&
498         i != Type::LabelTyID) {
499       const Type *Ty = CompactionTypes[i];
500       SC_DEBUG("Getting Null Value #" << i << " for Type " << Ty << "\n");
501       assert(Ty->getTypeID() != Type::VoidTyID);
502       assert(Ty->getTypeID() != Type::LabelTyID);
503       getOrCreateCompactionTableSlot(Constant::getNullValue(Ty));
504     }
505   
506   // Okay, now at this point, we have a legal compaction table.  Since we want
507   // to emit the smallest possible binaries, do not compactify the type plane if
508   // it will not save us anything.  Because we have not yet incorporated the
509   // function body itself yet, we don't know whether or not it's a good idea to
510   // compactify other planes.  We will defer this decision until later.
511   TypeList &GlobalTypes = Types;
512   
513   // All of the values types will be scrunched to the start of the types plane
514   // of the global table.  Figure out just how many there are.
515   assert(!GlobalTypes.empty() && "No global types???");
516   unsigned NumFCTypes = GlobalTypes.size()-1;
517   while (!GlobalTypes[NumFCTypes]->isFirstClassType())
518     --NumFCTypes;
519
520   // If there are fewer that 64 types, no instructions will be exploded due to
521   // the size of the type operands.  Thus there is no need to compactify types.
522   // Also, if the compaction table contains most of the entries in the global
523   // table, there really is no reason to compactify either.
524   if (NumFCTypes < 64) {
525     // Decompactifying types is tricky, because we have to move type planes all
526     // over the place.  At least we don't need to worry about updating the
527     // CompactionNodeMap for non-types though.
528     std::vector<TypePlane> TmpCompactionTable;
529     std::swap(CompactionTable, TmpCompactionTable);
530     TypeList TmpTypes;
531     std::swap(TmpTypes, CompactionTypes);
532     
533     // Move each plane back over to the uncompactified plane
534     while (!TmpTypes.empty()) {
535       const Type *Ty = TmpTypes.back();
536       TmpTypes.pop_back();
537       CompactionTypeMap.erase(Ty);  // Decompactify type!
538
539       // Find the global slot number for this type.
540       int TySlot = getSlot(Ty);
541       assert(TySlot != -1 && "Type doesn't exist in global table?");
542       
543       // Now we know where to put the compaction table plane.
544       if (CompactionTable.size() <= unsigned(TySlot))
545         CompactionTable.resize(TySlot+1);
546       // Move the plane back into the compaction table.
547       std::swap(CompactionTable[TySlot], TmpCompactionTable[TmpTypes.size()]);
548
549       // And remove the empty plane we just moved in.
550       TmpCompactionTable.pop_back();
551     }
552   }
553 }
554
555
556 /// pruneCompactionTable - Once the entire function being processed has been
557 /// incorporated into the current compaction table, look over the compaction
558 /// table and check to see if there are any values whose compaction will not
559 /// save us any space in the bytecode file.  If compactifying these values
560 /// serves no purpose, then we might as well not even emit the compactification
561 /// information to the bytecode file, saving a bit more space.
562 ///
563 /// Note that the type plane has already been compactified if possible.
564 ///
565 void SlotCalculator::pruneCompactionTable() {
566   TypeList &TyPlane = CompactionTypes;
567   for (unsigned ctp = 0, e = CompactionTable.size(); ctp != e; ++ctp)
568     if (!CompactionTable[ctp].empty()) {
569       TypePlane &CPlane = CompactionTable[ctp];
570       unsigned GlobalSlot = ctp;
571       if (!TyPlane.empty())
572         GlobalSlot = getGlobalSlot(TyPlane[ctp]);
573
574       if (GlobalSlot >= Table.size())
575         Table.resize(GlobalSlot+1);
576       TypePlane &GPlane = Table[GlobalSlot];
577       
578       unsigned ModLevel = getModuleLevel(ctp);
579       unsigned NumFunctionObjs = CPlane.size()-ModLevel;
580
581       // If the maximum index required if all entries in this plane were merged
582       // into the global plane is less than 64, go ahead and eliminate the
583       // plane.
584       bool PrunePlane = GPlane.size() + NumFunctionObjs < 64;
585
586       // If there are no function-local values defined, and the maximum
587       // referenced global entry is less than 64, we don't need to compactify.
588       if (!PrunePlane && NumFunctionObjs == 0) {
589         unsigned MaxIdx = 0;
590         for (unsigned i = 0; i != ModLevel; ++i) {
591           unsigned Idx = NodeMap[CPlane[i]];
592           if (Idx > MaxIdx) MaxIdx = Idx;
593         }
594         PrunePlane = MaxIdx < 64;
595       }
596
597       // Ok, finally, if we decided to prune this plane out of the compaction
598       // table, do so now.
599       if (PrunePlane) {
600         TypePlane OldPlane;
601         std::swap(OldPlane, CPlane);
602
603         // Loop over the function local objects, relocating them to the global
604         // table plane.
605         for (unsigned i = ModLevel, e = OldPlane.size(); i != e; ++i) {
606           const Value *V = OldPlane[i];
607           CompactionNodeMap.erase(V);
608           assert(NodeMap.count(V) == 0 && "Value already in table??");
609           getOrCreateSlot(V);
610         }
611
612         // For compactified global values, just remove them from the compaction
613         // node map.
614         for (unsigned i = 0; i != ModLevel; ++i)
615           CompactionNodeMap.erase(OldPlane[i]);
616
617         // Update the new modulelevel for this plane.
618         assert(ctp < ModuleLevel.size() && "Cannot set modulelevel!");
619         ModuleLevel[ctp] = GPlane.size()-NumFunctionObjs;
620         assert((int)ModuleLevel[ctp] >= 0 && "Bad computation!");
621       }
622     }
623 }
624
625 /// Determine if the compaction table is actually empty. Because the
626 /// compaction table always includes the primitive type planes, we 
627 /// can't just check getCompactionTable().size() because it will never
628 /// be zero. Furthermore, the ModuleLevel factors into whether a given
629 /// plane is empty or not. This function does the necessary computation
630 /// to determine if its actually empty.
631 bool SlotCalculator::CompactionTableIsEmpty() const {
632   // Check a degenerate case, just in case.
633   if (CompactionTable.size() == 0) return true;
634
635   // Check each plane
636   for (unsigned i = 0, e = CompactionTable.size(); i < e; ++i) {
637     // If the plane is not empty
638     if (!CompactionTable[i].empty()) {
639       // If the module level is non-zero then at least the
640       // first element of the plane is valid and therefore not empty.
641       unsigned End = getModuleLevel(i);
642       if (End != 0) 
643         return false;
644     }
645   }
646   // All the compaction table planes are empty so the table is
647   // considered empty too.
648   return true;
649 }
650
651 int SlotCalculator::getSlot(const Value *V) const {
652   // If there is a CompactionTable active...
653   if (!CompactionNodeMap.empty()) {
654     std::map<const Value*, unsigned>::const_iterator I =
655       CompactionNodeMap.find(V);
656     if (I != CompactionNodeMap.end())
657       return (int)I->second;
658     // Otherwise, if it's not in the compaction table, it must be in a
659     // non-compactified plane.
660   }
661
662   std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
663   if (I != NodeMap.end())
664     return (int)I->second;
665
666   return -1;
667 }
668
669 int SlotCalculator::getSlot(const Type*T) const {
670   // If there is a CompactionTable active...
671   if (!CompactionTypeMap.empty()) {
672     std::map<const Type*, unsigned>::const_iterator I =
673       CompactionTypeMap.find(T);
674     if (I != CompactionTypeMap.end())
675       return (int)I->second;
676     // Otherwise, if it's not in the compaction table, it must be in a
677     // non-compactified plane.
678   }
679
680   std::map<const Type*, unsigned>::const_iterator I = TypeMap.find(T);
681   if (I != TypeMap.end())
682     return (int)I->second;
683
684   return -1;
685 }
686
687 int SlotCalculator::getOrCreateSlot(const Value *V) {
688   if (V->getType() == Type::VoidTy) return -1;
689
690   int SlotNo = getSlot(V);        // Check to see if it's already in!
691   if (SlotNo != -1) return SlotNo;
692
693   if (!isa<GlobalValue>(V))  // Initializers for globals are handled explicitly
694     if (const Constant *C = dyn_cast<Constant>(V)) {
695       assert(CompactionNodeMap.empty() &&
696              "All needed constants should be in the compaction map already!");
697
698       // Do not index the characters that make up constant strings.  We emit 
699       // constant strings as special entities that don't require their 
700       // individual characters to be emitted.
701       if (!isa<ConstantArray>(C) || !cast<ConstantArray>(C)->isString()) {
702         // This makes sure that if a constant has uses (for example an array of
703         // const ints), that they are inserted also.
704         //
705         for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
706              I != E; ++I)
707           getOrCreateSlot(*I);
708       } else {
709         assert(ModuleLevel.empty() &&
710                "How can a constant string be directly accessed in a function?");
711         // Otherwise, if we are emitting a bytecode file and this IS a string,
712         // remember it.
713         if (!C->isNullValue())
714           ConstantStrings.push_back(cast<ConstantArray>(C));
715       }
716     }
717
718   return insertValue(V);
719 }
720
721 int SlotCalculator::getOrCreateSlot(const Type* T) {
722   int SlotNo = getSlot(T);        // Check to see if it's already in!
723   if (SlotNo != -1) return SlotNo;
724   return insertType(T);
725 }
726
727 int SlotCalculator::insertValue(const Value *D, bool dontIgnore) {
728   assert(D && "Can't insert a null value!");
729   assert(getSlot(D) == -1 && "Value is already in the table!");
730
731   // If we are building a compaction map, and if this plane is being compacted,
732   // insert the value into the compaction map, not into the global map.
733   if (!CompactionNodeMap.empty()) {
734     if (D->getType() == Type::VoidTy) return -1;  // Do not insert void values
735     assert(!isa<Constant>(D) &&
736            "Types, constants, and globals should be in global table!");
737
738     int Plane = getSlot(D->getType());
739     assert(Plane != -1 && CompactionTable.size() > (unsigned)Plane &&
740            "Didn't find value type!");
741     if (!CompactionTable[Plane].empty())
742       return getOrCreateCompactionTableSlot(D);
743   }
744
745   // If this node does not contribute to a plane, or if the node has a 
746   // name and we don't want names, then ignore the silly node... Note that types
747   // do need slot numbers so that we can keep track of where other values land.
748   //
749   if (!dontIgnore)                               // Don't ignore nonignorables!
750     if (D->getType() == Type::VoidTy ) {         // Ignore void type nodes
751       SC_DEBUG("ignored value " << *D << "\n");
752       return -1;                  // We do need types unconditionally though
753     }
754
755   // Okay, everything is happy, actually insert the silly value now...
756   return doInsertValue(D);
757 }
758
759 int SlotCalculator::insertType(const Type *Ty, bool dontIgnore) {
760   assert(Ty && "Can't insert a null type!");
761   assert(getSlot(Ty) == -1 && "Type is already in the table!");
762
763   // If we are building a compaction map, and if this plane is being compacted,
764   // insert the value into the compaction map, not into the global map.
765   if (!CompactionTypeMap.empty()) {
766     getOrCreateCompactionTableSlot(Ty);
767   }
768
769   // Insert the current type before any subtypes.  This is important because
770   // recursive types elements are inserted in a bottom up order.  Changing
771   // this here can break things.  For example:
772   //
773   //    global { \2 * } { { \2 }* null }
774   //
775   int ResultSlot = doInsertType(Ty);
776   SC_DEBUG("  Inserted type: " << Ty->getDescription() << " slot=" <<
777            ResultSlot << "\n");
778
779   // Loop over any contained types in the definition... in post
780   // order.
781   for (po_iterator<const Type*> I = po_begin(Ty), E = po_end(Ty);
782        I != E; ++I) {
783     if (*I != Ty) {
784       const Type *SubTy = *I;
785       // If we haven't seen this sub type before, add it to our type table!
786       if (getSlot(SubTy) == -1) {
787         SC_DEBUG("  Inserting subtype: " << SubTy->getDescription() << "\n");
788         doInsertType(SubTy);
789         SC_DEBUG("  Inserted subtype: " << SubTy->getDescription() << "\n");
790       }
791     }
792   }
793   return ResultSlot;
794 }
795
796 // doInsertValue - This is a small helper function to be called only
797 // be insertValue.
798 //
799 int SlotCalculator::doInsertValue(const Value *D) {
800   const Type *Typ = D->getType();
801   unsigned Ty;
802
803   // Used for debugging DefSlot=-1 assertion...
804   //if (Typ == Type::TypeTy)
805   //  cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
806
807   if (Typ->isDerivedType()) {
808     int ValSlot;
809     if (CompactionTable.empty())
810       ValSlot = getSlot(Typ);
811     else
812       ValSlot = getGlobalSlot(Typ);
813     if (ValSlot == -1) {                // Have we already entered this type?
814       // Nope, this is the first we have seen the type, process it.
815       ValSlot = insertType(Typ, true);
816       assert(ValSlot != -1 && "ProcessType returned -1 for a type?");
817     }
818     Ty = (unsigned)ValSlot;
819   } else {
820     Ty = Typ->getTypeID();
821   }
822   
823   if (Table.size() <= Ty)    // Make sure we have the type plane allocated...
824     Table.resize(Ty+1, TypePlane());
825
826   // If this is the first value to get inserted into the type plane, make sure
827   // to insert the implicit null value...
828   if (Table[Ty].empty() &&  hasNullValue(Ty)) {
829     Value *ZeroInitializer = Constant::getNullValue(Typ);
830
831     // If we are pushing zeroinit, it will be handled below.
832     if (D != ZeroInitializer) {
833       Table[Ty].push_back(ZeroInitializer);
834       NodeMap[ZeroInitializer] = 0;
835     }
836   }
837
838   // Insert node into table and NodeMap...
839   unsigned DestSlot = NodeMap[D] = Table[Ty].size();
840   Table[Ty].push_back(D);
841
842   SC_DEBUG("  Inserting value [" << Ty << "] = " << D << " slot=" << 
843            DestSlot << " [");
844   // G = Global, C = Constant, T = Type, F = Function, o = other
845   SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" : 
846            (isa<Function>(D) ? "F" : "o"))));
847   SC_DEBUG("]\n");
848   return (int)DestSlot;
849 }
850
851 // doInsertType - This is a small helper function to be called only
852 // be insertType.
853 //
854 int SlotCalculator::doInsertType(const Type *Ty) {
855
856   // Insert node into table and NodeMap...
857   unsigned DestSlot = TypeMap[Ty] = Types.size();
858   Types.push_back(Ty);
859
860   SC_DEBUG("  Inserting type [" << DestSlot << "] = " << Ty << "\n" );
861   return (int)DestSlot;
862 }
863
864 // vim: sw=2 ai