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 "llvm/Analysis/SlotCalculator.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/iOther.h"
21 #include "llvm/Module.h"
22 #include "llvm/SymbolTable.h"
23 #include "llvm/Analysis/ConstantsScanner.h"
24 #include "Support/PostOrderIterator.h"
25 #include "Support/STLExtras.h"
30 #define SC_DEBUG(X) std::cerr << X
35 SlotCalculator::SlotCalculator(const Module *M ) {
36 ModuleContainsAllFunctionConstants = false;
39 // Preload table... Make sure that all of the primitive types are in the table
40 // and that their Primitive ID is equal to their slot #
42 SC_DEBUG("Inserting primitive types:\n");
43 for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
44 assert(Type::getPrimitiveType((Type::PrimitiveID)i));
45 insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
48 if (M == 0) return; // Empty table...
52 SlotCalculator::SlotCalculator(const Function *M ) {
53 ModuleContainsAllFunctionConstants = false;
54 TheModule = M ? M->getParent() : 0;
56 // Preload table... Make sure that all of the primitive types are in the table
57 // and that their Primitive ID is equal to their slot #
59 SC_DEBUG("Inserting primitive types:\n");
60 for (unsigned i = 0; i < Type::FirstDerivedTyID; ++i) {
61 assert(Type::getPrimitiveType((Type::PrimitiveID)i));
62 insertValue(Type::getPrimitiveType((Type::PrimitiveID)i), true);
65 if (TheModule == 0) return; // Empty table...
67 processModule(); // Process module level stuff
68 incorporateFunction(M); // Start out in incorporated state
71 unsigned SlotCalculator::getGlobalSlot(const Value *V) const {
72 assert(!CompactionTable.empty() &&
73 "This method can only be used when compaction is enabled!");
74 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
76 std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
77 assert(I != NodeMap.end() && "Didn't find global slot entry!");
81 SlotCalculator::TypePlane &SlotCalculator::getPlane(unsigned Plane) {
82 unsigned PIdx = Plane;
83 if (CompactionTable.empty()) { // No compaction table active?
85 } else if (!CompactionTable[Plane].empty()) { // Compaction table active.
86 assert(Plane < CompactionTable.size());
87 return CompactionTable[Plane];
89 // Final case: compaction table active, but this plane is not
90 // compactified. If the type plane is compactified, unmap back to the
91 // global type plane corresponding to "Plane".
92 if (!CompactionTable[Type::TypeTyID].empty()) {
93 const Type *Ty = cast<Type>(CompactionTable[Type::TypeTyID][Plane]);
94 std::map<const Value*, unsigned>::iterator It = NodeMap.find(Ty);
95 assert(It != NodeMap.end() && "Type not in global constant map?");
100 // Okay we are just returning an entry out of the main Table. Make sure the
101 // plane exists and return it.
102 if (PIdx >= Table.size())
103 Table.resize(PIdx+1);
108 // processModule - Process all of the module level function declarations and
109 // types that are available.
111 void SlotCalculator::processModule() {
112 SC_DEBUG("begin processModule!\n");
114 // Add all of the global variables to the value table...
116 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
120 // Scavenge the types out of the functions, then add the functions themselves
121 // to the value table...
123 for (Module::const_iterator I = TheModule->begin(), E = TheModule->end();
127 // Add all of the module level constants used as initializers
129 for (Module::const_giterator I = TheModule->gbegin(), E = TheModule->gend();
131 if (I->hasInitializer())
132 getOrCreateSlot(I->getInitializer());
134 // Now that all global constants have been added, rearrange constant planes
135 // that contain constant strings so that the strings occur at the start of the
136 // plane, not somewhere in the middle.
138 TypePlane &Types = Table[Type::TypeTyID];
139 for (unsigned plane = 0, e = Table.size(); plane != e; ++plane) {
140 if (const ArrayType *AT = dyn_cast<ArrayType>(Types[plane]))
141 if (AT->getElementType() == Type::SByteTy ||
142 AT->getElementType() == Type::UByteTy) {
143 TypePlane &Plane = Table[plane];
144 unsigned FirstNonStringID = 0;
145 for (unsigned i = 0, e = Plane.size(); i != e; ++i)
146 if (isa<ConstantAggregateZero>(Plane[i]) ||
147 cast<ConstantArray>(Plane[i])->isString()) {
148 // Check to see if we have to shuffle this string around. If not,
149 // don't do anything.
150 if (i != FirstNonStringID) {
151 // Swap the plane entries....
152 std::swap(Plane[i], Plane[FirstNonStringID]);
154 // Keep the NodeMap up to date.
155 NodeMap[Plane[i]] = i;
156 NodeMap[Plane[FirstNonStringID]] = FirstNonStringID;
163 // If we are emitting a bytecode file, scan all of the functions for their
164 // constants, which allows us to emit more compact modules. This is optional,
165 // and is just used to compactify the constants used by different functions
168 // This functionality is completely optional for the bytecode writer, but
169 // tends to produce smaller bytecode files. This should not be used in the
170 // future by clients that want to, for example, build and emit functions on
171 // the fly. For now, however, it is unconditionally enabled when building
172 // bytecode information.
174 ModuleContainsAllFunctionConstants = true;
176 SC_DEBUG("Inserting function constants:\n");
177 for (Module::const_iterator F = TheModule->begin(), E = TheModule->end();
179 for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I){
180 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
181 if (isa<Constant>(I->getOperand(op)))
182 getOrCreateSlot(I->getOperand(op));
183 getOrCreateSlot(I->getType());
184 if (const VANextInst *VAN = dyn_cast<VANextInst>(&*I))
185 getOrCreateSlot(VAN->getArgType());
187 processSymbolTableConstants(&F->getSymbolTable());
190 // Insert constants that are named at module level into the slot pool so that
191 // the module symbol table can refer to them...
192 SC_DEBUG("Inserting SymbolTable values:\n");
193 processSymbolTable(&TheModule->getSymbolTable());
195 // Now that we have collected together all of the information relevant to the
196 // module, compactify the type table if it is particularly big and outputting
197 // a bytecode file. The basic problem we run into is that some programs have
198 // a large number of types, which causes the type field to overflow its size,
199 // which causes instructions to explode in size (particularly call
200 // instructions). To avoid this behavior, we "sort" the type table so that
201 // all non-value types are pushed to the end of the type table, giving nice
202 // low numbers to the types that can be used by instructions, thus reducing
203 // the amount of explodage we suffer.
204 if (Table[Type::TypeTyID].size() >= 64) {
205 // Scan through the type table moving value types to the start of the table.
206 TypePlane *Types = &Table[Type::TypeTyID];
207 unsigned FirstNonValueTypeID = 0;
208 for (unsigned i = 0, e = Types->size(); i != e; ++i)
209 if (cast<Type>((*Types)[i])->isFirstClassType() ||
210 cast<Type>((*Types)[i])->isPrimitiveType()) {
211 // Check to see if we have to shuffle this type around. If not, don't
213 if (i != FirstNonValueTypeID) {
214 assert(i != Type::TypeTyID && FirstNonValueTypeID != Type::TypeTyID &&
215 "Cannot move around the type plane!");
217 // Swap the type ID's.
218 std::swap((*Types)[i], (*Types)[FirstNonValueTypeID]);
220 // Keep the NodeMap up to date.
221 NodeMap[(*Types)[i]] = i;
222 NodeMap[(*Types)[FirstNonValueTypeID]] = FirstNonValueTypeID;
224 // When we move a type, make sure to move its value plane as needed.
225 if (Table.size() > FirstNonValueTypeID) {
226 if (Table.size() <= i) Table.resize(i+1);
227 std::swap(Table[i], Table[FirstNonValueTypeID]);
228 Types = &Table[Type::TypeTyID];
231 ++FirstNonValueTypeID;
235 SC_DEBUG("end processModule!\n");
238 // processSymbolTable - Insert all of the values in the specified symbol table
239 // into the values table...
241 void SlotCalculator::processSymbolTable(const SymbolTable *ST) {
242 // Do the types first.
243 for (SymbolTable::type_const_iterator TI = ST->type_begin(),
244 TE = ST->type_end(); TI != TE; ++TI )
245 getOrCreateSlot(TI->second);
247 // Now do the values.
248 for (SymbolTable::plane_const_iterator PI = ST->plane_begin(),
249 PE = ST->plane_end(); PI != PE; ++PI)
250 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
251 VE = PI->second.end(); VI != VE; ++VI)
252 getOrCreateSlot(VI->second);
255 void SlotCalculator::processSymbolTableConstants(const SymbolTable *ST) {
256 // Do the types first
257 for (SymbolTable::type_const_iterator TI = ST->type_begin(),
258 TE = ST->type_end(); TI != TE; ++TI )
259 getOrCreateSlot(TI->second);
261 // Now do the constant values in all planes
262 for (SymbolTable::plane_const_iterator PI = ST->plane_begin(),
263 PE = ST->plane_end(); PI != PE; ++PI)
264 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
265 VE = PI->second.end(); VI != VE; ++VI)
266 if (isa<Constant>(VI->second))
267 getOrCreateSlot(VI->second);
271 void SlotCalculator::incorporateFunction(const Function *F) {
272 assert(ModuleLevel.size() == 0 && "Module already incorporated!");
274 SC_DEBUG("begin processFunction!\n");
276 // If we emitted all of the function constants, build a compaction table.
277 if ( ModuleContainsAllFunctionConstants)
278 buildCompactionTable(F);
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();
285 // Iterate over function arguments, adding them to the value table...
286 for(Function::const_aiterator I = F->abegin(), E = F->aend(); 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 for_each(constant_begin(F), constant_end(F),
299 bind_obj(this, &SlotCalculator::getOrCreateSlot));
301 // If there is a symbol table, it is possible that the user has names for
302 // constants that are not being used. In this case, we will have problems
303 // if we don't emit the constants now, because otherwise we will get
304 // symbol table references to constants not in the output. Scan for these
307 processSymbolTableConstants(&F->getSymbolTable());
310 SC_DEBUG("Inserting Instructions:\n");
312 // Add all of the instructions to the type planes...
313 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
315 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
317 if (const VANextInst *VAN = dyn_cast<VANextInst>(I))
318 getOrCreateSlot(VAN->getArgType());
322 // If we are building a compaction table, prune out planes that do not benefit
323 // from being compactified.
324 if (!CompactionTable.empty())
325 pruneCompactionTable();
327 SC_DEBUG("end processFunction!\n");
330 void SlotCalculator::purgeFunction() {
331 assert(ModuleLevel.size() != 0 && "Module not incorporated!");
332 unsigned NumModuleTypes = ModuleLevel.size();
334 SC_DEBUG("begin purgeFunction!\n");
336 // First, free the compaction map if used.
337 CompactionNodeMap.clear();
339 // Next, remove values from existing type planes
340 for (unsigned i = 0; i != NumModuleTypes; ++i) {
341 // Size of plane before function came
342 unsigned ModuleLev = getModuleLevel(i);
343 assert(int(ModuleLev) >= 0 && "BAD!");
345 TypePlane &Plane = getPlane(i);
347 assert(ModuleLev <= Plane.size() && "module levels higher than elements?");
348 while (Plane.size() != ModuleLev) {
349 assert(!isa<GlobalValue>(Plane.back()) &&
350 "Functions cannot define globals!");
351 NodeMap.erase(Plane.back()); // Erase from nodemap
352 Plane.pop_back(); // Shrink plane
356 // We don't need this state anymore, free it up.
359 // Finally, remove any type planes defined by the function...
360 if (!CompactionTable.empty()) {
361 CompactionTable.clear();
363 while (Table.size() > NumModuleTypes) {
364 TypePlane &Plane = Table.back();
365 SC_DEBUG("Removing Plane " << (Table.size()-1) << " of size "
366 << Plane.size() << "\n");
367 while (Plane.size()) {
368 assert(!isa<GlobalValue>(Plane.back()) &&
369 "Functions cannot define globals!");
370 NodeMap.erase(Plane.back()); // Erase from nodemap
371 Plane.pop_back(); // Shrink plane
374 Table.pop_back(); // Nuke the plane, we don't like it.
378 SC_DEBUG("end purgeFunction!\n");
381 static inline bool hasNullValue(unsigned TyID) {
382 return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
383 TyID != Type::VoidTyID;
386 /// getOrCreateCompactionTableSlot - This method is used to build up the initial
387 /// approximation of the compaction table.
388 unsigned SlotCalculator::getOrCreateCompactionTableSlot(const Value *V) {
389 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
391 std::map<const Value*, unsigned>::iterator I =
392 CompactionNodeMap.lower_bound(V);
393 if (I != CompactionNodeMap.end() && I->first == V)
394 return I->second; // Already exists?
396 // Make sure the type is in the table.
398 if (!CompactionTable[Type::TypeTyID].empty())
399 Ty = getOrCreateCompactionTableSlot(V->getType());
400 else // If the type plane was decompactified, use the global plane ID
401 Ty = getSlot(V->getType());
402 if (CompactionTable.size() <= Ty)
403 CompactionTable.resize(Ty+1);
405 assert(!isa<Type>(V) || ModuleLevel.empty());
407 TypePlane &TyPlane = CompactionTable[Ty];
409 // Make sure to insert the null entry if the thing we are inserting is not a
411 if (TyPlane.empty() && hasNullValue(V->getType()->getPrimitiveID())) {
412 Value *ZeroInitializer = Constant::getNullValue(V->getType());
413 if (V != ZeroInitializer) {
414 TyPlane.push_back(ZeroInitializer);
415 CompactionNodeMap[ZeroInitializer] = 0;
419 unsigned SlotNo = TyPlane.size();
420 TyPlane.push_back(V);
421 CompactionNodeMap.insert(std::make_pair(V, SlotNo));
426 /// buildCompactionTable - Since all of the function constants and types are
427 /// stored in the module-level constant table, we don't need to emit a function
428 /// constant table. Also due to this, the indices for various constants and
429 /// types might be very large in large programs. In order to avoid blowing up
430 /// the size of instructions in the bytecode encoding, we build a compaction
431 /// table, which defines a mapping from function-local identifiers to global
433 void SlotCalculator::buildCompactionTable(const Function *F) {
434 assert(CompactionNodeMap.empty() && "Compaction table already built!");
435 // First step, insert the primitive types.
436 CompactionTable.resize(Type::TypeTyID+1);
437 for (unsigned i = 0; i != Type::FirstDerivedTyID; ++i) {
438 const Type *PrimTy = Type::getPrimitiveType((Type::PrimitiveID)i);
439 CompactionTable[Type::TypeTyID].push_back(PrimTy);
440 CompactionNodeMap[PrimTy] = i;
443 // Next, include any types used by function arguments.
444 for (Function::const_aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
445 getOrCreateCompactionTableSlot(I->getType());
447 // Next, find all of the types and values that are referred to by the
448 // instructions in the program.
449 for (const_inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
450 getOrCreateCompactionTableSlot(I->getType());
451 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op)
452 if (isa<Constant>(I->getOperand(op)) ||
453 isa<GlobalValue>(I->getOperand(op)))
454 getOrCreateCompactionTableSlot(I->getOperand(op));
455 if (const VANextInst *VAN = dyn_cast<VANextInst>(&*I))
456 getOrCreateCompactionTableSlot(VAN->getArgType());
459 // Do the types in the symbol table
460 const SymbolTable &ST = F->getSymbolTable();
461 for (SymbolTable::type_const_iterator TI = ST.type_begin(),
462 TE = ST.type_end(); TI != TE; ++TI)
463 getOrCreateCompactionTableSlot(TI->second);
465 // Now do the constants and global values
466 for (SymbolTable::plane_const_iterator PI = ST.plane_begin(),
467 PE = ST.plane_end(); PI != PE; ++PI)
468 for (SymbolTable::value_const_iterator VI = PI->second.begin(),
469 VE = PI->second.end(); VI != VE; ++VI)
470 if (isa<Constant>(VI->second) || isa<GlobalValue>(VI->second))
471 getOrCreateCompactionTableSlot(VI->second);
473 // Now that we have all of the values in the table, and know what types are
474 // referenced, make sure that there is at least the zero initializer in any
475 // used type plane. Since the type was used, we will be emitting instructions
476 // to the plane even if there are no constants in it.
477 CompactionTable.resize(CompactionTable[Type::TypeTyID].size());
478 for (unsigned i = 0, e = CompactionTable.size(); i != e; ++i)
479 if (CompactionTable[i].empty() && i != Type::VoidTyID &&
480 i != Type::LabelTyID) {
481 const Type *Ty = cast<Type>(CompactionTable[Type::TypeTyID][i]);
482 getOrCreateCompactionTableSlot(Constant::getNullValue(Ty));
485 // Okay, now at this point, we have a legal compaction table. Since we want
486 // to emit the smallest possible binaries, do not compactify the type plane if
487 // it will not save us anything. Because we have not yet incorporated the
488 // function body itself yet, we don't know whether or not it's a good idea to
489 // compactify other planes. We will defer this decision until later.
490 TypePlane &GlobalTypes = Table[Type::TypeTyID];
492 // All of the values types will be scrunched to the start of the types plane
493 // of the global table. Figure out just how many there are.
494 assert(!GlobalTypes.empty() && "No global types???");
495 unsigned NumFCTypes = GlobalTypes.size()-1;
496 while (!cast<Type>(GlobalTypes[NumFCTypes])->isFirstClassType())
499 // If there are fewer that 64 types, no instructions will be exploded due to
500 // the size of the type operands. Thus there is no need to compactify types.
501 // Also, if the compaction table contains most of the entries in the global
502 // table, there really is no reason to compactify either.
503 if (NumFCTypes < 64) {
504 // Decompactifying types is tricky, because we have to move type planes all
505 // over the place. At least we don't need to worry about updating the
506 // CompactionNodeMap for non-types though.
507 std::vector<TypePlane> TmpCompactionTable;
508 std::swap(CompactionTable, TmpCompactionTable);
510 std::swap(Types, TmpCompactionTable[Type::TypeTyID]);
512 // Move each plane back over to the uncompactified plane
513 while (!Types.empty()) {
514 const Type *Ty = cast<Type>(Types.back());
516 CompactionNodeMap.erase(Ty); // Decompactify type!
518 if (Ty != Type::TypeTy) {
519 // Find the global slot number for this type.
520 int TySlot = getSlot(Ty);
521 assert(TySlot != -1 && "Type doesn't exist in global table?");
523 // Now we know where to put the compaction table plane.
524 if (CompactionTable.size() <= unsigned(TySlot))
525 CompactionTable.resize(TySlot+1);
526 // Move the plane back into the compaction table.
527 std::swap(CompactionTable[TySlot], TmpCompactionTable[Types.size()]);
529 // And remove the empty plane we just moved in.
530 TmpCompactionTable.pop_back();
537 /// pruneCompactionTable - Once the entire function being processed has been
538 /// incorporated into the current compaction table, look over the compaction
539 /// table and check to see if there are any values whose compaction will not
540 /// save us any space in the bytecode file. If compactifying these values
541 /// serves no purpose, then we might as well not even emit the compactification
542 /// information to the bytecode file, saving a bit more space.
544 /// Note that the type plane has already been compactified if possible.
546 void SlotCalculator::pruneCompactionTable() {
547 TypePlane &TyPlane = CompactionTable[Type::TypeTyID];
548 for (unsigned ctp = 0, e = CompactionTable.size(); ctp != e; ++ctp)
549 if (ctp != Type::TypeTyID && !CompactionTable[ctp].empty()) {
550 TypePlane &CPlane = CompactionTable[ctp];
551 unsigned GlobalSlot = ctp;
552 if (!TyPlane.empty())
553 GlobalSlot = getGlobalSlot(TyPlane[ctp]);
555 if (GlobalSlot >= Table.size())
556 Table.resize(GlobalSlot+1);
557 TypePlane &GPlane = Table[GlobalSlot];
559 unsigned ModLevel = getModuleLevel(ctp);
560 unsigned NumFunctionObjs = CPlane.size()-ModLevel;
562 // If the maximum index required if all entries in this plane were merged
563 // into the global plane is less than 64, go ahead and eliminate the
565 bool PrunePlane = GPlane.size() + NumFunctionObjs < 64;
567 // If there are no function-local values defined, and the maximum
568 // referenced global entry is less than 64, we don't need to compactify.
569 if (!PrunePlane && NumFunctionObjs == 0) {
571 for (unsigned i = 0; i != ModLevel; ++i) {
572 unsigned Idx = NodeMap[CPlane[i]];
573 if (Idx > MaxIdx) MaxIdx = Idx;
575 PrunePlane = MaxIdx < 64;
578 // Ok, finally, if we decided to prune this plane out of the compaction
582 std::swap(OldPlane, CPlane);
584 // Loop over the function local objects, relocating them to the global
586 for (unsigned i = ModLevel, e = OldPlane.size(); i != e; ++i) {
587 const Value *V = OldPlane[i];
588 CompactionNodeMap.erase(V);
589 assert(NodeMap.count(V) == 0 && "Value already in table??");
593 // For compactified global values, just remove them from the compaction
595 for (unsigned i = 0; i != ModLevel; ++i)
596 CompactionNodeMap.erase(OldPlane[i]);
598 // Update the new modulelevel for this plane.
599 assert(ctp < ModuleLevel.size() && "Cannot set modulelevel!");
600 ModuleLevel[ctp] = GPlane.size()-NumFunctionObjs;
601 assert((int)ModuleLevel[ctp] >= 0 && "Bad computation!");
607 int SlotCalculator::getSlot(const Value *V) const {
608 // If there is a CompactionTable active...
609 if (!CompactionNodeMap.empty()) {
610 std::map<const Value*, unsigned>::const_iterator I =
611 CompactionNodeMap.find(V);
612 if (I != CompactionNodeMap.end())
613 return (int)I->second;
614 // Otherwise, if it's not in the compaction table, it must be in a
615 // non-compactified plane.
618 std::map<const Value*, unsigned>::const_iterator I = NodeMap.find(V);
619 if (I != NodeMap.end())
620 return (int)I->second;
622 // Do not number ConstantPointerRef's at all. They are an abomination.
623 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
624 return getSlot(CPR->getValue());
630 int SlotCalculator::getOrCreateSlot(const Value *V) {
631 if (V->getType() == Type::VoidTy) return -1;
633 int SlotNo = getSlot(V); // Check to see if it's already in!
634 if (SlotNo != -1) return SlotNo;
636 // Do not number ConstantPointerRef's at all. They are an abomination.
637 if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(V))
638 return getOrCreateSlot(CPR->getValue());
640 if (!isa<GlobalValue>(V)) // Initializers for globals are handled explicitly
641 if (const Constant *C = dyn_cast<Constant>(V)) {
642 assert(CompactionNodeMap.empty() &&
643 "All needed constants should be in the compaction map already!");
645 // Do not index the characters that make up constant strings. We emit
646 // constant strings as special entities that don't require their
647 // individual characters to be emitted.
648 if (!isa<ConstantArray>(C) || !cast<ConstantArray>(C)->isString()) {
649 // This makes sure that if a constant has uses (for example an array of
650 // const ints), that they are inserted also.
652 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
656 assert(ModuleLevel.empty() &&
657 "How can a constant string be directly accessed in a function?");
658 // Otherwise, if we are emitting a bytecode file and this IS a string,
660 if (!C->isNullValue())
661 ConstantStrings.push_back(cast<ConstantArray>(C));
665 return insertValue(V);
669 int SlotCalculator::insertValue(const Value *D, bool dontIgnore) {
670 assert(D && "Can't insert a null value!");
671 assert(getSlot(D) == -1 && "Value is already in the table!");
673 // If we are building a compaction map, and if this plane is being compacted,
674 // insert the value into the compaction map, not into the global map.
675 if (!CompactionNodeMap.empty()) {
676 if (D->getType() == Type::VoidTy) return -1; // Do not insert void values
677 assert(!isa<Type>(D) && !isa<Constant>(D) && !isa<GlobalValue>(D) &&
678 "Types, constants, and globals should be in global SymTab!");
680 int Plane = getSlot(D->getType());
681 assert(Plane != -1 && CompactionTable.size() > (unsigned)Plane &&
682 "Didn't find value type!");
683 if (!CompactionTable[Plane].empty())
684 return getOrCreateCompactionTableSlot(D);
687 // If this node does not contribute to a plane, or if the node has a
688 // name and we don't want names, then ignore the silly node... Note that types
689 // do need slot numbers so that we can keep track of where other values land.
691 if (!dontIgnore) // Don't ignore nonignorables!
692 if (D->getType() == Type::VoidTy ) { // Ignore void type nodes
693 SC_DEBUG("ignored value " << *D << "\n");
694 return -1; // We do need types unconditionally though
697 // If it's a type, make sure that all subtypes of the type are included...
698 if (const Type *TheTy = dyn_cast<Type>(D)) {
700 // Insert the current type before any subtypes. This is important because
701 // recursive types elements are inserted in a bottom up order. Changing
702 // this here can break things. For example:
704 // global { \2 * } { { \2 }* null }
706 int ResultSlot = doInsertValue(TheTy);
707 SC_DEBUG(" Inserted type: " << TheTy->getDescription() << " slot=" <<
710 // Loop over any contained types in the definition... in post
713 for (po_iterator<const Type*> I = po_begin(TheTy), E = po_end(TheTy);
716 const Type *SubTy = *I;
717 // If we haven't seen this sub type before, add it to our type table!
718 if (getSlot(SubTy) == -1) {
719 SC_DEBUG(" Inserting subtype: " << SubTy->getDescription() << "\n");
720 int Slot = doInsertValue(SubTy);
721 SC_DEBUG(" Inserted subtype: " << SubTy->getDescription() <<
722 " slot=" << Slot << "\n");
729 // Okay, everything is happy, actually insert the silly value now...
730 return doInsertValue(D);
733 // doInsertValue - This is a small helper function to be called only
736 int SlotCalculator::doInsertValue(const Value *D) {
737 const Type *Typ = D->getType();
740 // Used for debugging DefSlot=-1 assertion...
741 //if (Typ == Type::TypeTy)
742 // cerr << "Inserting type '" << cast<Type>(D)->getDescription() << "'!\n";
744 if (Typ->isDerivedType()) {
746 if (CompactionTable.empty())
747 ValSlot = getSlot(Typ);
749 ValSlot = getGlobalSlot(Typ);
750 if (ValSlot == -1) { // Have we already entered this type?
751 // Nope, this is the first we have seen the type, process it.
752 ValSlot = insertValue(Typ, true);
753 assert(ValSlot != -1 && "ProcessType returned -1 for a type?");
755 Ty = (unsigned)ValSlot;
757 Ty = Typ->getPrimitiveID();
760 if (Table.size() <= Ty) // Make sure we have the type plane allocated...
761 Table.resize(Ty+1, TypePlane());
763 // If this is the first value to get inserted into the type plane, make sure
764 // to insert the implicit null value...
765 if (Table[Ty].empty() && hasNullValue(Ty)) {
766 Value *ZeroInitializer = Constant::getNullValue(Typ);
768 // If we are pushing zeroinit, it will be handled below.
769 if (D != ZeroInitializer) {
770 Table[Ty].push_back(ZeroInitializer);
771 NodeMap[ZeroInitializer] = 0;
775 // Insert node into table and NodeMap...
776 unsigned DestSlot = NodeMap[D] = Table[Ty].size();
777 Table[Ty].push_back(D);
779 SC_DEBUG(" Inserting value [" << Ty << "] = " << D << " slot=" <<
781 // G = Global, C = Constant, T = Type, F = Function, o = other
782 SC_DEBUG((isa<GlobalVariable>(D) ? "G" : (isa<Constant>(D) ? "C" :
783 (isa<Type>(D) ? "T" : (isa<Function>(D) ? "F" : "o")))));
785 return (int)DestSlot;