Speedup bitcode writer. Do not walk all values for all functions to emit function...
[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/Module.h"
18 #include "llvm/TypeSymbolTable.h"
19 #include "llvm/ValueSymbolTable.h"
20 #include "llvm/Instructions.h"
21 #include <algorithm>
22 using namespace llvm;
23
24 static bool isSingleValueType(const std::pair<const llvm::Type*,
25                               unsigned int> &P) {
26   return P.first->isSingleValueType();
27 }
28
29 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
30   return V.first->getType()->isIntegerTy();
31 }
32
33 static bool CompareByFrequency(const std::pair<const llvm::Type*,
34                                unsigned int> &P1,
35                                const std::pair<const llvm::Type*,
36                                unsigned int> &P2) {
37   return P1.second > P2.second;
38 }
39
40 /// ValueEnumerator - Enumerate module-level information.
41 ValueEnumerator::ValueEnumerator(const Module *M) {
42   // Enumerate the global variables.
43   for (Module::const_global_iterator I = M->global_begin(),
44          E = M->global_end(); I != E; ++I)
45     EnumerateValue(I);
46
47   // Enumerate the functions.
48   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
49     EnumerateValue(I);
50     EnumerateAttributes(cast<Function>(I)->getAttributes());
51   }
52
53   // Enumerate the aliases.
54   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
55        I != E; ++I)
56     EnumerateValue(I);
57
58   // Remember what is the cutoff between globalvalue's and other constants.
59   unsigned FirstConstant = Values.size();
60
61   // Enumerate the global variable initializers.
62   for (Module::const_global_iterator I = M->global_begin(),
63          E = M->global_end(); I != E; ++I)
64     if (I->hasInitializer())
65       EnumerateValue(I->getInitializer());
66
67   // Enumerate the aliasees.
68   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
69        I != E; ++I)
70     EnumerateValue(I->getAliasee());
71
72   // Enumerate types used by the type symbol table.
73   EnumerateTypeSymbolTable(M->getTypeSymbolTable());
74
75   // Insert constants and metadata  that are named at module level into the slot 
76   // pool so that the module symbol table can refer to them...
77   EnumerateValueSymbolTable(M->getValueSymbolTable());
78   EnumerateMDSymbolTable(M->getMDSymbolTable());
79
80   SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
81
82   // Enumerate types used by function bodies and argument lists.
83   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
84
85     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
86          I != E; ++I)
87       EnumerateType(I->getType());
88
89     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
90       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
91         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
92              OI != E; ++OI) {
93           if (MDNode *MD = dyn_cast<MDNode>(*OI))
94             if (MD->isFunctionLocal() && MD->getFunction())
95               // These will get enumerated during function-incorporation.
96               continue;
97           EnumerateOperandType(*OI);
98         }
99         EnumerateType(I->getType());
100         if (const CallInst *CI = dyn_cast<CallInst>(I))
101           EnumerateAttributes(CI->getAttributes());
102         else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
103           EnumerateAttributes(II->getAttributes());
104
105         // Enumerate metadata attached with this instruction.
106         MDs.clear();
107         I->getAllMetadataOtherThanDebugLoc(MDs);
108         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
109           EnumerateMetadata(MDs[i].second);
110         
111         if (!I->getDebugLoc().isUnknown()) {
112           MDNode *Scope, *IA;
113           I->getDebugLoc().getScopeAndInlinedAt(Scope, IA, I->getContext());
114           if (Scope) EnumerateMetadata(Scope);
115           if (IA) EnumerateMetadata(IA);
116         }
117       }
118   }
119
120   // Optimize constant ordering.
121   OptimizeConstants(FirstConstant, Values.size());
122
123   // Sort the type table by frequency so that most commonly used types are early
124   // in the table (have low bit-width).
125   std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
126
127   // Partition the Type ID's so that the single-value types occur before the
128   // aggregate types.  This allows the aggregate types to be dropped from the
129   // type table after parsing the global variable initializers.
130   std::partition(Types.begin(), Types.end(), isSingleValueType);
131
132   // Now that we rearranged the type table, rebuild TypeMap.
133   for (unsigned i = 0, e = Types.size(); i != e; ++i)
134     TypeMap[Types[i].first] = i+1;
135 }
136
137 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
138   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
139   assert (I != InstructionMap.end() && "Instruction is not mapped!");
140     return I->second;
141 }
142
143 void ValueEnumerator::setInstructionID(const Instruction *I) {
144   InstructionMap[I] = InstructionCount++;
145 }
146
147 unsigned ValueEnumerator::getValueID(const Value *V) const {
148   if (isa<MDNode>(V) || isa<MDString>(V)) {
149     ValueMapType::const_iterator I = MDValueMap.find(V);
150     assert(I != MDValueMap.end() && "Value not in slotcalculator!");
151     return I->second-1;
152   }
153
154   ValueMapType::const_iterator I = ValueMap.find(V);
155   assert(I != ValueMap.end() && "Value not in slotcalculator!");
156   return I->second-1;
157 }
158
159 // Optimize constant ordering.
160 namespace {
161   struct CstSortPredicate {
162     ValueEnumerator &VE;
163     explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
164     bool operator()(const std::pair<const Value*, unsigned> &LHS,
165                     const std::pair<const Value*, unsigned> &RHS) {
166       // Sort by plane.
167       if (LHS.first->getType() != RHS.first->getType())
168         return VE.getTypeID(LHS.first->getType()) <
169                VE.getTypeID(RHS.first->getType());
170       // Then by frequency.
171       return LHS.second > RHS.second;
172     }
173   };
174 }
175
176 /// OptimizeConstants - Reorder constant pool for denser encoding.
177 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
178   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
179
180   CstSortPredicate P(*this);
181   std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
182
183   // Ensure that integer constants are at the start of the constant pool.  This
184   // is important so that GEP structure indices come before gep constant exprs.
185   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
186                  isIntegerValue);
187
188   // Rebuild the modified portion of ValueMap.
189   for (; CstStart != CstEnd; ++CstStart)
190     ValueMap[Values[CstStart].first] = CstStart+1;
191 }
192
193
194 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
195 /// table.
196 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
197   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
198        TI != TE; ++TI)
199     EnumerateType(TI->second);
200 }
201
202 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
203 /// table into the values table.
204 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
205   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
206        VI != VE; ++VI)
207     EnumerateValue(VI->getValue());
208 }
209
210 /// EnumerateMDSymbolTable - Insert all of the values in the specified metadata
211 /// table.
212 void ValueEnumerator::EnumerateMDSymbolTable(const MDSymbolTable &MST) {
213   for (MDSymbolTable::const_iterator MI = MST.begin(), ME = MST.end();
214        MI != ME; ++MI)
215     EnumerateValue(MI->getValue());
216 }
217
218 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
219   // Check to see if it's already in!
220   unsigned &MDValueID = MDValueMap[MD];
221   if (MDValueID) {
222     // Increment use count.
223     MDValues[MDValueID-1].second++;
224     return;
225   }
226
227   // Enumerate the type of this value.
228   EnumerateType(MD->getType());
229
230   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
231     if (MDNode *E = MD->getOperand(i))
232       EnumerateValue(E);
233   MDValues.push_back(std::make_pair(MD, 1U));
234   MDValueMap[MD] = Values.size();
235 }
236
237 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
238   assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
239   // Check to see if it's already in!
240   unsigned &MDValueID = MDValueMap[MD];
241   if (MDValueID) {
242     // Increment use count.
243     MDValues[MDValueID-1].second++;
244     return;
245   }
246
247   // Enumerate the type of this value.
248   EnumerateType(MD->getType());
249
250   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
251     MDValues.push_back(std::make_pair(MD, 1U));
252     MDValueMap[MD] = MDValues.size();
253     MDValueID = MDValues.size();
254     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
255       if (Value *V = N->getOperand(i))
256         EnumerateValue(V);
257       else
258         EnumerateType(Type::getVoidTy(MD->getContext()));
259     }
260     if (N->isFunctionLocal() && N->getFunction())
261       FunctionLocalMDs.push_back(N);
262     return;
263   }
264   
265   // Add the value.
266   assert(isa<MDString>(MD) && "Unknown metadata kind");
267   MDValues.push_back(std::make_pair(MD, 1U));
268   MDValueID = MDValues.size();
269 }
270
271 void ValueEnumerator::EnumerateValue(const Value *V) {
272   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
273   if (isa<MDNode>(V) || isa<MDString>(V))
274     return EnumerateMetadata(V);
275   else if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
276     return EnumerateNamedMDNode(NMD);
277
278   // Check to see if it's already in!
279   unsigned &ValueID = ValueMap[V];
280   if (ValueID) {
281     // Increment use count.
282     Values[ValueID-1].second++;
283     return;
284   }
285
286   // Enumerate the type of this value.
287   EnumerateType(V->getType());
288
289   if (const Constant *C = dyn_cast<Constant>(V)) {
290     if (isa<GlobalValue>(C)) {
291       // Initializers for globals are handled explicitly elsewhere.
292     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
293       // Do not enumerate the initializers for an array of simple characters.
294       // The initializers just polute the value table, and we emit the strings
295       // specially.
296     } else if (C->getNumOperands()) {
297       // If a constant has operands, enumerate them.  This makes sure that if a
298       // constant has uses (for example an array of const ints), that they are
299       // inserted also.
300
301       // We prefer to enumerate them with values before we enumerate the user
302       // itself.  This makes it more likely that we can avoid forward references
303       // in the reader.  We know that there can be no cycles in the constants
304       // graph that don't go through a global variable.
305       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
306            I != E; ++I)
307         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
308           EnumerateValue(*I);
309
310       // Finally, add the value.  Doing this could make the ValueID reference be
311       // dangling, don't reuse it.
312       Values.push_back(std::make_pair(V, 1U));
313       ValueMap[V] = Values.size();
314       return;
315     }
316   }
317
318   // Add the value.
319   Values.push_back(std::make_pair(V, 1U));
320   ValueID = Values.size();
321 }
322
323
324 void ValueEnumerator::EnumerateType(const Type *Ty) {
325   unsigned &TypeID = TypeMap[Ty];
326
327   if (TypeID) {
328     // If we've already seen this type, just increase its occurrence count.
329     Types[TypeID-1].second++;
330     return;
331   }
332
333   // First time we saw this type, add it.
334   Types.push_back(std::make_pair(Ty, 1U));
335   TypeID = Types.size();
336
337   // Enumerate subtypes.
338   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
339        I != E; ++I)
340     EnumerateType(*I);
341 }
342
343 // Enumerate the types for the specified value.  If the value is a constant,
344 // walk through it, enumerating the types of the constant.
345 void ValueEnumerator::EnumerateOperandType(const Value *V) {
346   EnumerateType(V->getType());
347   
348   if (const Constant *C = dyn_cast<Constant>(V)) {
349     // If this constant is already enumerated, ignore it, we know its type must
350     // be enumerated.
351     if (ValueMap.count(V)) return;
352
353     // This constant may have operands, make sure to enumerate the types in
354     // them.
355     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
356       const User *Op = C->getOperand(i);
357       
358       // Don't enumerate basic blocks here, this happens as operands to
359       // blockaddress.
360       if (isa<BasicBlock>(Op)) continue;
361       
362       EnumerateOperandType(cast<Constant>(Op));
363     }
364
365     if (const MDNode *N = dyn_cast<MDNode>(V)) {
366       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
367         if (Value *Elem = N->getOperand(i))
368           EnumerateOperandType(Elem);
369     }
370   } else if (isa<MDString>(V) || isa<MDNode>(V))
371     EnumerateValue(V);
372 }
373
374 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
375   if (PAL.isEmpty()) return;  // null is always 0.
376   // Do a lookup.
377   unsigned &Entry = AttributeMap[PAL.getRawPointer()];
378   if (Entry == 0) {
379     // Never saw this before, add it.
380     Attributes.push_back(PAL);
381     Entry = Attributes.size();
382   }
383 }
384
385
386 void ValueEnumerator::incorporateFunction(const Function &F) {
387   InstructionCount = 0;
388   NumModuleValues = Values.size();
389
390   // Adding function arguments to the value table.
391   for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
392       I != E; ++I)
393     EnumerateValue(I);
394
395   FirstFuncConstantID = Values.size();
396
397   // Add all function-level constants to the value table.
398   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
399     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
400       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
401            OI != E; ++OI) {
402         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
403             isa<InlineAsm>(*OI))
404           EnumerateValue(*OI);
405       }
406     BasicBlocks.push_back(BB);
407     ValueMap[BB] = BasicBlocks.size();
408   }
409
410   // Optimize the constant layout.
411   OptimizeConstants(FirstFuncConstantID, Values.size());
412
413   // Add the function's parameter attributes so they are available for use in
414   // the function's instruction.
415   EnumerateAttributes(F.getAttributes());
416
417   FirstInstID = Values.size();
418
419   FunctionLocalMDs.clear();
420   SmallVector<MDNode *, 8> FnLocalMDVector;
421   // Add all of the instructions.
422   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
423     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
424       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
425            OI != E; ++OI) {
426         if (MDNode *MD = dyn_cast<MDNode>(*OI))
427           if (MD->isFunctionLocal() && MD->getFunction())
428             // Enumerate metadata after the instructions they might refer to.
429             FnLocalMDVector.push_back(MD);
430       }
431       if (!I->getType()->isVoidTy())
432         EnumerateValue(I);
433     }
434   }
435
436   // Add all of the function-local metadata.
437   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
438     EnumerateOperandType(FnLocalMDVector[i]);
439 }
440
441 void ValueEnumerator::purgeFunction() {
442   /// Remove purged values from the ValueMap.
443   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
444     ValueMap.erase(Values[i].first);
445   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
446     ValueMap.erase(BasicBlocks[i]);
447
448   Values.resize(NumModuleValues);
449   BasicBlocks.clear();
450 }
451
452 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
453                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
454   unsigned Counter = 0;
455   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
456     IDMap[BB] = ++Counter;
457 }
458
459 /// getGlobalBasicBlockID - This returns the function-specific ID for the
460 /// specified basic block.  This is relatively expensive information, so it
461 /// should only be used by rare constructs such as address-of-label.
462 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
463   unsigned &Idx = GlobalBasicBlockIDs[BB];
464   if (Idx != 0)
465     return Idx-1;
466
467   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
468   return getGlobalBasicBlockID(BB);
469 }
470