Implement review feedback. Aliasees can be either GlobalValue's or
[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/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/TypeSymbolTable.h"
25 #include "llvm/Type.h"
26 #include "llvm/ValueSymbolTable.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include <algorithm>
29 #include <functional>
30 using namespace llvm;
31
32 #ifndef NDEBUG
33 #include "llvm/Support/Streams.h"
34 #include "llvm/Support/CommandLine.h"
35 static cl::opt<bool> SlotCalculatorDebugOption("scdebug",cl::init(false), 
36     cl::desc("Enable SlotCalculator debug output"), cl::Hidden);
37 #define SC_DEBUG(X) if (SlotCalculatorDebugOption) cerr << X
38 #else
39 #define SC_DEBUG(X)
40 #endif
41
42 void SlotCalculator::insertPrimitives() {
43   // Preload the table with the built-in types. These built-in types are
44   // inserted first to ensure that they have low integer indices which helps to
45   // keep bytecode sizes small. Note that the first group of indices must match
46   // the Type::TypeIDs for the primitive types. After that the integer types are
47   // added, but the order and value is not critical. What is critical is that 
48   // the indices of these "well known" slot numbers be properly maintained in
49   // Reader.h which uses them directly to extract values of these types.
50   SC_DEBUG("Inserting primitive types:\n");
51                                     // See WellKnownTypeSlots in Reader.h
52   getOrCreateTypeSlot(Type::VoidTy  ); // 0: VoidTySlot
53   getOrCreateTypeSlot(Type::FloatTy ); // 1: FloatTySlot
54   getOrCreateTypeSlot(Type::DoubleTy); // 2: DoubleTySlot
55   getOrCreateTypeSlot(Type::LabelTy ); // 3: LabelTySlot
56   assert(TypeMap.size() == Type::FirstDerivedTyID &&"Invalid primitive insert");
57   // Above here *must* correspond 1:1 with the primitive types.
58   getOrCreateTypeSlot(Type::Int1Ty  ); // 4: Int1TySlot
59   getOrCreateTypeSlot(Type::Int8Ty  ); // 5: Int8TySlot
60   getOrCreateTypeSlot(Type::Int16Ty ); // 6: Int16TySlot
61   getOrCreateTypeSlot(Type::Int32Ty ); // 7: Int32TySlot
62   getOrCreateTypeSlot(Type::Int64Ty ); // 8: Int64TySlot
63 }
64
65 SlotCalculator::SlotCalculator(const Module *M) {
66   assert(M);
67   TheModule = M;
68
69   insertPrimitives();
70   processModule();
71 }
72
73 // processModule - Process all of the module level function declarations and
74 // types that are available.
75 //
76 void SlotCalculator::processModule() {
77   SC_DEBUG("begin processModule!\n");
78
79   // Add all of the global variables to the value table...
80   //
81   for (Module::const_global_iterator I = TheModule->global_begin(),
82          E = TheModule->global_end(); I != E; ++I)
83     CreateSlotIfNeeded(I);
84
85   // Scavenge the types out of the functions, then add the functions themselves
86   // to the value table...
87   //
88   for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
89        I != E; ++I)
90     CreateSlotIfNeeded(I);
91
92   // Add all of the global aliases to the value table...
93   //
94   for (Module::const_alias_iterator I = TheModule->alias_begin(),
95          E = TheModule->alias_end(); I != E; ++I)
96     CreateSlotIfNeeded(I);
97
98   // Add all of the module level constants used as initializers
99   //
100   for (Module::const_global_iterator I = TheModule->global_begin(),
101          E = TheModule->global_end(); I != E; ++I)
102     if (I->hasInitializer())
103       CreateSlotIfNeeded(I->getInitializer());
104
105   // Add all of the module level constants used as aliasees
106   //
107   for (Module::const_alias_iterator I = TheModule->alias_begin(),
108          E = TheModule->alias_end(); I != E; ++I)
109     if (I->getAliasee())
110       CreateSlotIfNeeded(I->getAliasee());
111
112   // Now that all global constants have been added, rearrange constant planes
113   // that contain constant strings so that the strings occur at the start of the
114   // plane, not somewhere in the middle.
115   //
116   for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
117     if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
118       if (AT->getElementType() == Type::Int8Ty) {
119         TypePlane &Plane = Table[plane];
120         unsigned FirstNonStringID = 0;
121         for (unsigned i = 0, e = Plane.size(); i != e; ++i)
122           if (isa<ConstantAggregateZero>(Plane[i]) ||
123               (isa<ConstantArray>(Plane[i]) &&
124                cast<ConstantArray>(Plane[i])->isString())) {
125             // Check to see if we have to shuffle this string around.  If not,
126             // don't do anything.
127             if (i != FirstNonStringID) {
128               // Swap the plane entries....
129               std::swap(Plane[i], Plane[FirstNonStringID]);
130
131               // Keep the NodeMap up to date.
132               NodeMap[Plane[i]] = i;
133               NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
134             }
135             ++FirstNonStringID;
136           }
137       }
138   }
139
140   // Scan all of the functions for their constants, which allows us to emit
141   // more compact modules.
142   SC_DEBUG("Inserting function constants:\n");
143   for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
144        F != E; ++F) {
145     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
146       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
147         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
148              OI != E; ++OI) {
149           if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
150               isa<InlineAsm>(*OI))
151             CreateSlotIfNeeded(*OI);
152         }
153         getOrCreateTypeSlot(I->getType());
154       }
155   }
156
157   // Insert constants that are named at module level into the slot pool so that
158   // the module symbol table can refer to them...
159   SC_DEBUG("Inserting SymbolTable values:\n");
160   processTypeSymbolTable(&TheModule->getTypeSymbolTable());
161   processValueSymbolTable(&TheModule->getValueSymbolTable());
162
163   // Now that we have collected together all of the information relevant to the
164   // module, compactify the type table if it is particularly big and outputting
165   // a bytecode file.  The basic problem we run into is that some programs have
166   // a large number of types, which causes the type field to overflow its size,
167   // which causes instructions to explode in size (particularly call
168   // instructions).  To avoid this behavior, we "sort" the type table so that
169   // all non-value types are pushed to the end of the type table, giving nice
170   // low numbers to the types that can be used by instructions, thus reducing
171   // the amount of explodage we suffer.
172   if (Types.size() >= 64) {
173     unsigned FirstNonValueTypeID = 0;
174     for (unsigned i = 0, e = Types.size(); i != e; ++i)
175       if (Types[i]->isFirstClassType() || Types[i]->isPrimitiveType()) {
176         // Check to see if we have to shuffle this type around.  If not, don't
177         // do anything.
178         if (i != FirstNonValueTypeID) {
179           // Swap the type ID's.
180           std::swap(Types[i], Types[FirstNonValueTypeID]);
181
182           // Keep the TypeMap up to date.
183           TypeMap[Types[i]] = i;
184           TypeMap[Types[FirstNonValueTypeID]] = FirstNonValueTypeID;
185
186           // When we move a type, make sure to move its value plane as needed.
187           if (Table.size() > FirstNonValueTypeID) {
188             if (Table.size() <= i) Table.resize(i+1);
189             std::swap(Table[i], Table[FirstNonValueTypeID]);
190           }
191         }
192         ++FirstNonValueTypeID;
193       }
194   }
195     
196   NumModuleTypes = getNumPlanes();
197
198   SC_DEBUG("end processModule!\n");
199 }
200
201 // processTypeSymbolTable - Insert all of the type sin the specified symbol
202 // table.
203 void SlotCalculator::processTypeSymbolTable(const TypeSymbolTable *TST) {
204   for (TypeSymbolTable::const_iterator TI = TST->begin(), TE = TST->end(); 
205        TI != TE; ++TI )
206     getOrCreateTypeSlot(TI->second);
207 }
208
209 // processSymbolTable - Insert all of the values in the specified symbol table
210 // into the values table...
211 //
212 void SlotCalculator::processValueSymbolTable(const ValueSymbolTable *VST) {
213   for (ValueSymbolTable::const_iterator VI = VST->begin(), VE = VST->end(); 
214        VI != VE; ++VI)
215     CreateSlotIfNeeded(VI->getValue());
216 }
217
218 void SlotCalculator::CreateSlotIfNeeded(const Value *V) {
219   // Check to see if it's already in!
220   if (NodeMap.count(V)) return;
221
222   const Type *Ty = V->getType();
223   assert(Ty != Type::VoidTy && "Can't insert void values!");
224   
225   if (const Constant *C = dyn_cast<Constant>(V)) {
226     if (isa<GlobalValue>(C)) {
227       // Initializers for globals are handled explicitly elsewhere.
228     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
229       // Do not index the characters that make up constant strings.  We emit
230       // constant strings as special entities that don't require their
231       // individual characters to be emitted.
232       if (!C->isNullValue())
233         ConstantStrings.push_back(cast<ConstantArray>(C));
234     } else {
235       // This makes sure that if a constant has uses (for example an array of
236       // const ints), that they are inserted also.
237       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
238            I != E; ++I)
239         CreateSlotIfNeeded(*I);
240     }
241   }
242
243   unsigned TyPlane = getOrCreateTypeSlot(Ty);
244   if (Table.size() <= TyPlane)    // Make sure we have the type plane allocated.
245     Table.resize(TyPlane+1, TypePlane());
246   
247   // If this is the first value to get inserted into the type plane, make sure
248   // to insert the implicit null value.
249   if (Table[TyPlane].empty()) {
250     // Label's and opaque types can't have a null value.
251     if (Ty != Type::LabelTy && !isa<OpaqueType>(Ty)) {
252       Value *ZeroInitializer = Constant::getNullValue(Ty);
253       
254       // If we are pushing zeroinit, it will be handled below.
255       if (V != ZeroInitializer) {
256         Table[TyPlane].push_back(ZeroInitializer);
257         NodeMap[ZeroInitializer] = 0;
258       }
259     }
260   }
261   
262   // Insert node into table and NodeMap...
263   NodeMap[V] = Table[TyPlane].size();
264   Table[TyPlane].push_back(V);
265   
266   SC_DEBUG("  Inserting value [" << TyPlane << "] = " << *V << " slot=" <<
267            NodeMap[V] << "\n");
268 }
269
270
271 unsigned SlotCalculator::getOrCreateTypeSlot(const Type *Ty) {
272   TypeMapType::iterator TyIt = TypeMap.find(Ty);
273   if (TyIt != TypeMap.end()) return TyIt->second;
274
275   // Insert into TypeMap.
276   unsigned ResultSlot = TypeMap[Ty] = Types.size();
277   Types.push_back(Ty);
278   SC_DEBUG("  Inserting type [" << ResultSlot << "] = " << *Ty << "\n" );
279   
280   // Loop over any contained types in the definition, ensuring they are also
281   // inserted.
282   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
283        I != E; ++I)
284     getOrCreateTypeSlot(*I);
285
286   return ResultSlot;
287 }
288
289
290
291 void SlotCalculator::incorporateFunction(const Function *F) {
292   SC_DEBUG("begin processFunction!\n");
293   
294   // Iterate over function arguments, adding them to the value table...
295   for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
296       I != E; ++I)
297     CreateFunctionValueSlot(I);
298   
299   SC_DEBUG("Inserting Instructions:\n");
300   
301   // Add all of the instructions to the type planes...
302   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
303     CreateFunctionValueSlot(BB);
304     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
305       if (I->getType() != Type::VoidTy)
306         CreateFunctionValueSlot(I);
307     }
308   }
309   
310   SC_DEBUG("end processFunction!\n");
311 }
312
313 void SlotCalculator::purgeFunction() {
314   SC_DEBUG("begin purgeFunction!\n");
315   
316   // Next, remove values from existing type planes
317   for (DenseMap<unsigned,unsigned,
318           ModuleLevelDenseMapKeyInfo>::iterator I = ModuleLevel.begin(),
319        E = ModuleLevel.end(); I != E; ++I) {
320     unsigned PlaneNo = I->first;
321     unsigned ModuleLev = I->second;
322     
323     // Pop all function-local values in this type-plane off of Table.
324     TypePlane &Plane = getPlane(PlaneNo);
325     assert(ModuleLev < Plane.size() && "module levels higher than elements?");
326     for (unsigned i = ModuleLev, e = Plane.size(); i != e; ++i) {
327       NodeMap.erase(Plane.back());       // Erase from nodemap
328       Plane.pop_back();                  // Shrink plane
329     }
330   }
331
332   ModuleLevel.clear();
333
334   // Finally, remove any type planes defined by the function...
335   while (Table.size() > NumModuleTypes) {
336     TypePlane &Plane = Table.back();
337     SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
338              << Plane.size() << "\n");
339     for (unsigned i = 0, e = Plane.size(); i != e; ++i)
340       NodeMap.erase(Plane[i]);   // Erase from nodemap
341     
342     Table.pop_back();                // Nuke the plane, we don't like it.
343   }
344   
345   SC_DEBUG("end purgeFunction!\n");
346 }
347
348 inline static bool hasImplicitNull(const Type* Ty) {
349   return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
350 }
351
352 void SlotCalculator::CreateFunctionValueSlot(const Value *V) {
353   assert(!NodeMap.count(V) && "Function-local value can't be inserted!");
354   
355   const Type *Ty = V->getType();
356   assert(Ty != Type::VoidTy && "Can't insert void values!");
357   assert(!isa<Constant>(V) && "Not a function-local value!");
358   
359   unsigned TyPlane = getOrCreateTypeSlot(Ty);
360   if (Table.size() <= TyPlane)    // Make sure we have the type plane allocated.
361     Table.resize(TyPlane+1, TypePlane());
362   
363   // If this is the first value noticed of this type within this function,
364   // remember the module level for this type plane in ModuleLevel.  This reminds
365   // us to remove the values in purgeFunction and tells us how many to remove.
366   if (TyPlane < NumModuleTypes)
367     ModuleLevel.insert(std::make_pair(TyPlane, Table[TyPlane].size()));
368   
369   // If this is the first value to get inserted into the type plane, make sure
370   // to insert the implicit null value.
371   if (Table[TyPlane].empty()) {
372     // Label's and opaque types can't have a null value.
373     if (hasImplicitNull(Ty)) {
374       Value *ZeroInitializer = Constant::getNullValue(Ty);
375       
376       // If we are pushing zeroinit, it will be handled below.
377       if (V != ZeroInitializer) {
378         Table[TyPlane].push_back(ZeroInitializer);
379         NodeMap[ZeroInitializer] = 0;
380       }
381     }
382   }
383   
384   // Insert node into table and NodeMap...
385   NodeMap[V] = Table[TyPlane].size();
386   Table[TyPlane].push_back(V);
387   
388   SC_DEBUG("  Inserting value [" << TyPlane << "] = " << *V << " slot=" <<
389            NodeMap[V] << "\n");
390