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/Metadata.h"
18 #include "llvm/Module.h"
19 #include "llvm/TypeSymbolTable.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Instructions.h"
25 static bool isSingleValueType(const std::pair<const llvm::Type*,
27 return P.first->isSingleValueType();
30 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
31 return isa<IntegerType>(V.first->getType());
34 static bool CompareByFrequency(const std::pair<const llvm::Type*,
36 const std::pair<const llvm::Type*,
38 return P1.second > P2.second;
41 /// ValueEnumerator - Enumerate module-level information.
42 ValueEnumerator::ValueEnumerator(const Module *M) {
45 // Enumerate the global variables.
46 for (Module::const_global_iterator I = M->global_begin(),
47 E = M->global_end(); I != E; ++I)
50 // Enumerate the functions.
51 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
53 EnumerateAttributes(cast<Function>(I)->getAttributes());
56 // Enumerate the aliases.
57 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
61 // Remember what is the cutoff between globalvalue's and other constants.
62 unsigned FirstConstant = Values.size();
64 // Enumerate the global variable initializers.
65 for (Module::const_global_iterator I = M->global_begin(),
66 E = M->global_end(); I != E; ++I)
67 if (I->hasInitializer())
68 EnumerateValue(I->getInitializer());
70 // Enumerate the aliasees.
71 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
73 EnumerateValue(I->getAliasee());
75 // Enumerate types used by the type symbol table.
76 EnumerateTypeSymbolTable(M->getTypeSymbolTable());
78 // Insert constants that are named at module level into the slot pool so that
79 // the module symbol table can refer to them...
80 EnumerateValueSymbolTable(M->getValueSymbolTable());
82 // Enumerate types used by function bodies and argument lists.
83 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
85 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
87 EnumerateType(I->getType());
89 MetadataContext &TheMetadata = F->getContext().getMetadata();
90 typedef SmallVector<std::pair<unsigned, TrackingVH<MDNode> >, 2> MDMapTy;
92 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
93 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
94 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
96 EnumerateOperandType(*OI);
97 EnumerateType(I->getType());
98 if (const CallInst *CI = dyn_cast<CallInst>(I))
99 EnumerateAttributes(CI->getAttributes());
100 else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
101 EnumerateAttributes(II->getAttributes());
103 // Enumerate metadata attached with this instruction.
105 TheMetadata.getMDs(I, MDs);
106 for (MDMapTy::const_iterator MI = MDs.begin(), ME = MDs.end(); MI != ME;
108 EnumerateMetadata(MI->second);
112 // Optimize constant ordering.
113 OptimizeConstants(FirstConstant, Values.size());
115 // Sort the type table by frequency so that most commonly used types are early
116 // in the table (have low bit-width).
117 std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
119 // Partition the Type ID's so that the single-value types occur before the
120 // aggregate types. This allows the aggregate types to be dropped from the
121 // type table after parsing the global variable initializers.
122 std::partition(Types.begin(), Types.end(), isSingleValueType);
124 // Now that we rearranged the type table, rebuild TypeMap.
125 for (unsigned i = 0, e = Types.size(); i != e; ++i)
126 TypeMap[Types[i].first] = i+1;
129 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
130 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
131 assert (I != InstructionMap.end() && "Instruction is not mapped!");
135 void ValueEnumerator::setInstructionID(const Instruction *I) {
136 InstructionMap[I] = InstructionCount++;
139 unsigned ValueEnumerator::getValueID(const Value *V) const {
140 if (isa<MetadataBase>(V)) {
141 ValueMapType::const_iterator I = MDValueMap.find(V);
142 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
146 ValueMapType::const_iterator I = ValueMap.find(V);
147 assert(I != ValueMap.end() && "Value not in slotcalculator!");
151 // Optimize constant ordering.
153 struct CstSortPredicate {
155 explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
156 bool operator()(const std::pair<const Value*, unsigned> &LHS,
157 const std::pair<const Value*, unsigned> &RHS) {
159 if (LHS.first->getType() != RHS.first->getType())
160 return VE.getTypeID(LHS.first->getType()) <
161 VE.getTypeID(RHS.first->getType());
162 // Then by frequency.
163 return LHS.second > RHS.second;
168 /// OptimizeConstants - Reorder constant pool for denser encoding.
169 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
170 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
172 CstSortPredicate P(*this);
173 std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
175 // Ensure that integer constants are at the start of the constant pool. This
176 // is important so that GEP structure indices come before gep constant exprs.
177 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
180 // Rebuild the modified portion of ValueMap.
181 for (; CstStart != CstEnd; ++CstStart)
182 ValueMap[Values[CstStart].first] = CstStart+1;
186 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
188 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
189 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
191 EnumerateType(TI->second);
194 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
195 /// table into the values table.
196 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
197 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
199 EnumerateValue(VI->getValue());
202 void ValueEnumerator::EnumerateMetadata(const MetadataBase *MD) {
203 // Check to see if it's already in!
204 unsigned &MDValueID = MDValueMap[MD];
206 // Increment use count.
207 MDValues[MDValueID-1].second++;
211 // Enumerate the type of this value.
212 EnumerateType(MD->getType());
214 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
215 MDValues.push_back(std::make_pair(MD, 1U));
216 MDValueMap[MD] = MDValues.size();
217 MDValueID = MDValues.size();
218 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
219 if (Value *V = N->getElement(i))
222 EnumerateType(Type::getVoidTy(MD->getContext()));
225 } else if (const NamedMDNode *N = dyn_cast<NamedMDNode>(MD)) {
226 for(NamedMDNode::const_elem_iterator I = N->elem_begin(),
227 E = N->elem_end(); I != E; ++I) {
228 MetadataBase *M = *I;
231 MDValues.push_back(std::make_pair(MD, 1U));
232 MDValueMap[MD] = Values.size();
237 MDValues.push_back(std::make_pair(MD, 1U));
238 MDValueID = MDValues.size();
241 void ValueEnumerator::EnumerateValue(const Value *V) {
242 assert(V->getType() != Type::getVoidTy(V->getContext()) &&
243 "Can't insert void values!");
244 if (const MetadataBase *MB = dyn_cast<MetadataBase>(V))
245 return EnumerateMetadata(MB);
247 // Check to see if it's already in!
248 unsigned &ValueID = ValueMap[V];
250 // Increment use count.
251 Values[ValueID-1].second++;
255 // Enumerate the type of this value.
256 EnumerateType(V->getType());
258 if (const Constant *C = dyn_cast<Constant>(V)) {
259 if (isa<GlobalValue>(C)) {
260 // Initializers for globals are handled explicitly elsewhere.
261 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
262 // Do not enumerate the initializers for an array of simple characters.
263 // The initializers just polute the value table, and we emit the strings
265 } else if (C->getNumOperands()) {
266 // If a constant has operands, enumerate them. This makes sure that if a
267 // constant has uses (for example an array of const ints), that they are
270 // We prefer to enumerate them with values before we enumerate the user
271 // itself. This makes it more likely that we can avoid forward references
272 // in the reader. We know that there can be no cycles in the constants
273 // graph that don't go through a global variable.
274 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
278 // Finally, add the value. Doing this could make the ValueID reference be
279 // dangling, don't reuse it.
280 Values.push_back(std::make_pair(V, 1U));
281 ValueMap[V] = Values.size();
287 Values.push_back(std::make_pair(V, 1U));
288 ValueID = Values.size();
292 void ValueEnumerator::EnumerateType(const Type *Ty) {
293 unsigned &TypeID = TypeMap[Ty];
296 // If we've already seen this type, just increase its occurrence count.
297 Types[TypeID-1].second++;
301 // First time we saw this type, add it.
302 Types.push_back(std::make_pair(Ty, 1U));
303 TypeID = Types.size();
305 // Enumerate subtypes.
306 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
311 // Enumerate the types for the specified value. If the value is a constant,
312 // walk through it, enumerating the types of the constant.
313 void ValueEnumerator::EnumerateOperandType(const Value *V) {
314 EnumerateType(V->getType());
315 if (const Constant *C = dyn_cast<Constant>(V)) {
316 // If this constant is already enumerated, ignore it, we know its type must
318 if (ValueMap.count(V)) return;
320 // This constant may have operands, make sure to enumerate the types in
322 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
323 EnumerateOperandType(C->getOperand(i));
325 if (const MDNode *N = dyn_cast<MDNode>(V)) {
326 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
327 Value *Elem = N->getElement(i);
329 EnumerateOperandType(Elem);
332 } else if (isa<MDString>(V) || isa<MDNode>(V))
336 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
337 if (PAL.isEmpty()) return; // null is always 0.
339 unsigned &Entry = AttributeMap[PAL.getRawPointer()];
341 // Never saw this before, add it.
342 Attributes.push_back(PAL);
343 Entry = Attributes.size();
348 void ValueEnumerator::incorporateFunction(const Function &F) {
349 NumModuleValues = Values.size();
351 // Adding function arguments to the value table.
352 for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
356 FirstFuncConstantID = Values.size();
358 // Add all function-level constants to the value table.
359 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
360 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
361 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
363 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
367 BasicBlocks.push_back(BB);
368 ValueMap[BB] = BasicBlocks.size();
371 // Optimize the constant layout.
372 OptimizeConstants(FirstFuncConstantID, Values.size());
374 // Add the function's parameter attributes so they are available for use in
375 // the function's instruction.
376 EnumerateAttributes(F.getAttributes());
378 FirstInstID = Values.size();
380 // Add all of the instructions.
381 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
382 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
383 if (I->getType() != Type::getVoidTy(F.getContext()))
389 void ValueEnumerator::purgeFunction() {
390 /// Remove purged values from the ValueMap.
391 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
392 ValueMap.erase(Values[i].first);
393 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
394 ValueMap.erase(BasicBlocks[i]);
396 Values.resize(NumModuleValues);