LLVM API Documentation

ValueEnumerator.cpp

Go to the documentation of this file.
00001 //===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the ValueEnumerator class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "ValueEnumerator.h"
00015 #include "llvm/Constants.h"
00016 #include "llvm/DerivedTypes.h"
00017 #include "llvm/Module.h"
00018 #include "llvm/TypeSymbolTable.h"
00019 #include "llvm/ValueSymbolTable.h"
00020 #include "llvm/Instructions.h"
00021 #include <algorithm>
00022 using namespace llvm;
00023 
00024 static bool isSingleValueType(const std::pair<const llvm::Type*,
00025                               unsigned int> &P) {
00026   return P.first->isSingleValueType();
00027 }
00028 
00029 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
00030   return isa<IntegerType>(V.first->getType());
00031 }
00032 
00033 static bool CompareByFrequency(const std::pair<const llvm::Type*,
00034                                unsigned int> &P1,
00035                                const std::pair<const llvm::Type*,
00036                                unsigned int> &P2) {
00037   return P1.second > P2.second;
00038 }
00039 
00040 /// ValueEnumerator - Enumerate module-level information.
00041 ValueEnumerator::ValueEnumerator(const Module *M) {
00042   // Enumerate the global variables.
00043   for (Module::const_global_iterator I = M->global_begin(),
00044          E = M->global_end(); I != E; ++I)
00045     EnumerateValue(I);
00046 
00047   // Enumerate the functions.
00048   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
00049     EnumerateValue(I);
00050     EnumerateAttributes(cast<Function>(I)->getAttributes());
00051   }
00052 
00053   // Enumerate the aliases.
00054   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
00055        I != E; ++I)
00056     EnumerateValue(I);
00057   
00058   // Remember what is the cutoff between globalvalue's and other constants.
00059   unsigned FirstConstant = Values.size();
00060   
00061   // Enumerate the global variable initializers.
00062   for (Module::const_global_iterator I = M->global_begin(),
00063          E = M->global_end(); I != E; ++I)
00064     if (I->hasInitializer())
00065       EnumerateValue(I->getInitializer());
00066 
00067   // Enumerate the aliasees.
00068   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
00069        I != E; ++I)
00070     EnumerateValue(I->getAliasee());
00071   
00072   // Enumerate types used by the type symbol table.
00073   EnumerateTypeSymbolTable(M->getTypeSymbolTable());
00074 
00075   // Insert constants that are named at module level into the slot pool so that
00076   // the module symbol table can refer to them...
00077   EnumerateValueSymbolTable(M->getValueSymbolTable());
00078   
00079   // Enumerate types used by function bodies and argument lists.
00080   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
00081     
00082     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
00083          I != E; ++I)
00084       EnumerateType(I->getType());
00085     
00086     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00087       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
00088         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
00089              OI != E; ++OI)
00090           EnumerateOperandType(*OI);
00091         EnumerateType(I->getType());
00092         if (const CallInst *CI = dyn_cast<CallInst>(I))
00093           EnumerateAttributes(CI->getAttributes());
00094         else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
00095           EnumerateAttributes(II->getAttributes());
00096       }
00097   }
00098   
00099   // Optimize constant ordering.
00100   OptimizeConstants(FirstConstant, Values.size());
00101     
00102   // Sort the type table by frequency so that most commonly used types are early
00103   // in the table (have low bit-width).
00104   std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
00105     
00106   // Partition the Type ID's so that the single-value types occur before the
00107   // aggregate types.  This allows the aggregate types to be dropped from the
00108   // type table after parsing the global variable initializers.
00109   std::partition(Types.begin(), Types.end(), isSingleValueType);
00110 
00111   // Now that we rearranged the type table, rebuild TypeMap.
00112   for (unsigned i = 0, e = Types.size(); i != e; ++i)
00113     TypeMap[Types[i].first] = i+1;
00114 }
00115 
00116 // Optimize constant ordering.
00117 namespace {
00118   struct CstSortPredicate {
00119     ValueEnumerator &VE;
00120     explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
00121     bool operator()(const std::pair<const Value*, unsigned> &LHS,
00122                     const std::pair<const Value*, unsigned> &RHS) {
00123       // Sort by plane.
00124       if (LHS.first->getType() != RHS.first->getType())
00125         return VE.getTypeID(LHS.first->getType()) < 
00126                VE.getTypeID(RHS.first->getType());
00127       // Then by frequency.
00128       return LHS.second > RHS.second;
00129     }
00130   };
00131 }
00132 
00133 /// OptimizeConstants - Reorder constant pool for denser encoding.
00134 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
00135   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
00136   
00137   CstSortPredicate P(*this);
00138   std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
00139   
00140   // Ensure that integer constants are at the start of the constant pool.  This
00141   // is important so that GEP structure indices come before gep constant exprs.
00142   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
00143                  isIntegerValue);
00144   
00145   // Rebuild the modified portion of ValueMap.
00146   for (; CstStart != CstEnd; ++CstStart)
00147     ValueMap[Values[CstStart].first] = CstStart+1;
00148 }
00149 
00150 
00151 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
00152 /// table.
00153 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
00154   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
00155        TI != TE; ++TI)
00156     EnumerateType(TI->second);
00157 }
00158 
00159 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
00160 /// table into the values table.
00161 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
00162   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); 
00163        VI != VE; ++VI)
00164     EnumerateValue(VI->getValue());
00165 }
00166 
00167 void ValueEnumerator::EnumerateValue(const Value *V) {
00168   assert(V->getType() != Type::VoidTy && "Can't insert void values!");
00169   
00170   // Check to see if it's already in!
00171   unsigned &ValueID = ValueMap[V];
00172   if (ValueID) {
00173     // Increment use count.
00174     Values[ValueID-1].second++;
00175     return;
00176   }
00177 
00178   // Enumerate the type of this value.
00179   EnumerateType(V->getType());
00180   
00181   if (const Constant *C = dyn_cast<Constant>(V)) {
00182     if (isa<GlobalValue>(C)) {
00183       // Initializers for globals are handled explicitly elsewhere.
00184     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
00185       // Do not enumerate the initializers for an array of simple characters.
00186       // The initializers just polute the value table, and we emit the strings
00187       // specially.
00188     } else if (C->getNumOperands()) {
00189       // If a constant has operands, enumerate them.  This makes sure that if a
00190       // constant has uses (for example an array of const ints), that they are
00191       // inserted also.
00192       
00193       // We prefer to enumerate them with values before we enumerate the user
00194       // itself.  This makes it more likely that we can avoid forward references
00195       // in the reader.  We know that there can be no cycles in the constants
00196       // graph that don't go through a global variable.
00197       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
00198            I != E; ++I)
00199         EnumerateValue(*I);
00200       
00201       // Finally, add the value.  Doing this could make the ValueID reference be
00202       // dangling, don't reuse it.
00203       Values.push_back(std::make_pair(V, 1U));
00204       ValueMap[V] = Values.size();
00205       return;
00206     }
00207   }
00208   
00209   // Add the value.
00210   Values.push_back(std::make_pair(V, 1U));
00211   ValueID = Values.size();
00212 }
00213 
00214 
00215 void ValueEnumerator::EnumerateType(const Type *Ty) {
00216   unsigned &TypeID = TypeMap[Ty];
00217   
00218   if (TypeID) {
00219     // If we've already seen this type, just increase its occurrence count.
00220     Types[TypeID-1].second++;
00221     return;
00222   }
00223   
00224   // First time we saw this type, add it.
00225   Types.push_back(std::make_pair(Ty, 1U));
00226   TypeID = Types.size();
00227   
00228   // Enumerate subtypes.
00229   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
00230        I != E; ++I)
00231     EnumerateType(*I);
00232 }
00233 
00234 // Enumerate the types for the specified value.  If the value is a constant,
00235 // walk through it, enumerating the types of the constant.
00236 void ValueEnumerator::EnumerateOperandType(const Value *V) {
00237   EnumerateType(V->getType());
00238   if (const Constant *C = dyn_cast<Constant>(V)) {
00239     // If this constant is already enumerated, ignore it, we know its type must
00240     // be enumerated.
00241     if (ValueMap.count(V)) return;
00242 
00243     // This constant may have operands, make sure to enumerate the types in
00244     // them.
00245     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
00246       EnumerateOperandType(C->getOperand(i));
00247   }
00248 }
00249 
00250 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
00251   if (PAL.isEmpty()) return;  // null is always 0.
00252   // Do a lookup.
00253   unsigned &Entry = AttributeMap[PAL.getRawPointer()];
00254   if (Entry == 0) {
00255     // Never saw this before, add it.
00256     Attributes.push_back(PAL);
00257     Entry = Attributes.size();
00258   }
00259 }
00260 
00261 
00262 /// PurgeAggregateValues - If there are any aggregate values at the end of the
00263 /// value list, remove them and return the count of the remaining values.  If
00264 /// there are none, return -1.
00265 int ValueEnumerator::PurgeAggregateValues() {
00266   // If there are no aggregate values at the end of the list, return -1.
00267   if (Values.empty() || Values.back().first->getType()->isSingleValueType())
00268     return -1;
00269   
00270   // Otherwise, remove aggregate values...
00271   while (!Values.empty() && !Values.back().first->getType()->isSingleValueType())
00272     Values.pop_back();
00273   
00274   // ... and return the new size.
00275   return Values.size();
00276 }
00277 
00278 void ValueEnumerator::incorporateFunction(const Function &F) {
00279   NumModuleValues = Values.size();
00280   
00281   // Adding function arguments to the value table.
00282   for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
00283       I != E; ++I)
00284     EnumerateValue(I);
00285 
00286   FirstFuncConstantID = Values.size();
00287   
00288   // Add all function-level constants to the value table.
00289   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00290     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
00291       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
00292            OI != E; ++OI) {
00293         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
00294             isa<InlineAsm>(*OI))
00295           EnumerateValue(*OI);
00296       }
00297     BasicBlocks.push_back(BB);
00298     ValueMap[BB] = BasicBlocks.size();
00299   }
00300   
00301   // Optimize the constant layout.
00302   OptimizeConstants(FirstFuncConstantID, Values.size());
00303   
00304   // Add the function's parameter attributes so they are available for use in
00305   // the function's instruction.
00306   EnumerateAttributes(F.getAttributes());
00307 
00308   FirstInstID = Values.size();
00309   
00310   // Add all of the instructions.
00311   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00312     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
00313       if (I->getType() != Type::VoidTy)
00314         EnumerateValue(I);
00315     }
00316   }
00317 }
00318 
00319 void ValueEnumerator::purgeFunction() {
00320   /// Remove purged values from the ValueMap.
00321   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
00322     ValueMap.erase(Values[i].first);
00323   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
00324     ValueMap.erase(BasicBlocks[i]);
00325     
00326   Values.resize(NumModuleValues);
00327   BasicBlocks.clear();
00328 }
00329