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 V.first->getType()->isIntegerTy();
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) {
42 // Enumerate the global variables.
43 for (Module::const_global_iterator I = M->global_begin(),
44 E = M->global_end(); I != E; ++I)
47 // Enumerate the functions.
48 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
50 EnumerateAttributes(cast<Function>(I)->getAttributes());
53 // Enumerate the aliases.
54 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
58 // Remember what is the cutoff between globalvalue's and other constants.
59 unsigned FirstConstant = Values.size();
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());
67 // Enumerate the aliasees.
68 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
70 EnumerateValue(I->getAliasee());
72 // Enumerate types used by the type symbol table.
73 EnumerateTypeSymbolTable(M->getTypeSymbolTable());
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);
80 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
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 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();
93 if (MDNode *MD = dyn_cast<MDNode>(*OI))
94 if (MD->isFunctionLocal() && MD->getFunction())
95 // These will get enumerated during function-incorporation.
97 EnumerateOperandType(*OI);
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());
105 // Enumerate metadata attached with this instruction.
107 I->getAllMetadataOtherThanDebugLoc(MDs);
108 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
109 EnumerateMetadata(MDs[i].second);
111 if (!I->getDebugLoc().isUnknown()) {
113 I->getDebugLoc().getScopeAndInlinedAt(Scope, IA, I->getContext());
114 if (Scope) EnumerateMetadata(Scope);
115 if (IA) EnumerateMetadata(IA);
120 // Optimize constant ordering.
121 OptimizeConstants(FirstConstant, Values.size());
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);
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);
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;
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!");
143 void ValueEnumerator::setInstructionID(const Instruction *I) {
144 InstructionMap[I] = InstructionCount++;
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!");
154 ValueMapType::const_iterator I = ValueMap.find(V);
155 assert(I != ValueMap.end() && "Value not in slotcalculator!");
159 // Optimize constant ordering.
161 struct CstSortPredicate {
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) {
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;
176 /// OptimizeConstants - Reorder constant pool for denser encoding.
177 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
178 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
180 CstSortPredicate P(*this);
181 std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
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,
188 // Rebuild the modified portion of ValueMap.
189 for (; CstStart != CstEnd; ++CstStart)
190 ValueMap[Values[CstStart].first] = CstStart+1;
194 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
196 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
197 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
199 EnumerateType(TI->second);
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();
207 EnumerateValue(VI->getValue());
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);
218 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
219 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
220 EnumerateMetadata(MD->getOperand(i));
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];
228 // Increment use count.
229 MDValues[MDValueID-1].second++;
233 // Enumerate the type of this value.
234 EnumerateType(MD->getType());
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))
244 EnumerateType(Type::getVoidTy(MD->getContext()));
246 if (N->isFunctionLocal() && N->getFunction())
247 FunctionLocalMDs.push_back(N);
252 assert(isa<MDString>(MD) && "Unknown metadata kind");
253 MDValues.push_back(std::make_pair(MD, 1U));
254 MDValueID = MDValues.size();
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);
262 // Check to see if it's already in!
263 unsigned &ValueID = ValueMap[V];
265 // Increment use count.
266 Values[ValueID-1].second++;
270 // Enumerate the type of this value.
271 EnumerateType(V->getType());
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
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
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();
291 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
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();
303 Values.push_back(std::make_pair(V, 1U));
304 ValueID = Values.size();
308 void ValueEnumerator::EnumerateType(const Type *Ty) {
309 unsigned &TypeID = TypeMap[Ty];
312 // If we've already seen this type, just increase its occurrence count.
313 Types[TypeID-1].second++;
317 // First time we saw this type, add it.
318 Types.push_back(std::make_pair(Ty, 1U));
319 TypeID = Types.size();
321 // Enumerate subtypes.
322 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
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());
332 if (const Constant *C = dyn_cast<Constant>(V)) {
333 // If this constant is already enumerated, ignore it, we know its type must
335 if (ValueMap.count(V)) return;
337 // This constant may have operands, make sure to enumerate the types in
339 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
340 const User *Op = C->getOperand(i);
342 // Don't enumerate basic blocks here, this happens as operands to
344 if (isa<BasicBlock>(Op)) continue;
346 EnumerateOperandType(cast<Constant>(Op));
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);
354 } else if (isa<MDString>(V) || isa<MDNode>(V))
358 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
359 if (PAL.isEmpty()) return; // null is always 0.
361 unsigned &Entry = AttributeMap[PAL.getRawPointer()];
363 // Never saw this before, add it.
364 Attributes.push_back(PAL);
365 Entry = Attributes.size();
370 void ValueEnumerator::incorporateFunction(const Function &F) {
371 InstructionCount = 0;
372 NumModuleValues = Values.size();
374 // Adding function arguments to the value table.
375 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
379 FirstFuncConstantID = Values.size();
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();
386 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
390 BasicBlocks.push_back(BB);
391 ValueMap[BB] = BasicBlocks.size();
394 // Optimize the constant layout.
395 OptimizeConstants(FirstFuncConstantID, Values.size());
397 // Add the function's parameter attributes so they are available for use in
398 // the function's instruction.
399 EnumerateAttributes(F.getAttributes());
401 FirstInstID = Values.size();
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();
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);
415 if (!I->getType()->isVoidTy())
420 // Add all of the function-local metadata.
421 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
422 EnumerateOperandType(FnLocalMDVector[i]);
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]);
432 Values.resize(NumModuleValues);
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;
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];
451 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
452 return getGlobalBasicBlockID(BB);