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/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 "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/ADT/STLExtras.h"
35 #define SC_DEBUG(X) std::cerr << X
40 SlotCalculator::SlotCalculator(const Module *M ) {
41 ModuleContainsAllFunctionConstants = false;
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 #
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);
54 if (M == 0) return; // Empty table...
58 SlotCalculator::SlotCalculator(const Function *M ) {
59 ModuleContainsAllFunctionConstants = false;
60 TheModule = M ? M->getParent() : 0;
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 #
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);
71 if (TheModule == 0) return; // Empty table...
73 processModule(); // Process module level stuff
74 incorporateFunction(M); // Start out in incorporated state
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!");
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!");
91 SlotCalculator::TypePlane &SlotCalculator::getPlane(unsigned Plane) {
92 if (CompactionTable.empty()) { // No compaction table active?
94 } else if (!CompactionTable[Plane].empty()) { // Compaction table active.
95 assert(Plane < CompactionTable.size());
96 return CompactionTable[Plane];
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?");
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);
116 // processModule - Process all of the module level function declarations and
117 // types that are available.
119 void SlotCalculator::processModule() {
120 SC_DEBUG("begin processModule!\n");
122 // Add all of the global variables to the value table...
124 for (Module::const_global_iterator I = TheModule->global_begin(),
125 E = TheModule->global_end(); I != E; ++I)
128 // Scavenge the types out of the functions, then add the functions themselves
129 // to the value table...
131 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
135 // Add all of the module level constants used as initializers
137 for (Module::const_global_iterator I = TheModule->global_begin(),
138 E = TheModule->global_end(); I != E; ++I)
139 if (I->hasInitializer())
140 getOrCreateSlot(I->getInitializer());
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.
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 (isa<ConstantArray>(Plane[i]) &&
155 cast<ConstantArray>(Plane[i])->isString())) {
156 // Check to see if we have to shuffle this string around. If not,
157 // don't do anything.
158 if (i != FirstNonStringID) {
159 // Swap the plane entries....
160 std::swap(Plane[i], Plane[FirstNonStringID]);
162 // Keep the NodeMap up to date.
163 NodeMap[Plane[i]] = i;
164 NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
171 // Scan all of the functions for their constants, which allows us to emit
172 // more compact modules. This is optional, and is just used to compactify
173 // the constants used by different functions together.
175 // This functionality tends to produce smaller bytecode files. This should
176 // not be used in the future by clients that want to, for example, build and
177 // emit functions on the fly. For now, however, it is unconditionally
179 ModuleContainsAllFunctionConstants = true;
181 SC_DEBUG("Inserting function constants:\n");
182 for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
184 for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I){
185 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
186 if (isa<Constant>(I->getOperand(op)) &&
187 !isa<GlobalValue>(I->getOperand(op)))
188 getOrCreateSlot(I->getOperand(op));
189 getOrCreateSlot(I->getType());
191 processSymbolTableConstants(&F->getSymbolTable());
194 // Insert constants that are named at module level into the slot pool so that
195 // the module symbol table can refer to them...
196 SC_DEBUG("Inserting SymbolTable values:\n");
197 processSymbolTable(&TheModule->getSymbolTable());
199 // Now that we have collected together all of the information relevant to the
200 // module, compactify the type table if it is particularly big and outputting
201 // a bytecode file. The basic problem we run into is that some programs have
202 // a large number of types, which causes the type field to overflow its size,
203 // which causes instructions to explode in size (particularly call
204 // instructions). To avoid this behavior, we "sort" the type table so that
205 // all non-value types are pushed to the end of the type table, giving nice
206 // low numbers to the types that can be used by instructions, thus reducing
207 // the amount of explodage we suffer.
208 if (Types.size() >= 64) {
209 unsigned FirstNonValueTypeID = 0;
210 for (unsigned i = 0, e = Types.size(); i != e; ++i)
211 if (Types[i]->isFirstClassType() || Types[i]->isPrimitiveType()) {
212 // Check to see if we have to shuffle this type around. If not, don't
214 if (i != FirstNonValueTypeID) {
215 // Swap the type ID's.
216 std::swap(Types[i], Types[FirstNonValueTypeID]);
218 // Keep the TypeMap up to date.
219 TypeMap[Types[i]] = i;
220 TypeMap[Types[FirstNonValueTypeID]] = FirstNonValueTypeID;
222 // When we move a type, make sure to move its value plane as needed.
223 if (Table.size() > FirstNonValueTypeID) {
224 if (Table.size() <= i) Table.resize(i+1);
225 std::swap(Table[i], Table[FirstNonValueTypeID]);
228 ++FirstNonValueTypeID;
232 SC_DEBUG("end processModule!\n");
235 // processSymbolTable - Insert all of the values in the specified symbol table
236 // into the values table...
238 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
239 // Do the types first.
240 for (SymbolTable::type_const_iterator TI = ST->type_begin(),
241 TE = ST->type_end(); TI != TE; ++TI )
242 getOrCreateSlot(TI->second);
244 // Now do the values.
245 for (SymbolTable::plane_const_iterator PI = ST->plane_begin(),
246 PE = ST->plane_end(); PI != PE; ++PI)
247 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
248 VE = PI->second.end(); VI != VE; ++VI)
249 getOrCreateSlot(VI->second);
252 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
253 // Do the types first
254 for (SymbolTable::type_const_iterator TI = ST->type_begin(),
255 TE = ST->type_end(); TI != TE; ++TI )
256 getOrCreateSlot(TI->second);
258 // Now do the constant values in all planes
259 for (SymbolTable::plane_const_iterator PI = ST->plane_begin(),
260 PE = ST->plane_end(); PI != PE; ++PI)
261 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
262 VE = PI->second.end(); VI != VE; ++VI)
263 if (isa<Constant>(VI->second) &&
264 !isa<GlobalValue>(VI->second))
265 getOrCreateSlot(VI->second);
269 void SlotCalculator::incorporateFunction(const Function *F) {
270 assert((ModuleLevel.size() == 0 ||
271 ModuleTypeLevel == 0) && "Module already incorporated!");
273 SC_DEBUG("begin processFunction!\n");
275 // If we emitted all of the function constants, build a compaction table.
276 if ( ModuleContainsAllFunctionConstants)
277 buildCompactionTable(F);
279 // Update the ModuleLevel entries to be accurate.
280 ModuleLevel.resize(getNumPlanes());
281 for (unsigned i = 0, e = getNumPlanes(); i != e; ++i)
282 ModuleLevel[i] = getPlane(i).size();
283 ModuleTypeLevel = Types.size();
285 // Iterate over function arguments, adding them to the value table...
286 for(Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
289 if ( !ModuleContainsAllFunctionConstants ) {
290 // Iterate over all of the instructions in the function, looking for
291 // constant values that are referenced. Add these to the value pools
292 // before any nonconstant values. This will be turned into the constant
293 // pool for the bytecode writer.
296 // Emit all of the constants that are being used by the instructions in
298 constant_iterator CI = constant_begin(F);
299 constant_iterator CE = constant_end(F);
301 this->getOrCreateSlot(*CI);
305 // If there is a symbol table, it is possible that the user has names for
306 // constants that are not being used. In this case, we will have problems
307 // if we don't emit the constants now, because otherwise we will get
308 // symbol table references to constants not in the output. Scan for these
311 processSymbolTableConstants(&F->getSymbolTable());
314 SC_DEBUG("Inserting Instructions:\n");
316 // Add all of the instructions to the type planes...
317 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
319 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
324 // If we are building a compaction table, prune out planes that do not benefit
325 // from being compactified.
326 if (!CompactionTable.empty())
327 pruneCompactionTable();
329 SC_DEBUG("end processFunction!\n");
332 void SlotCalculator::purgeFunction() {
333 assert((ModuleLevel.size() != 0 ||
334 ModuleTypeLevel != 0) && "Module not incorporated!");
335 unsigned NumModuleTypes = ModuleLevel.size();
337 SC_DEBUG("begin purgeFunction!\n");
339 // First, free the compaction map if used.
340 CompactionNodeMap.clear();
341 CompactionTypeMap.clear();
343 // Next, remove values from existing type planes
344 for (unsigned i = 0; i != NumModuleTypes; ++i) {
345 // Size of plane before function came
346 unsigned ModuleLev = getModuleLevel(i);
347 assert(int(ModuleLev) >= 0 && "BAD!");
349 TypePlane &Plane = getPlane(i);
351 assert(ModuleLev <= Plane.size() && "module levels higher than elements?");
352 while (Plane.size() != ModuleLev) {
353 assert(!isa<GlobalValue>(Plane.back()) &&
354 "Functions cannot define globals!");
355 NodeMap.erase(Plane.back()); // Erase from nodemap
356 Plane.pop_back(); // Shrink plane
360 // We don't need this state anymore, free it up.
364 // Finally, remove any type planes defined by the function...
365 CompactionTypes.clear();
366 if (!CompactionTable.empty()) {
367 CompactionTable.clear();
369 while (Table.size() > NumModuleTypes) {
370 TypePlane &Plane = Table.back();
371 SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
372 << Plane.size() << "\n");
373 while (Plane.size()) {
374 assert(!isa<GlobalValue>(Plane.back()) &&
375 "Functions cannot define globals!");
376 NodeMap.erase(Plane.back()); // Erase from nodemap
377 Plane.pop_back(); // Shrink plane
380 Table.pop_back(); // Nuke the plane, we don't like it.
384 SC_DEBUG("end purgeFunction!\n");
387 static inline bool hasNullValue(const Type *Ty) {
388 return Ty != Type::LabelTy && Ty != Type::VoidTy && !isa<OpaqueType>(Ty);
391 /// getOrCreateCompactionTableSlot - This method is used to build up the initial
392 /// approximation of the compaction table.
393 unsigned SlotCalculator::getOrCreateCompactionTableSlot(const Value *V) {
394 std::map<const Value*, unsigned>::iterator I =
395 CompactionNodeMap.lower_bound(V);
396 if (I != CompactionNodeMap.end() && I->first == V)
397 return I->second; // Already exists?
399 // Make sure the type is in the table.
401 if (!CompactionTypes.empty())
402 Ty = getOrCreateCompactionTableSlot(V->getType());
403 else // If the type plane was decompactified, use the global plane ID
404 Ty = getSlot(V->getType());
405 if (CompactionTable.size() <= Ty)
406 CompactionTable.resize(Ty+1);
408 TypePlane &TyPlane = CompactionTable[Ty];
410 // Make sure to insert the null entry if the thing we are inserting is not a
412 if (TyPlane.empty() && hasNullValue(V->getType())) {
413 Value *ZeroInitializer = Constant::getNullValue(V->getType());
414 if (V != ZeroInitializer) {
415 TyPlane.push_back(ZeroInitializer);
416 CompactionNodeMap[ZeroInitializer] = 0;
420 unsigned SlotNo = TyPlane.size();
421 TyPlane.push_back(V);
422 CompactionNodeMap.insert(std::make_pair(V, SlotNo));
426 /// getOrCreateCompactionTableSlot - This method is used to build up the initial
427 /// approximation of the compaction table.
428 unsigned SlotCalculator::getOrCreateCompactionTableSlot(const Type *T) {
429 std::map<const Type*, unsigned>::iterator I =
430 CompactionTypeMap.lower_bound(T);
431 if (I != CompactionTypeMap.end() && I->first == T)
432 return I->second; // Already exists?
434 unsigned SlotNo = CompactionTypes.size();
435 SC_DEBUG("Inserting Compaction Type #" << SlotNo << ": " << T << "\n");
436 CompactionTypes.push_back(T);
437 CompactionTypeMap.insert(std::make_pair(T, SlotNo));
441 /// buildCompactionTable - Since all of the function constants and types are
442 /// stored in the module-level constant table, we don't need to emit a function
443 /// constant table. Also due to this, the indices for various constants and
444 /// types might be very large in large programs. In order to avoid blowing up
445 /// the size of instructions in the bytecode encoding, we build a compaction
446 /// table, which defines a mapping from function-local identifiers to global
448 void SlotCalculator::buildCompactionTable(const Function *F) {
449 assert(CompactionNodeMap.empty() && "Compaction table already built!");
450 assert(CompactionTypeMap.empty() && "Compaction types already built!");
451 // First step, insert the primitive types.
452 CompactionTable.resize(Type::LastPrimitiveTyID+1);
453 for (unsigned i = 0; i <= Type::LastPrimitiveTyID; ++i) {
454 const Type *PrimTy = Type::getPrimitiveType((Type::TypeID)i);
455 CompactionTypes.push_back(PrimTy);
456 CompactionTypeMap[PrimTy] = i;
459 // Next, include any types used by function arguments.
460 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
462 getOrCreateCompactionTableSlot(I->getType());
464 // Next, find all of the types and values that are referred to by the
465 // instructions in the function.
466 for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
467 getOrCreateCompactionTableSlot(I->getType());
468 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
469 if (isa<Constant>(I->getOperand(op)))
470 getOrCreateCompactionTableSlot(I->getOperand(op));
473 // Do the types in the symbol table
474 const SymbolTable &ST = F->getSymbolTable();
475 for (SymbolTable::type_const_iterator TI = ST.type_begin(),
476 TE = ST.type_end(); TI != TE; ++TI)
477 getOrCreateCompactionTableSlot(TI->second);
479 // Now do the constants and global values
480 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
481 PE = ST.plane_end(); PI != PE; ++PI)
482 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
483 VE = PI->second.end(); VI != VE; ++VI)
484 if (isa<Constant>(VI->second) && !isa<GlobalValue>(VI->second))
485 getOrCreateCompactionTableSlot(VI->second);
487 // Now that we have all of the values in the table, and know what types are
488 // referenced, make sure that there is at least the zero initializer in any
489 // used type plane. Since the type was used, we will be emitting instructions
490 // to the plane even if there are no constants in it.
491 CompactionTable.resize(CompactionTypes.size());
492 for (unsigned i = 0, e = CompactionTable.size(); i != e; ++i)
493 if (CompactionTable[i].empty() && (i != Type::VoidTyID) &&
494 i != Type::LabelTyID) {
495 const Type *Ty = CompactionTypes[i];
496 SC_DEBUG("Getting Null Value #" << i << " for Type " << Ty << "\n");
497 assert(Ty->getTypeID() != Type::VoidTyID);
498 assert(Ty->getTypeID() != Type::LabelTyID);
499 getOrCreateCompactionTableSlot(Constant::getNullValue(Ty));
502 // Okay, now at this point, we have a legal compaction table. Since we want
503 // to emit the smallest possible binaries, do not compactify the type plane if
504 // it will not save us anything. Because we have not yet incorporated the
505 // function body itself yet, we don't know whether or not it's a good idea to
506 // compactify other planes. We will defer this decision until later.
507 TypeList &GlobalTypes = Types;
509 // All of the values types will be scrunched to the start of the types plane
510 // of the global table. Figure out just how many there are.
511 assert(!GlobalTypes.empty() && "No global types???");
512 unsigned NumFCTypes = GlobalTypes.size()-1;
513 while (!GlobalTypes[NumFCTypes]->isFirstClassType())
516 // If there are fewer that 64 types, no instructions will be exploded due to
517 // the size of the type operands. Thus there is no need to compactify types.
518 // Also, if the compaction table contains most of the entries in the global
519 // table, there really is no reason to compactify either.
520 if (NumFCTypes < 64) {
521 // Decompactifying types is tricky, because we have to move type planes all
522 // over the place. At least we don't need to worry about updating the
523 // CompactionNodeMap for non-types though.
524 std::vector<TypePlane> TmpCompactionTable;
525 std::swap(CompactionTable, TmpCompactionTable);
527 std::swap(TmpTypes, CompactionTypes);
529 // Move each plane back over to the uncompactified plane
530 while (!TmpTypes.empty()) {
531 const Type *Ty = TmpTypes.back();
533 CompactionTypeMap.erase(Ty); // Decompactify type!
535 // Find the global slot number for this type.
536 int TySlot = getSlot(Ty);
537 assert(TySlot != -1 && "Type doesn't exist in global table?");
539 // Now we know where to put the compaction table plane.
540 if (CompactionTable.size() <= unsigned(TySlot))
541 CompactionTable.resize(TySlot+1);
542 // Move the plane back into the compaction table.
543 std::swap(CompactionTable[TySlot], TmpCompactionTable[TmpTypes.size()]);
545 // And remove the empty plane we just moved in.
546 TmpCompactionTable.pop_back();
552 /// pruneCompactionTable - Once the entire function being processed has been
553 /// incorporated into the current compaction table, look over the compaction
554 /// table and check to see if there are any values whose compaction will not
555 /// save us any space in the bytecode file. If compactifying these values
556 /// serves no purpose, then we might as well not even emit the compactification
557 /// information to the bytecode file, saving a bit more space.
559 /// Note that the type plane has already been compactified if possible.
561 void SlotCalculator::pruneCompactionTable() {
562 TypeList &TyPlane = CompactionTypes;
563 for (unsigned ctp = 0, e = CompactionTable.size(); ctp != e; ++ctp)
564 if (!CompactionTable[ctp].empty()) {
565 TypePlane &CPlane = CompactionTable[ctp];
566 unsigned GlobalSlot = ctp;
567 if (!TyPlane.empty())
568 GlobalSlot = getGlobalSlot(TyPlane[ctp]);
570 if (GlobalSlot >= Table.size())
571 Table.resize(GlobalSlot+1);
572 TypePlane &GPlane = Table[GlobalSlot];
574 unsigned ModLevel = getModuleLevel(ctp);
575 unsigned NumFunctionObjs = CPlane.size()-ModLevel;
577 // If the maximum index required if all entries in this plane were merged
578 // into the global plane is less than 64, go ahead and eliminate the
580 bool PrunePlane = GPlane.size() + NumFunctionObjs < 64;
582 // If there are no function-local values defined, and the maximum
583 // referenced global entry is less than 64, we don't need to compactify.
584 if (!PrunePlane && NumFunctionObjs == 0) {
586 for (unsigned i = 0; i != ModLevel; ++i) {
587 unsigned Idx = NodeMap[CPlane[i]];
588 if (Idx > MaxIdx) MaxIdx = Idx;
590 PrunePlane = MaxIdx < 64;
593 // Ok, finally, if we decided to prune this plane out of the compaction
597 std::swap(OldPlane, CPlane);
599 // Loop over the function local objects, relocating them to the global
601 for (unsigned i = ModLevel, e = OldPlane.size(); i != e; ++i) {
602 const Value *V = OldPlane[i];
603 CompactionNodeMap.erase(V);
604 assert(NodeMap.count(V) == 0 && "Value already in table??");
608 // For compactified global values, just remove them from the compaction
610 for (unsigned i = 0; i != ModLevel; ++i)
611 CompactionNodeMap.erase(OldPlane[i]);
613 // Update the new modulelevel for this plane.
614 assert(ctp < ModuleLevel.size() && "Cannot set modulelevel!");
615 ModuleLevel[ctp] = GPlane.size()-NumFunctionObjs;
616 assert((int)ModuleLevel[ctp] >= 0 && "Bad computation!");
621 /// Determine if the compaction table is actually empty. Because the
622 /// compaction table always includes the primitive type planes, we
623 /// can't just check getCompactionTable().size() because it will never
624 /// be zero. Furthermore, the ModuleLevel factors into whether a given
625 /// plane is empty or not. This function does the necessary computation
626 /// to determine if its actually empty.
627 bool SlotCalculator::CompactionTableIsEmpty() const {
628 // Check a degenerate case, just in case.
629 if (CompactionTable.size() == 0) return true;
632 for (unsigned i = 0, e = CompactionTable.size(); i < e; ++i) {
633 // If the plane is not empty
634 if (!CompactionTable[i].empty()) {
635 // If the module level is non-zero then at least the
636 // first element of the plane is valid and therefore not empty.
637 unsigned End = getModuleLevel(i);
642 // All the compaction table planes are empty so the table is
643 // considered empty too.
647 int SlotCalculator::getSlot(const Value *V) const {
648 // If there is a CompactionTable active...
649 if (!CompactionNodeMap.empty()) {
650 std::map<const Value*, unsigned>::const_iterator I =
651 CompactionNodeMap.find(V);
652 if (I != CompactionNodeMap.end())
653 return (int)I->second;
654 // Otherwise, if it's not in the compaction table, it must be in a
655 // non-compactified plane.
658 std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
659 if (I != NodeMap.end())
660 return (int)I->second;
665 int SlotCalculator::getSlot(const Type*T) const {
666 // If there is a CompactionTable active...
667 if (!CompactionTypeMap.empty()) {
668 std::map<const Type*, unsigned>::const_iterator I =
669 CompactionTypeMap.find(T);
670 if (I != CompactionTypeMap.end())
671 return (int)I->second;
672 // Otherwise, if it's not in the compaction table, it must be in a
673 // non-compactified plane.
676 std::map<const Type*, unsigned>::const_iterator I = TypeMap.find(T);
677 if (I != TypeMap.end())
678 return (int)I->second;
683 int SlotCalculator::getOrCreateSlot(const Value *V) {
684 if (V->getType() == Type::VoidTy) return -1;
686 int SlotNo = getSlot(V); // Check to see if it's already in!
687 if (SlotNo != -1) return SlotNo;
689 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
690 assert(GV->getParent() != 0 && "Global not embedded into a module!");
692 if (!isa<GlobalValue>(V)) // Initializers for globals are handled explicitly
693 if (const Constant *C = dyn_cast<Constant>(V)) {
694 assert(CompactionNodeMap.empty() &&
695 "All needed constants should be in the compaction map already!");
697 // Do not index the characters that make up constant strings. We emit
698 // constant strings as special entities that don't require their
699 // individual characters to be emitted.
700 if (!isa<ConstantArray>(C) || !cast<ConstantArray>(C)->isString()) {
701 // This makes sure that if a constant has uses (for example an array of
702 // const ints), that they are inserted also.
704 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
708 assert(ModuleLevel.empty() &&
709 "How can a constant string be directly accessed in a function?");
710 // Otherwise, if we are emitting a bytecode file and this IS a string,
712 if (!C->isNullValue())
713 ConstantStrings.push_back(cast<ConstantArray>(C));
717 return insertValue(V);
720 int SlotCalculator::getOrCreateSlot(const Type* T) {
721 int SlotNo = getSlot(T); // Check to see if it's already in!
722 if (SlotNo != -1) return SlotNo;
723 return insertType(T);
726 int SlotCalculator::insertValue(const Value *D, bool dontIgnore) {
727 assert(D && "Can't insert a null value!");
728 assert(getSlot(D) == -1 && "Value is already in the table!");
730 // If we are building a compaction map, and if this plane is being compacted,
731 // insert the value into the compaction map, not into the global map.
732 if (!CompactionNodeMap.empty()) {
733 if (D->getType() == Type::VoidTy) return -1; // Do not insert void values
734 assert(!isa<Constant>(D) &&
735 "Types, constants, and globals should be in global table!");
737 int Plane = getSlot(D->getType());
738 assert(Plane != -1 && CompactionTable.size() > (unsigned)Plane &&
739 "Didn't find value type!");
740 if (!CompactionTable[Plane].empty())
741 return getOrCreateCompactionTableSlot(D);
744 // If this node does not contribute to a plane, or if the node has a
745 // name and we don't want names, then ignore the silly node... Note that types
746 // do need slot numbers so that we can keep track of where other values land.
748 if (!dontIgnore) // Don't ignore nonignorables!
749 if (D->getType() == Type::VoidTy ) { // Ignore void type nodes
750 SC_DEBUG("ignored value " << *D << "\n");
751 return -1; // We do need types unconditionally though
754 // Okay, everything is happy, actually insert the silly value now...
755 return doInsertValue(D);
758 int SlotCalculator::insertType(const Type *Ty, bool dontIgnore) {
759 assert(Ty && "Can't insert a null type!");
760 assert(getSlot(Ty) == -1 && "Type is already in the table!");
762 // If we are building a compaction map, and if this plane is being compacted,
763 // insert the value into the compaction map, not into the global map.
764 if (!CompactionTypeMap.empty()) {
765 getOrCreateCompactionTableSlot(Ty);
768 // Insert the current type before any subtypes. This is important because
769 // recursive types elements are inserted in a bottom up order. Changing
770 // this here can break things. For example:
772 // global { \2 * } { { \2 }* null }
774 int ResultSlot = doInsertType(Ty);
775 SC_DEBUG(" Inserted type: " << Ty->getDescription() << " slot=" <<
778 // Loop over any contained types in the definition... in post
780 for (po_iterator<const Type*> I = po_begin(Ty), E = po_end(Ty);
783 const Type *SubTy = *I;
784 // If we haven't seen this sub type before, add it to our type table!
785 if (getSlot(SubTy) == -1) {
786 SC_DEBUG(" Inserting subtype: " << SubTy->getDescription() << "\n");
788 SC_DEBUG(" Inserted subtype: " << SubTy->getDescription() << "\n");
795 // doInsertValue - This is a small helper function to be called only
798 int SlotCalculator::doInsertValue(const Value *D) {
799 const Type *Typ = D->getType();
802 // Used for debugging DefSlot=-1 assertion...
803 //if (Typ == Type::TypeTy)
804 // cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
806 if (Typ->isDerivedType()) {
808 if (CompactionTable.empty())
809 ValSlot = getSlot(Typ);
811 ValSlot = getGlobalSlot(Typ);
812 if (ValSlot == -1) { // Have we already entered this type?
813 // Nope, this is the first we have seen the type, process it.
814 ValSlot = insertType(Typ, true);
815 assert(ValSlot != -1 && "ProcessType returned -1 for a type?");
817 Ty = (unsigned)ValSlot;
819 Ty = Typ->getTypeID();
822 if (Table.size() <= Ty) // Make sure we have the type plane allocated...
823 Table.resize(Ty+1, TypePlane());
825 // If this is the first value to get inserted into the type plane, make sure
826 // to insert the implicit null value...
827 if (Table[Ty].empty() && hasNullValue(Typ)) {
828 Value *ZeroInitializer = Constant::getNullValue(Typ);
830 // If we are pushing zeroinit, it will be handled below.
831 if (D != ZeroInitializer) {
832 Table[Ty].push_back(ZeroInitializer);
833 NodeMap[ZeroInitializer] = 0;
837 // Insert node into table and NodeMap...
838 unsigned DestSlot = NodeMap[D] = Table[Ty].size();
839 Table[Ty].push_back(D);
841 SC_DEBUG(" Inserting value [" << Ty << "] = " << D << " slot=" <<
843 // G = Global, C = Constant, T = Type, F = Function, o = other
844 SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" :
845 (isa<Function>(D) ? "F" : "o"))));
847 return (int)DestSlot;
850 // doInsertType - This is a small helper function to be called only
853 int SlotCalculator::doInsertType(const Type *Ty) {
855 // Insert node into table and NodeMap...
856 unsigned DestSlot = TypeMap[Ty] = Types.size();
859 SC_DEBUG(" Inserting type [" << DestSlot << "] = " << Ty << "\n" );
860 return (int)DestSlot;