1 //===-- SlotCalculator.cpp - Calculate what slots values land in ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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).
13 // This is used when writing a file to disk, either in bytecode or assembly.
15 //===----------------------------------------------------------------------===//
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"
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
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
65 SlotCalculator::SlotCalculator(const Module *M) {
73 // processModule - Process all of the module level function declarations and
74 // types that are available.
76 void SlotCalculator::processModule() {
77 SC_DEBUG("begin processModule!\n");
79 // Add all of the global variables to the value table...
81 for (Module::const_global_iterator I = TheModule->global_begin(),
82 E = TheModule->global_end(); I != E; ++I)
83 CreateSlotIfNeeded(I);
85 // Scavenge the types out of the functions, then add the functions themselves
86 // to the value table...
88 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
90 CreateSlotIfNeeded(I);
92 // Add all of the module level constants used as initializers
94 for (Module::const_global_iterator I = TheModule->global_begin(),
95 E = TheModule->global_end(); I != E; ++I)
96 if (I->hasInitializer())
97 CreateSlotIfNeeded(I->getInitializer());
99 // Now that all global constants have been added, rearrange constant planes
100 // that contain constant strings so that the strings occur at the start of the
101 // plane, not somewhere in the middle.
103 for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
104 if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
105 if (AT->getElementType() == Type::Int8Ty) {
106 TypePlane &Plane = Table[plane];
107 unsigned FirstNonStringID = 0;
108 for (unsigned i = 0, e = Plane.size(); i != e; ++i)
109 if (isa<ConstantAggregateZero>(Plane[i]) ||
110 (isa<ConstantArray>(Plane[i]) &&
111 cast<ConstantArray>(Plane[i])->isString())) {
112 // Check to see if we have to shuffle this string around. If not,
113 // don't do anything.
114 if (i != FirstNonStringID) {
115 // Swap the plane entries....
116 std::swap(Plane[i], Plane[FirstNonStringID]);
118 // Keep the NodeMap up to date.
119 NodeMap[Plane[i]] = i;
120 NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
127 // Scan all of the functions for their constants, which allows us to emit
128 // more compact modules.
129 SC_DEBUG("Inserting function constants:\n");
130 for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
132 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
133 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
134 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
136 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
138 CreateSlotIfNeeded(*OI);
140 getOrCreateTypeSlot(I->getType());
144 // Insert constants that are named at module level into the slot pool so that
145 // the module symbol table can refer to them...
146 SC_DEBUG("Inserting SymbolTable values:\n");
147 processTypeSymbolTable(&TheModule->getTypeSymbolTable());
148 processValueSymbolTable(&TheModule->getValueSymbolTable());
150 // Now that we have collected together all of the information relevant to the
151 // module, compactify the type table if it is particularly big and outputting
152 // a bytecode file. The basic problem we run into is that some programs have
153 // a large number of types, which causes the type field to overflow its size,
154 // which causes instructions to explode in size (particularly call
155 // instructions). To avoid this behavior, we "sort" the type table so that
156 // all non-value types are pushed to the end of the type table, giving nice
157 // low numbers to the types that can be used by instructions, thus reducing
158 // the amount of explodage we suffer.
159 if (Types.size() >= 64) {
160 unsigned FirstNonValueTypeID = 0;
161 for (unsigned i = 0, e = Types.size(); i != e; ++i)
162 if (Types[i]->isFirstClassType() || Types[i]->isPrimitiveType()) {
163 // Check to see if we have to shuffle this type around. If not, don't
165 if (i != FirstNonValueTypeID) {
166 // Swap the type ID's.
167 std::swap(Types[i], Types[FirstNonValueTypeID]);
169 // Keep the TypeMap up to date.
170 TypeMap[Types[i]] = i;
171 TypeMap[Types[FirstNonValueTypeID]] = FirstNonValueTypeID;
173 // When we move a type, make sure to move its value plane as needed.
174 if (Table.size() > FirstNonValueTypeID) {
175 if (Table.size() <= i) Table.resize(i+1);
176 std::swap(Table[i], Table[FirstNonValueTypeID]);
179 ++FirstNonValueTypeID;
183 NumModuleTypes = getNumPlanes();
185 SC_DEBUG("end processModule!\n");
188 // processTypeSymbolTable - Insert all of the type sin the specified symbol
190 void SlotCalculator::processTypeSymbolTable(const TypeSymbolTable *TST) {
191 for (TypeSymbolTable::const_iterator TI = TST->begin(), TE = TST->end();
193 getOrCreateTypeSlot(TI->second);
196 // processSymbolTable - Insert all of the values in the specified symbol table
197 // into the values table...
199 void SlotCalculator::processValueSymbolTable(const ValueSymbolTable *VST) {
200 for (ValueSymbolTable::const_iterator VI = VST->begin(), VE = VST->end();
202 CreateSlotIfNeeded(VI->getValue());
205 void SlotCalculator::CreateSlotIfNeeded(const Value *V) {
206 // Check to see if it's already in!
207 if (NodeMap.count(V)) return;
209 const Type *Ty = V->getType();
210 assert(Ty != Type::VoidTy && "Can't insert void values!");
212 if (const Constant *C = dyn_cast<Constant>(V)) {
213 if (isa<GlobalValue>(C)) {
214 // Initializers for globals are handled explicitly elsewhere.
215 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
216 // Do not index the characters that make up constant strings. We emit
217 // constant strings as special entities that don't require their
218 // individual characters to be emitted.
219 if (!C->isNullValue())
220 ConstantStrings.push_back(cast<ConstantArray>(C));
222 // This makes sure that if a constant has uses (for example an array of
223 // const ints), that they are inserted also.
224 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
226 CreateSlotIfNeeded(*I);
230 unsigned TyPlane = getOrCreateTypeSlot(Ty);
231 if (Table.size() <= TyPlane) // Make sure we have the type plane allocated.
232 Table.resize(TyPlane+1, TypePlane());
234 // If this is the first value to get inserted into the type plane, make sure
235 // to insert the implicit null value.
236 if (Table[TyPlane].empty()) {
237 // Label's and opaque types can't have a null value.
238 if (Ty != Type::LabelTy && !isa<OpaqueType>(Ty)) {
239 Value *ZeroInitializer = Constant::getNullValue(Ty);
241 // If we are pushing zeroinit, it will be handled below.
242 if (V != ZeroInitializer) {
243 Table[TyPlane].push_back(ZeroInitializer);
244 NodeMap[ZeroInitializer] = 0;
249 // Insert node into table and NodeMap...
250 NodeMap[V] = Table[TyPlane].size();
251 Table[TyPlane].push_back(V);
253 SC_DEBUG(" Inserting value [" << TyPlane << "] = " << *V << " slot=" <<
258 unsigned SlotCalculator::getOrCreateTypeSlot(const Type *Ty) {
259 TypeMapType::iterator TyIt = TypeMap.find(Ty);
260 if (TyIt != TypeMap.end()) return TyIt->second;
262 // Insert into TypeMap.
263 unsigned ResultSlot = TypeMap[Ty] = Types.size();
265 SC_DEBUG(" Inserting type [" << ResultSlot << "] = " << *Ty << "\n" );
267 // Loop over any contained types in the definition, ensuring they are also
269 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
271 getOrCreateTypeSlot(*I);
278 void SlotCalculator::incorporateFunction(const Function *F) {
279 SC_DEBUG("begin processFunction!\n");
281 // Iterate over function arguments, adding them to the value table...
282 for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
284 CreateFunctionValueSlot(I);
286 SC_DEBUG("Inserting Instructions:\n");
288 // Add all of the instructions to the type planes...
289 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
290 CreateFunctionValueSlot(BB);
291 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
292 if (I->getType() != Type::VoidTy)
293 CreateFunctionValueSlot(I);
297 SC_DEBUG("end processFunction!\n");
300 void SlotCalculator::purgeFunction() {
301 SC_DEBUG("begin purgeFunction!\n");
303 // Next, remove values from existing type planes
304 for (DenseMap<unsigned,unsigned,
305 ModuleLevelDenseMapKeyInfo>::iterator I = ModuleLevel.begin(),
306 E = ModuleLevel.end(); I != E; ++I) {
307 unsigned PlaneNo = I->first;
308 unsigned ModuleLev = I->second;
310 // Pop all function-local values in this type-plane off of Table.
311 TypePlane &Plane = getPlane(PlaneNo);
312 assert(ModuleLev < Plane.size() && "module levels higher than elements?");
313 for (unsigned i = ModuleLev, e = Plane.size(); i != e; ++i) {
314 NodeMap.erase(Plane.back()); // Erase from nodemap
315 Plane.pop_back(); // Shrink plane
321 // Finally, remove any type planes defined by the function...
322 while (Table.size() > NumModuleTypes) {
323 TypePlane &Plane = Table.back();
324 SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
325 << Plane.size() << "\n");
326 for (unsigned i = 0, e = Plane.size(); i != e; ++i)
327 NodeMap.erase(Plane[i]); // Erase from nodemap
329 Table.pop_back(); // Nuke the plane, we don't like it.
332 SC_DEBUG("end purgeFunction!\n");
335 void SlotCalculator::CreateFunctionValueSlot(const Value *V) {
336 assert(!NodeMap.count(V) && "Function-local value can't be inserted!");
338 const Type *Ty = V->getType();
339 assert(Ty != Type::VoidTy && "Can't insert void values!");
340 assert(!isa<Constant>(V) && "Not a function-local value!");
342 unsigned TyPlane = getOrCreateTypeSlot(Ty);
343 if (Table.size() <= TyPlane) // Make sure we have the type plane allocated.
344 Table.resize(TyPlane+1, TypePlane());
346 // If this is the first value noticed of this type within this function,
347 // remember the module level for this type plane in ModuleLevel. This reminds
348 // us to remove the values in purgeFunction and tells us how many to remove.
349 if (TyPlane < NumModuleTypes)
350 ModuleLevel.insert(std::make_pair(TyPlane, Table[TyPlane].size()));
352 // If this is the first value to get inserted into the type plane, make sure
353 // to insert the implicit null value.
354 if (Table[TyPlane].empty()) {
355 // Label's and opaque types can't have a null value.
356 if (Ty != Type::LabelTy && !isa<OpaqueType>(Ty)) {
357 Value *ZeroInitializer = Constant::getNullValue(Ty);
359 // If we are pushing zeroinit, it will be handled below.
360 if (V != ZeroInitializer) {
361 Table[TyPlane].push_back(ZeroInitializer);
362 NodeMap[ZeroInitializer] = 0;
367 // Insert node into table and NodeMap...
368 NodeMap[V] = Table[TyPlane].size();
369 Table[TyPlane].push_back(V);
371 SC_DEBUG(" Inserting value [" << TyPlane << "] = " << *V << " slot=" <<