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