optimize constant layout. This fixes encoding of 181.mcf (by ensuring
[oota-llvm.git] / lib / Bitcode / Writer / ValueEnumerator.cpp
1 //===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the ValueEnumerator class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ValueEnumerator.h"
15 #include "llvm/DerivedTypes.h"
16 #include "llvm/Module.h"
17 #include "llvm/TypeSymbolTable.h"
18 #include "llvm/ValueSymbolTable.h"
19 #include <algorithm>
20 using namespace llvm;
21
22 static bool isFirstClassType(const std::pair<const llvm::Type*,
23                              unsigned int> &P) {
24   return P.first->isFirstClassType();
25 }
26
27 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
28   return isa<IntegerType>(V.first->getType());
29 }
30
31 static bool CompareByFrequency(const std::pair<const llvm::Type*,
32                                unsigned int> &P1,
33                                const std::pair<const llvm::Type*,
34                                unsigned int> &P2) {
35   return P1.second > P2.second;
36 }
37
38 /// ValueEnumerator - Enumerate module-level information.
39 ValueEnumerator::ValueEnumerator(const Module *M) {
40   // Enumerate the global variables.
41   for (Module::const_global_iterator I = M->global_begin(),
42          E = M->global_end(); I != E; ++I)
43     EnumerateValue(I);
44
45   // Enumerate the functions.
46   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
47     EnumerateValue(I);
48
49   // Enumerate the aliases.
50   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
51        I != E; ++I)
52     EnumerateValue(I);
53   
54   // Remember what is the cutoff between globalvalue's and other constants.
55   unsigned FirstConstant = Values.size();
56   
57   // Enumerate the global variable initializers.
58   for (Module::const_global_iterator I = M->global_begin(),
59          E = M->global_end(); I != E; ++I)
60     if (I->hasInitializer())
61       EnumerateValue(I->getInitializer());
62
63   // Enumerate the aliasees.
64   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
65        I != E; ++I)
66     EnumerateValue(I->getAliasee());
67   
68   // FIXME: Implement the 'string constant' optimization.
69
70   // Enumerate types used by the type symbol table.
71   EnumerateTypeSymbolTable(M->getTypeSymbolTable());
72
73   // Insert constants that are named at module level into the slot pool so that
74   // the module symbol table can refer to them...
75   EnumerateValueSymbolTable(M->getValueSymbolTable());
76   
77   // Enumerate types used by function bodies and argument lists.
78   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
79     
80     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
81          I != E; ++I)
82       EnumerateType(I->getType());
83     
84     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
85       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
86         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
87              OI != E; ++OI)
88           EnumerateType((*OI)->getType());
89         EnumerateType(I->getType());
90       }
91   }
92   
93   // Optimize constant ordering.
94   OptimizeConstants(FirstConstant, Values.size());
95     
96   // Sort the type table by frequency so that most commonly used types are early
97   // in the table (have low bit-width).
98   std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
99     
100   // Partition the Type ID's so that the first-class types occur before the
101   // aggregate types.  This allows the aggregate types to be dropped from the
102   // type table after parsing the global variable initializers.
103   std::partition(Types.begin(), Types.end(), isFirstClassType);
104
105   // Now that we rearranged the type table, rebuild TypeMap.
106   for (unsigned i = 0, e = Types.size(); i != e; ++i)
107     TypeMap[Types[i].first] = i+1;
108   
109   // FIXME: Sort value tables by frequency.
110 }
111
112 // Optimize constant ordering.
113 struct CstSortPredicate {
114   ValueEnumerator &VE;
115   CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
116   bool operator()(const std::pair<const Value*, unsigned> &LHS,
117                   const std::pair<const Value*, unsigned> &RHS) {
118     // Sort by plane.
119     if (LHS.first->getType() != RHS.first->getType())
120       return VE.getTypeID(LHS.first->getType()) < 
121              VE.getTypeID(RHS.first->getType());
122     // Then by frequency.
123     return LHS.second > RHS.second;
124   }
125 };
126
127 /// OptimizeConstants - Reorder constant pool for denser encoding.
128 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
129   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
130   
131   CstSortPredicate P(*this);
132   std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
133   
134   // Ensure that integer constants are at the start of the constant pool.  This
135   // is important so that GEP structure indices come before gep constant exprs.
136   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
137                  isIntegerValue);
138   
139   // Rebuild the modified portion of ValueMap.
140   for (; CstStart != CstEnd; ++CstStart)
141     ValueMap[Values[CstStart].first] = CstStart+1;
142 }
143
144
145 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
146 /// table.
147 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
148   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
149        TI != TE; ++TI)
150     EnumerateType(TI->second);
151 }
152
153 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
154 /// table into the values table.
155 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
156   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); 
157        VI != VE; ++VI)
158     EnumerateValue(VI->getValue());
159 }
160
161 void ValueEnumerator::EnumerateValue(const Value *V) {
162   assert(V->getType() != Type::VoidTy && "Can't insert void values!");
163   
164   // Check to see if it's already in!
165   unsigned &ValueID = ValueMap[V];
166   if (ValueID) {
167     // Increment use count.
168     Values[ValueID-1].second++;
169     return;
170   }
171   
172   // Add the value.
173   Values.push_back(std::make_pair(V, 1U));
174   ValueID = Values.size();
175
176   if (const Constant *C = dyn_cast<Constant>(V)) {
177     if (isa<GlobalValue>(C)) {
178       // Initializers for globals are handled explicitly elsewhere.
179     } else {
180       // This makes sure that if a constant has uses (for example an array of
181       // const ints), that they are inserted also.
182       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
183            I != E; ++I)
184         EnumerateValue(*I);
185     }
186   }
187
188   EnumerateType(V->getType());
189 }
190
191
192 void ValueEnumerator::EnumerateType(const Type *Ty) {
193   unsigned &TypeID = TypeMap[Ty];
194   
195   if (TypeID) {
196     // If we've already seen this type, just increase its occurrence count.
197     Types[TypeID-1].second++;
198     return;
199   }
200   
201   // First time we saw this type, add it.
202   Types.push_back(std::make_pair(Ty, 1U));
203   TypeID = Types.size();
204   
205   // Enumerate subtypes.
206   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
207        I != E; ++I)
208     EnumerateType(*I);
209   
210   // If this is a function type, enumerate the param attrs.
211   if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty))
212     EnumerateParamAttrs(FTy->getParamAttrs());
213 }
214
215 void ValueEnumerator::EnumerateParamAttrs(const ParamAttrsList *PAL) {
216   if (PAL == 0) return;  // null is always 0.
217   // Do a lookup.
218   unsigned &Entry = ParamAttrMap[PAL];
219   if (Entry == 0) {
220     // Never saw this before, add it.
221     ParamAttrs.push_back(PAL);
222     Entry = ParamAttrs.size();
223   }
224 }
225
226
227 /// PurgeAggregateValues - If there are any aggregate values at the end of the
228 /// value list, remove them and return the count of the remaining values.  If
229 /// there are none, return -1.
230 int ValueEnumerator::PurgeAggregateValues() {
231   // If there are no aggregate values at the end of the list, return -1.
232   if (Values.empty() || Values.back().first->getType()->isFirstClassType())
233     return -1;
234   
235   // Otherwise, remove aggregate values...
236   while (!Values.empty() && !Values.back().first->getType()->isFirstClassType())
237     Values.pop_back();
238   
239   // ... and return the new size.
240   return Values.size();
241 }
242
243 void ValueEnumerator::incorporateFunction(const Function &F) {
244   NumModuleValues = Values.size();
245   
246   // Adding function arguments to the value table.
247   for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
248       I != E; ++I)
249     EnumerateValue(I);
250
251   FirstFuncConstantID = Values.size();
252   
253   // Add all function-level constants to the value table.
254   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
255     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
256       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
257            OI != E; ++OI) {
258         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
259             isa<InlineAsm>(*OI))
260           EnumerateValue(*OI);
261       }
262     BasicBlocks.push_back(BB);
263     ValueMap[BB] = BasicBlocks.size();
264   }
265   
266   // Optimize the constant layout.
267   OptimizeConstants(FirstFuncConstantID, Values.size());
268   
269   FirstInstID = Values.size();
270   
271   // Add all of the instructions.
272   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
273     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
274       if (I->getType() != Type::VoidTy)
275         EnumerateValue(I);
276     }
277   }
278 }
279
280 void ValueEnumerator::purgeFunction() {
281   /// Remove purged values from the ValueMap.
282   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
283     ValueMap.erase(Values[i].first);
284   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
285     ValueMap.erase(BasicBlocks[i]);
286     
287   Values.resize(NumModuleValues);
288   BasicBlocks.clear();
289 }
290