4712dea7629c0197665316d232451c761bc891a5
[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 is distributed under the University of Illinois Open Source
6 // 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/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Metadata.h"
18 #include "llvm/Module.h"
19 #include "llvm/TypeSymbolTable.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Instructions.h"
22 #include <algorithm>
23 using namespace llvm;
24
25 static bool isSingleValueType(const std::pair<const llvm::Type*,
26                               unsigned int> &P) {
27   return P.first->isSingleValueType();
28 }
29
30 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
31   return isa<IntegerType>(V.first->getType());
32 }
33
34 static bool CompareByFrequency(const std::pair<const llvm::Type*,
35                                unsigned int> &P1,
36                                const std::pair<const llvm::Type*,
37                                unsigned int> &P2) {
38   return P1.second > P2.second;
39 }
40
41 /// ValueEnumerator - Enumerate module-level information.
42 ValueEnumerator::ValueEnumerator(const Module *M) {
43   // Enumerate the global variables.
44   for (Module::const_global_iterator I = M->global_begin(),
45          E = M->global_end(); I != E; ++I)
46     EnumerateValue(I);
47
48   // Enumerate the functions.
49   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
50     EnumerateValue(I);
51     EnumerateAttributes(cast<Function>(I)->getAttributes());
52   }
53
54   // Enumerate the aliases.
55   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
56        I != E; ++I)
57     EnumerateValue(I);
58   
59   // Remember what is the cutoff between globalvalue's and other constants.
60   unsigned FirstConstant = Values.size();
61   
62   // Enumerate the global variable initializers.
63   for (Module::const_global_iterator I = M->global_begin(),
64          E = M->global_end(); I != E; ++I)
65     if (I->hasInitializer())
66       EnumerateValue(I->getInitializer());
67
68   // Enumerate the aliasees.
69   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
70        I != E; ++I)
71     EnumerateValue(I->getAliasee());
72   
73   // Enumerate types used by the type symbol table.
74   EnumerateTypeSymbolTable(M->getTypeSymbolTable());
75
76   // Insert constants that are named at module level into the slot pool so that
77   // the module symbol table can refer to them...
78   EnumerateValueSymbolTable(M->getValueSymbolTable());
79   
80   // Enumerate types used by function bodies and argument lists.
81   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
82     
83     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
84          I != E; ++I)
85       EnumerateType(I->getType());
86     
87     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
88       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
89         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
90              OI != E; ++OI)
91           EnumerateOperandType(*OI);
92         EnumerateType(I->getType());
93         if (const CallInst *CI = dyn_cast<CallInst>(I))
94           EnumerateAttributes(CI->getAttributes());
95         else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
96           EnumerateAttributes(II->getAttributes());
97       }
98   }
99   
100   // Optimize constant ordering.
101   OptimizeConstants(FirstConstant, Values.size());
102     
103   // Sort the type table by frequency so that most commonly used types are early
104   // in the table (have low bit-width).
105   std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
106     
107   // Partition the Type ID's so that the single-value types occur before the
108   // aggregate types.  This allows the aggregate types to be dropped from the
109   // type table after parsing the global variable initializers.
110   std::partition(Types.begin(), Types.end(), isSingleValueType);
111
112   // Now that we rearranged the type table, rebuild TypeMap.
113   for (unsigned i = 0, e = Types.size(); i != e; ++i)
114     TypeMap[Types[i].first] = i+1;
115 }
116
117 unsigned ValueEnumerator::getValueID(const Value *V) const {
118   if (isa<MetadataBase>(V)) {
119     ValueMapType::const_iterator I = MDValueMap.find(V);
120     assert(I != MDValueMap.end() && "Value not in slotcalculator!");
121     return I->second-1;
122   }
123   
124   ValueMapType::const_iterator I = ValueMap.find(V);
125   assert(I != ValueMap.end() && "Value not in slotcalculator!");
126   return I->second-1;
127 }
128   
129 // Optimize constant ordering.
130 namespace {
131   struct CstSortPredicate {
132     ValueEnumerator &VE;
133     explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
134     bool operator()(const std::pair<const Value*, unsigned> &LHS,
135                     const std::pair<const Value*, unsigned> &RHS) {
136       // Sort by plane.
137       if (LHS.first->getType() != RHS.first->getType())
138         return VE.getTypeID(LHS.first->getType()) < 
139                VE.getTypeID(RHS.first->getType());
140       // Then by frequency.
141       return LHS.second > RHS.second;
142     }
143   };
144 }
145
146 /// OptimizeConstants - Reorder constant pool for denser encoding.
147 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
148   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
149   
150   CstSortPredicate P(*this);
151   std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
152   
153   // Ensure that integer constants are at the start of the constant pool.  This
154   // is important so that GEP structure indices come before gep constant exprs.
155   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
156                  isIntegerValue);
157   
158   // Rebuild the modified portion of ValueMap.
159   for (; CstStart != CstEnd; ++CstStart)
160     ValueMap[Values[CstStart].first] = CstStart+1;
161 }
162
163
164 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
165 /// table.
166 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
167   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
168        TI != TE; ++TI)
169     EnumerateType(TI->second);
170 }
171
172 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
173 /// table into the values table.
174 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
175   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); 
176        VI != VE; ++VI)
177     EnumerateValue(VI->getValue());
178 }
179
180 void ValueEnumerator::EnumerateMetadata(const MetadataBase *MD) {
181   // Check to see if it's already in!
182   unsigned &MDValueID = MDValueMap[MD];
183   if (MDValueID) {
184     // Increment use count.
185     MDValues[MDValueID-1].second++;
186     return;
187   }
188
189   // Enumerate the type of this value.
190   EnumerateType(MD->getType());
191
192   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
193     MDValues.push_back(std::make_pair(MD, 1U));
194     MDValueMap[MD] = MDValues.size();
195     MDValueID = MDValues.size();
196     for (MDNode::const_elem_iterator I = N->elem_begin(), E = N->elem_end();
197          I != E; ++I) {
198       if (*I)
199         EnumerateValue(*I);
200       else
201         EnumerateType(Type::VoidTy);
202     }
203     return;
204   } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(MD)) {
205     for(NamedMDNode::const_elem_iterator I = N->elem_begin(),
206           E = N->elem_end(); I != E; ++I) {
207       MetadataBase *M = *I;
208       EnumerateValue(M);
209     }
210     MDValues.push_back(std::make_pair(MD, 1U));
211     MDValueMap[MD] = Values.size();
212     return;
213   }
214
215   // Add the value.
216   MDValues.push_back(std::make_pair(MD, 1U));
217   MDValueID = MDValues.size();
218 }
219
220 void ValueEnumerator::EnumerateValue(const Value *V) {
221   assert(V->getType() != Type::VoidTy && "Can't insert void values!");
222   if (const MetadataBase *MB = dyn_cast<MetadataBase>(V))
223     return EnumerateMetadata(MB);
224
225   // Check to see if it's already in!
226   unsigned &ValueID = ValueMap[V];
227   if (ValueID) {
228     // Increment use count.
229     Values[ValueID-1].second++;
230     return;
231   }
232
233   // Enumerate the type of this value.
234   EnumerateType(V->getType());
235   
236   if (const Constant *C = dyn_cast<Constant>(V)) {
237     if (isa<GlobalValue>(C)) {
238       // Initializers for globals are handled explicitly elsewhere.
239     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
240       // Do not enumerate the initializers for an array of simple characters.
241       // The initializers just polute the value table, and we emit the strings
242       // specially.
243     } else if (C->getNumOperands()) {
244       // If a constant has operands, enumerate them.  This makes sure that if a
245       // constant has uses (for example an array of const ints), that they are
246       // inserted also.
247       
248       // We prefer to enumerate them with values before we enumerate the user
249       // itself.  This makes it more likely that we can avoid forward references
250       // in the reader.  We know that there can be no cycles in the constants
251       // graph that don't go through a global variable.
252       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
253            I != E; ++I)
254         EnumerateValue(*I);
255       
256       // Finally, add the value.  Doing this could make the ValueID reference be
257       // dangling, don't reuse it.
258       Values.push_back(std::make_pair(V, 1U));
259       ValueMap[V] = Values.size();
260       return;
261     }
262   }
263
264   // Add the value.
265   Values.push_back(std::make_pair(V, 1U));
266   ValueID = Values.size();
267 }
268
269
270 void ValueEnumerator::EnumerateType(const Type *Ty) {
271   unsigned &TypeID = TypeMap[Ty];
272   
273   if (TypeID) {
274     // If we've already seen this type, just increase its occurrence count.
275     Types[TypeID-1].second++;
276     return;
277   }
278   
279   // First time we saw this type, add it.
280   Types.push_back(std::make_pair(Ty, 1U));
281   TypeID = Types.size();
282   
283   // Enumerate subtypes.
284   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
285        I != E; ++I)
286     EnumerateType(*I);
287 }
288
289 // Enumerate the types for the specified value.  If the value is a constant,
290 // walk through it, enumerating the types of the constant.
291 void ValueEnumerator::EnumerateOperandType(const Value *V) {
292   EnumerateType(V->getType());
293   if (const Constant *C = dyn_cast<Constant>(V)) {
294     // If this constant is already enumerated, ignore it, we know its type must
295     // be enumerated.
296     if (ValueMap.count(V)) return;
297
298     // This constant may have operands, make sure to enumerate the types in
299     // them.
300     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
301       EnumerateOperandType(C->getOperand(i));
302
303     if (const MDNode *N = dyn_cast<MDNode>(V)) {
304       for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
305         Value *Elem = N->getElement(i);
306         if (Elem)
307           EnumerateOperandType(Elem);
308       }
309     }
310   } else if (isa<MDString>(V) || isa<MDNode>(V))
311     EnumerateValue(V);
312 }
313
314 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
315   if (PAL.isEmpty()) return;  // null is always 0.
316   // Do a lookup.
317   unsigned &Entry = AttributeMap[PAL.getRawPointer()];
318   if (Entry == 0) {
319     // Never saw this before, add it.
320     Attributes.push_back(PAL);
321     Entry = Attributes.size();
322   }
323 }
324
325
326 void ValueEnumerator::incorporateFunction(const Function &F) {
327   NumModuleValues = Values.size();
328   
329   // Adding function arguments to the value table.
330   for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
331       I != E; ++I)
332     EnumerateValue(I);
333
334   FirstFuncConstantID = Values.size();
335   
336   // Add all function-level constants to the value table.
337   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
338     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
339       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
340            OI != E; ++OI) {
341         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
342             isa<InlineAsm>(*OI))
343           EnumerateValue(*OI);
344       }
345     BasicBlocks.push_back(BB);
346     ValueMap[BB] = BasicBlocks.size();
347   }
348   
349   // Optimize the constant layout.
350   OptimizeConstants(FirstFuncConstantID, Values.size());
351   
352   // Add the function's parameter attributes so they are available for use in
353   // the function's instruction.
354   EnumerateAttributes(F.getAttributes());
355
356   FirstInstID = Values.size();
357   
358   // Add all of the instructions.
359   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
360     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
361       if (I->getType() != Type::VoidTy)
362         EnumerateValue(I);
363     }
364   }
365 }
366
367 void ValueEnumerator::purgeFunction() {
368   /// Remove purged values from the ValueMap.
369   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
370     ValueMap.erase(Values[i].first);
371   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
372     ValueMap.erase(BasicBlocks[i]);
373     
374   Values.resize(NumModuleValues);
375   BasicBlocks.clear();
376 }
377