When we know we have an MDValue or MDString, call EnumerateMetadata
[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   EnumerateNamedMetadata(M);
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 /// EnumerateNamedMetadata - Insert all of the values referenced by
211 /// named metadata in the specified module.
212 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
213   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
214        E = M->named_metadata_end(); I != E; ++I)
215     EnumerateNamedMDNode(I);
216 }
217
218 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
219   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
220     EnumerateMetadata(MD->getOperand(i));
221 }
222
223 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
224   assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
225   // Check to see if it's already in!
226   unsigned &MDValueID = MDValueMap[MD];
227   if (MDValueID) {
228     // Increment use count.
229     MDValues[MDValueID-1].second++;
230     return;
231   }
232
233   // Enumerate the type of this value.
234   EnumerateType(MD->getType());
235
236   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
237     MDValues.push_back(std::make_pair(MD, 1U));
238     MDValueMap[MD] = MDValues.size();
239     MDValueID = MDValues.size();
240     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
241       if (Value *V = N->getOperand(i))
242         EnumerateValue(V);
243       else
244         EnumerateType(Type::getVoidTy(MD->getContext()));
245     }
246     if (N->isFunctionLocal() && N->getFunction())
247       FunctionLocalMDs.push_back(N);
248     return;
249   }
250   
251   // Add the value.
252   assert(isa<MDString>(MD) && "Unknown metadata kind");
253   MDValues.push_back(std::make_pair(MD, 1U));
254   MDValueID = MDValues.size();
255 }
256
257 void ValueEnumerator::EnumerateValue(const Value *V) {
258   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
259   if (isa<MDNode>(V) || isa<MDString>(V))
260     return EnumerateMetadata(V);
261
262   // Check to see if it's already in!
263   unsigned &ValueID = ValueMap[V];
264   if (ValueID) {
265     // Increment use count.
266     Values[ValueID-1].second++;
267     return;
268   }
269
270   // Enumerate the type of this value.
271   EnumerateType(V->getType());
272
273   if (const Constant *C = dyn_cast<Constant>(V)) {
274     if (isa<GlobalValue>(C)) {
275       // Initializers for globals are handled explicitly elsewhere.
276     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
277       // Do not enumerate the initializers for an array of simple characters.
278       // The initializers just polute the value table, and we emit the strings
279       // specially.
280     } else if (C->getNumOperands()) {
281       // If a constant has operands, enumerate them.  This makes sure that if a
282       // constant has uses (for example an array of const ints), that they are
283       // inserted also.
284
285       // We prefer to enumerate them with values before we enumerate the user
286       // itself.  This makes it more likely that we can avoid forward references
287       // in the reader.  We know that there can be no cycles in the constants
288       // graph that don't go through a global variable.
289       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
290            I != E; ++I)
291         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
292           EnumerateValue(*I);
293
294       // Finally, add the value.  Doing this could make the ValueID reference be
295       // dangling, don't reuse it.
296       Values.push_back(std::make_pair(V, 1U));
297       ValueMap[V] = Values.size();
298       return;
299     }
300   }
301
302   // Add the value.
303   Values.push_back(std::make_pair(V, 1U));
304   ValueID = Values.size();
305 }
306
307
308 void ValueEnumerator::EnumerateType(const Type *Ty) {
309   unsigned &TypeID = TypeMap[Ty];
310
311   if (TypeID) {
312     // If we've already seen this type, just increase its occurrence count.
313     Types[TypeID-1].second++;
314     return;
315   }
316
317   // First time we saw this type, add it.
318   Types.push_back(std::make_pair(Ty, 1U));
319   TypeID = Types.size();
320
321   // Enumerate subtypes.
322   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
323        I != E; ++I)
324     EnumerateType(*I);
325 }
326
327 // Enumerate the types for the specified value.  If the value is a constant,
328 // walk through it, enumerating the types of the constant.
329 void ValueEnumerator::EnumerateOperandType(const Value *V) {
330   EnumerateType(V->getType());
331   
332   if (const Constant *C = dyn_cast<Constant>(V)) {
333     // If this constant is already enumerated, ignore it, we know its type must
334     // be enumerated.
335     if (ValueMap.count(V)) return;
336
337     // This constant may have operands, make sure to enumerate the types in
338     // them.
339     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
340       const User *Op = C->getOperand(i);
341       
342       // Don't enumerate basic blocks here, this happens as operands to
343       // blockaddress.
344       if (isa<BasicBlock>(Op)) continue;
345       
346       EnumerateOperandType(cast<Constant>(Op));
347     }
348
349     if (const MDNode *N = dyn_cast<MDNode>(V)) {
350       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
351         if (Value *Elem = N->getOperand(i))
352           EnumerateOperandType(Elem);
353     }
354   } else if (isa<MDString>(V) || isa<MDNode>(V))
355     EnumerateMetadata(V);
356 }
357
358 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
359   if (PAL.isEmpty()) return;  // null is always 0.
360   // Do a lookup.
361   unsigned &Entry = AttributeMap[PAL.getRawPointer()];
362   if (Entry == 0) {
363     // Never saw this before, add it.
364     Attributes.push_back(PAL);
365     Entry = Attributes.size();
366   }
367 }
368
369
370 void ValueEnumerator::incorporateFunction(const Function &F) {
371   InstructionCount = 0;
372   NumModuleValues = Values.size();
373
374   // Adding function arguments to the value table.
375   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
376        I != E; ++I)
377     EnumerateValue(I);
378
379   FirstFuncConstantID = Values.size();
380
381   // Add all function-level constants to the value table.
382   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
383     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
384       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
385            OI != E; ++OI) {
386         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
387             isa<InlineAsm>(*OI))
388           EnumerateValue(*OI);
389       }
390     BasicBlocks.push_back(BB);
391     ValueMap[BB] = BasicBlocks.size();
392   }
393
394   // Optimize the constant layout.
395   OptimizeConstants(FirstFuncConstantID, Values.size());
396
397   // Add the function's parameter attributes so they are available for use in
398   // the function's instruction.
399   EnumerateAttributes(F.getAttributes());
400
401   FirstInstID = Values.size();
402
403   FunctionLocalMDs.clear();
404   SmallVector<MDNode *, 8> FnLocalMDVector;
405   // Add all of the instructions.
406   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
407     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
408       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
409            OI != E; ++OI) {
410         if (MDNode *MD = dyn_cast<MDNode>(*OI))
411           if (MD->isFunctionLocal() && MD->getFunction())
412             // Enumerate metadata after the instructions they might refer to.
413             FnLocalMDVector.push_back(MD);
414       }
415       if (!I->getType()->isVoidTy())
416         EnumerateValue(I);
417     }
418   }
419
420   // Add all of the function-local metadata.
421   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
422     EnumerateOperandType(FnLocalMDVector[i]);
423 }
424
425 void ValueEnumerator::purgeFunction() {
426   /// Remove purged values from the ValueMap.
427   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
428     ValueMap.erase(Values[i].first);
429   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
430     ValueMap.erase(BasicBlocks[i]);
431
432   Values.resize(NumModuleValues);
433   BasicBlocks.clear();
434 }
435
436 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
437                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
438   unsigned Counter = 0;
439   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
440     IDMap[BB] = ++Counter;
441 }
442
443 /// getGlobalBasicBlockID - This returns the function-specific ID for the
444 /// specified basic block.  This is relatively expensive information, so it
445 /// should only be used by rare constructs such as address-of-label.
446 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
447   unsigned &Idx = GlobalBasicBlockIDs[BB];
448   if (Idx != 0)
449     return Idx-1;
450
451   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
452   return getGlobalBasicBlockID(BB);
453 }
454