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