1 //===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ValueEnumerator class.
12 //===----------------------------------------------------------------------===//
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"
24 static bool isSingleValueType(const std::pair<const llvm::Type*,
26 return P.first->isSingleValueType();
29 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
30 return isa<IntegerType>(V.first->getType());
33 static bool CompareByFrequency(const std::pair<const llvm::Type*,
35 const std::pair<const llvm::Type*,
37 return P1.second > P2.second;
40 /// ValueEnumerator - Enumerate module-level information.
41 ValueEnumerator::ValueEnumerator(const Module *M) {
44 // Enumerate the global variables.
45 for (Module::const_global_iterator I = M->global_begin(),
46 E = M->global_end(); I != E; ++I)
49 // Enumerate the functions.
50 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
52 EnumerateAttributes(cast<Function>(I)->getAttributes());
55 // Enumerate the aliases.
56 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
60 // Remember what is the cutoff between globalvalue's and other constants.
61 unsigned FirstConstant = Values.size();
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());
69 // Enumerate the aliasees.
70 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
72 EnumerateValue(I->getAliasee());
74 // Enumerate types used by the type symbol table.
75 EnumerateTypeSymbolTable(M->getTypeSymbolTable());
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());
81 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
83 // Enumerate types used by function bodies and argument lists.
84 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
86 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
88 EnumerateType(I->getType());
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();
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());
101 // Enumerate metadata attached with this instruction.
103 I->getAllMetadata(MDs);
104 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
105 EnumerateMetadata(MDs[i].second);
109 // Optimize constant ordering.
110 OptimizeConstants(FirstConstant, Values.size());
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);
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);
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;
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!");
132 void ValueEnumerator::setInstructionID(const Instruction *I) {
133 InstructionMap[I] = InstructionCount++;
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!");
143 ValueMapType::const_iterator I = ValueMap.find(V);
144 assert(I != ValueMap.end() && "Value not in slotcalculator!");
148 // Optimize constant ordering.
150 struct CstSortPredicate {
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) {
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;
165 /// OptimizeConstants - Reorder constant pool for denser encoding.
166 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
167 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
169 CstSortPredicate P(*this);
170 std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
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,
177 // Rebuild the modified portion of ValueMap.
178 for (; CstStart != CstEnd; ++CstStart)
179 ValueMap[Values[CstStart].first] = CstStart+1;
183 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
185 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
186 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
188 EnumerateType(TI->second);
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();
196 EnumerateValue(VI->getValue());
199 void ValueEnumerator::EnumerateMetadata(const MetadataBase *MD) {
200 // Check to see if it's already in!
201 unsigned &MDValueID = MDValueMap[MD];
203 // Increment use count.
204 MDValues[MDValueID-1].second++;
208 // Enumerate the type of this value.
209 EnumerateType(MD->getType());
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))
219 EnumerateType(Type::getVoidTy(MD->getContext()));
224 if (const NamedMDNode *N = dyn_cast<NamedMDNode>(MD)) {
225 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
226 if (MDNode *E = N->getOperand(i))
228 MDValues.push_back(std::make_pair(MD, 1U));
229 MDValueMap[MD] = Values.size();
234 assert(isa<MDString>(MD) && "Unknown metadata kind");
235 MDValues.push_back(std::make_pair(MD, 1U));
236 MDValueID = MDValues.size();
239 void ValueEnumerator::EnumerateValue(const Value *V) {
240 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
241 if (const MetadataBase *MB = dyn_cast<MetadataBase>(V))
242 return EnumerateMetadata(MB);
244 // Check to see if it's already in!
245 unsigned &ValueID = ValueMap[V];
247 // Increment use count.
248 Values[ValueID-1].second++;
252 // Enumerate the type of this value.
253 EnumerateType(V->getType());
255 if (const Constant *C = dyn_cast<Constant>(V)) {
256 if (isa<GlobalValue>(C)) {
257 // Initializers for globals are handled explicitly elsewhere.
258 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
259 // Do not enumerate the initializers for an array of simple characters.
260 // The initializers just polute the value table, and we emit the strings
262 } else if (C->getNumOperands()) {
263 // If a constant has operands, enumerate them. This makes sure that if a
264 // constant has uses (for example an array of const ints), that they are
267 // We prefer to enumerate them with values before we enumerate the user
268 // itself. This makes it more likely that we can avoid forward references
269 // in the reader. We know that there can be no cycles in the constants
270 // graph that don't go through a global variable.
271 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
273 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
276 // Finally, add the value. Doing this could make the ValueID reference be
277 // dangling, don't reuse it.
278 Values.push_back(std::make_pair(V, 1U));
279 ValueMap[V] = Values.size();
285 Values.push_back(std::make_pair(V, 1U));
286 ValueID = Values.size();
290 void ValueEnumerator::EnumerateType(const Type *Ty) {
291 unsigned &TypeID = TypeMap[Ty];
294 // If we've already seen this type, just increase its occurrence count.
295 Types[TypeID-1].second++;
299 // First time we saw this type, add it.
300 Types.push_back(std::make_pair(Ty, 1U));
301 TypeID = Types.size();
303 // Enumerate subtypes.
304 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
309 // Enumerate the types for the specified value. If the value is a constant,
310 // walk through it, enumerating the types of the constant.
311 void ValueEnumerator::EnumerateOperandType(const Value *V) {
312 EnumerateType(V->getType());
313 if (const Constant *C = dyn_cast<Constant>(V)) {
314 // If this constant is already enumerated, ignore it, we know its type must
316 if (ValueMap.count(V)) return;
318 // This constant may have operands, make sure to enumerate the types in
320 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
321 const User *Op = C->getOperand(i);
323 // Don't enumerate basic blocks here, this happens as operands to
325 if (isa<BasicBlock>(Op)) continue;
327 EnumerateOperandType(cast<Constant>(Op));
330 if (const MDNode *N = dyn_cast<MDNode>(V)) {
331 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
332 if (Value *Elem = N->getOperand(i))
333 EnumerateOperandType(Elem);
335 } else if (isa<MDString>(V) || isa<MDNode>(V))
339 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
340 if (PAL.isEmpty()) return; // null is always 0.
342 unsigned &Entry = AttributeMap[PAL.getRawPointer()];
344 // Never saw this before, add it.
345 Attributes.push_back(PAL);
346 Entry = Attributes.size();
351 void ValueEnumerator::incorporateFunction(const Function &F) {
352 NumModuleValues = Values.size();
354 // Adding function arguments to the value table.
355 for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
359 FirstFuncConstantID = Values.size();
361 // Add all function-level constants to the value table.
362 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
363 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
364 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
366 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
370 BasicBlocks.push_back(BB);
371 ValueMap[BB] = BasicBlocks.size();
374 // Optimize the constant layout.
375 OptimizeConstants(FirstFuncConstantID, Values.size());
377 // Add the function's parameter attributes so they are available for use in
378 // the function's instruction.
379 EnumerateAttributes(F.getAttributes());
381 FirstInstID = Values.size();
383 // Add all of the instructions.
384 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
385 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
386 if (!I->getType()->isVoidTy())
392 void ValueEnumerator::purgeFunction() {
393 /// Remove purged values from the ValueMap.
394 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
395 ValueMap.erase(Values[i].first);
396 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
397 ValueMap.erase(BasicBlocks[i]);
399 Values.resize(NumModuleValues);
403 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
404 DenseMap<const BasicBlock*, unsigned> &IDMap) {
405 unsigned Counter = 0;
406 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
407 IDMap[BB] = ++Counter;
410 /// getGlobalBasicBlockID - This returns the function-specific ID for the
411 /// specified basic block. This is relatively expensive information, so it
412 /// should only be used by rare constructs such as address-of-label.
413 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
414 unsigned &Idx = GlobalBasicBlockIDs[BB];
418 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
419 return getGlobalBasicBlockID(BB);