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/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/ValueSymbolTable.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
27 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
28 return V.first->getType()->isIntOrIntVectorTy();
31 /// ValueEnumerator - Enumerate module-level information.
32 ValueEnumerator::ValueEnumerator(const Module *M) {
33 // Enumerate the global variables.
34 for (Module::const_global_iterator I = M->global_begin(),
35 E = M->global_end(); I != E; ++I)
38 // Enumerate the functions.
39 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
41 EnumerateAttributes(cast<Function>(I)->getAttributes());
44 // Enumerate the aliases.
45 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
49 // Remember what is the cutoff between globalvalue's and other constants.
50 unsigned FirstConstant = Values.size();
52 // Enumerate the global variable initializers.
53 for (Module::const_global_iterator I = M->global_begin(),
54 E = M->global_end(); I != E; ++I)
55 if (I->hasInitializer())
56 EnumerateValue(I->getInitializer());
58 // Enumerate the aliasees.
59 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
61 EnumerateValue(I->getAliasee());
63 // Insert constants and metadata that are named at module level into the slot
64 // pool so that the module symbol table can refer to them...
65 EnumerateValueSymbolTable(M->getValueSymbolTable());
66 EnumerateNamedMetadata(M);
68 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
70 // Enumerate types used by function bodies and argument lists.
71 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
73 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
75 EnumerateType(I->getType());
77 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
78 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
79 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
81 if (MDNode *MD = dyn_cast<MDNode>(*OI))
82 if (MD->isFunctionLocal() && MD->getFunction())
83 // These will get enumerated during function-incorporation.
85 EnumerateOperandType(*OI);
87 EnumerateType(I->getType());
88 if (const CallInst *CI = dyn_cast<CallInst>(I))
89 EnumerateAttributes(CI->getAttributes());
90 else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
91 EnumerateAttributes(II->getAttributes());
93 // Enumerate metadata attached with this instruction.
95 I->getAllMetadataOtherThanDebugLoc(MDs);
96 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
97 EnumerateMetadata(MDs[i].second);
99 if (!I->getDebugLoc().isUnknown()) {
101 I->getDebugLoc().getScopeAndInlinedAt(Scope, IA, I->getContext());
102 if (Scope) EnumerateMetadata(Scope);
103 if (IA) EnumerateMetadata(IA);
108 // Optimize constant ordering.
109 OptimizeConstants(FirstConstant, Values.size());
112 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
113 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
114 assert(I != InstructionMap.end() && "Instruction is not mapped!");
118 void ValueEnumerator::setInstructionID(const Instruction *I) {
119 InstructionMap[I] = InstructionCount++;
122 unsigned ValueEnumerator::getValueID(const Value *V) const {
123 if (isa<MDNode>(V) || isa<MDString>(V)) {
124 ValueMapType::const_iterator I = MDValueMap.find(V);
125 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
129 ValueMapType::const_iterator I = ValueMap.find(V);
130 assert(I != ValueMap.end() && "Value not in slotcalculator!");
134 void ValueEnumerator::dump() const {
135 print(dbgs(), ValueMap, "Default");
137 print(dbgs(), MDValueMap, "MetaData");
141 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
142 const char *Name) const {
144 OS << "Map Name: " << Name << "\n";
145 OS << "Size: " << Map.size() << "\n";
146 for (ValueMapType::const_iterator I = Map.begin(),
147 E = Map.end(); I != E; ++I) {
149 const Value *V = I->first;
151 OS << "Value: " << V->getName();
153 OS << "Value: [null]\n";
156 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
157 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
159 if (UI != V->use_begin())
162 OS << " " << (*UI)->getName();
171 // Optimize constant ordering.
173 struct CstSortPredicate {
175 explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
176 bool operator()(const std::pair<const Value*, unsigned> &LHS,
177 const std::pair<const Value*, unsigned> &RHS) {
179 if (LHS.first->getType() != RHS.first->getType())
180 return VE.getTypeID(LHS.first->getType()) <
181 VE.getTypeID(RHS.first->getType());
182 // Then by frequency.
183 return LHS.second > RHS.second;
188 /// OptimizeConstants - Reorder constant pool for denser encoding.
189 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
190 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
192 CstSortPredicate P(*this);
193 std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
195 // Ensure that integer and vector of integer constants are at the start of the
196 // constant pool. This is important so that GEP structure indices come before
197 // gep constant exprs.
198 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
199 isIntOrIntVectorValue);
201 // Rebuild the modified portion of ValueMap.
202 for (; CstStart != CstEnd; ++CstStart)
203 ValueMap[Values[CstStart].first] = CstStart+1;
207 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
208 /// table into the values table.
209 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
210 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
212 EnumerateValue(VI->getValue());
215 /// EnumerateNamedMetadata - Insert all of the values referenced by
216 /// named metadata in the specified module.
217 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
218 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
219 E = M->named_metadata_end(); I != E; ++I)
220 EnumerateNamedMDNode(I);
223 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
224 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
225 EnumerateMetadata(MD->getOperand(i));
228 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
229 /// and types referenced by the given MDNode.
230 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
231 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
232 if (Value *V = N->getOperand(i)) {
233 if (isa<MDNode>(V) || isa<MDString>(V))
234 EnumerateMetadata(V);
235 else if (!isa<Instruction>(V) && !isa<Argument>(V))
238 EnumerateType(Type::getVoidTy(N->getContext()));
242 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
243 assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
245 // Enumerate the type of this value.
246 EnumerateType(MD->getType());
248 const MDNode *N = dyn_cast<MDNode>(MD);
250 // In the module-level pass, skip function-local nodes themselves, but
251 // do walk their operands.
252 if (N && N->isFunctionLocal() && N->getFunction()) {
253 EnumerateMDNodeOperands(N);
257 // Check to see if it's already in!
258 unsigned &MDValueID = MDValueMap[MD];
260 // Increment use count.
261 MDValues[MDValueID-1].second++;
264 MDValues.push_back(std::make_pair(MD, 1U));
265 MDValueID = MDValues.size();
267 // Enumerate all non-function-local operands.
269 EnumerateMDNodeOperands(N);
272 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
273 /// information reachable from the given MDNode.
274 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
275 assert(N->isFunctionLocal() && N->getFunction() &&
276 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
278 // Enumerate the type of this value.
279 EnumerateType(N->getType());
281 // Check to see if it's already in!
282 unsigned &MDValueID = MDValueMap[N];
284 // Increment use count.
285 MDValues[MDValueID-1].second++;
288 MDValues.push_back(std::make_pair(N, 1U));
289 MDValueID = MDValues.size();
291 // To incoroporate function-local information visit all function-local
292 // MDNodes and all function-local values they reference.
293 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
294 if (Value *V = N->getOperand(i)) {
295 if (MDNode *O = dyn_cast<MDNode>(V)) {
296 if (O->isFunctionLocal() && O->getFunction())
297 EnumerateFunctionLocalMetadata(O);
298 } else if (isa<Instruction>(V) || isa<Argument>(V))
302 // Also, collect all function-local MDNodes for easy access.
303 FunctionLocalMDs.push_back(N);
306 void ValueEnumerator::EnumerateValue(const Value *V) {
307 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
308 assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
309 "EnumerateValue doesn't handle Metadata!");
311 // Check to see if it's already in!
312 unsigned &ValueID = ValueMap[V];
314 // Increment use count.
315 Values[ValueID-1].second++;
319 // Enumerate the type of this value.
320 EnumerateType(V->getType());
322 if (const Constant *C = dyn_cast<Constant>(V)) {
323 if (isa<GlobalValue>(C)) {
324 // Initializers for globals are handled explicitly elsewhere.
325 } else if (C->getNumOperands()) {
326 // If a constant has operands, enumerate them. This makes sure that if a
327 // constant has uses (for example an array of const ints), that they are
330 // We prefer to enumerate them with values before we enumerate the user
331 // itself. This makes it more likely that we can avoid forward references
332 // in the reader. We know that there can be no cycles in the constants
333 // graph that don't go through a global variable.
334 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
336 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
339 // Finally, add the value. Doing this could make the ValueID reference be
340 // dangling, don't reuse it.
341 Values.push_back(std::make_pair(V, 1U));
342 ValueMap[V] = Values.size();
348 Values.push_back(std::make_pair(V, 1U));
349 ValueID = Values.size();
353 void ValueEnumerator::EnumerateType(Type *Ty) {
354 unsigned *TypeID = &TypeMap[Ty];
356 // We've already seen this type.
360 // If it is a non-anonymous struct, mark the type as being visited so that we
361 // don't recursively visit it. This is safe because we allow forward
362 // references of these in the bitcode reader.
363 if (StructType *STy = dyn_cast<StructType>(Ty))
364 if (!STy->isLiteral())
367 // Enumerate all of the subtypes before we enumerate this type. This ensures
368 // that the type will be enumerated in an order that can be directly built.
369 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
373 // Refresh the TypeID pointer in case the table rehashed.
374 TypeID = &TypeMap[Ty];
376 // Check to see if we got the pointer another way. This can happen when
377 // enumerating recursive types that hit the base case deeper than they start.
379 // If this is actually a struct that we are treating as forward ref'able,
380 // then emit the definition now that all of its contents are available.
381 if (*TypeID && *TypeID != ~0U)
384 // Add this type now that its contents are all happily enumerated.
387 *TypeID = Types.size();
390 // Enumerate the types for the specified value. If the value is a constant,
391 // walk through it, enumerating the types of the constant.
392 void ValueEnumerator::EnumerateOperandType(const Value *V) {
393 EnumerateType(V->getType());
395 if (const Constant *C = dyn_cast<Constant>(V)) {
396 // If this constant is already enumerated, ignore it, we know its type must
398 if (ValueMap.count(V)) return;
400 // This constant may have operands, make sure to enumerate the types in
402 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
403 const Value *Op = C->getOperand(i);
405 // Don't enumerate basic blocks here, this happens as operands to
407 if (isa<BasicBlock>(Op)) continue;
409 EnumerateOperandType(Op);
412 if (const MDNode *N = dyn_cast<MDNode>(V)) {
413 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
414 if (Value *Elem = N->getOperand(i))
415 EnumerateOperandType(Elem);
417 } else if (isa<MDString>(V) || isa<MDNode>(V))
418 EnumerateMetadata(V);
421 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
422 if (PAL.isEmpty()) return; // null is always 0.
425 unsigned &Entry = AttributeMap[PAL];
427 // Never saw this before, add it.
428 Attribute.push_back(PAL);
429 Entry = Attribute.size();
432 // Do lookups for all attribute groups.
433 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
434 AttributeSet AS = PAL.getSlotAttributes(i);
435 unsigned &Entry = AttributeGroupMap[AS];
437 AttributeGroups.push_back(AS);
438 Entry = AttributeGroups.size();
443 void ValueEnumerator::incorporateFunction(const Function &F) {
444 InstructionCount = 0;
445 NumModuleValues = Values.size();
446 NumModuleMDValues = MDValues.size();
448 // Adding function arguments to the value table.
449 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
453 FirstFuncConstantID = Values.size();
455 // Add all function-level constants to the value table.
456 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
457 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
458 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
460 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
464 BasicBlocks.push_back(BB);
465 ValueMap[BB] = BasicBlocks.size();
468 // Optimize the constant layout.
469 OptimizeConstants(FirstFuncConstantID, Values.size());
471 // Add the function's parameter attributes so they are available for use in
472 // the function's instruction.
473 EnumerateAttributes(F.getAttributes());
475 FirstInstID = Values.size();
477 SmallVector<MDNode *, 8> FnLocalMDVector;
478 // Add all of the instructions.
479 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
480 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
481 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
483 if (MDNode *MD = dyn_cast<MDNode>(*OI))
484 if (MD->isFunctionLocal() && MD->getFunction())
485 // Enumerate metadata after the instructions they might refer to.
486 FnLocalMDVector.push_back(MD);
489 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
490 I->getAllMetadataOtherThanDebugLoc(MDs);
491 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
492 MDNode *N = MDs[i].second;
493 if (N->isFunctionLocal() && N->getFunction())
494 FnLocalMDVector.push_back(N);
497 if (!I->getType()->isVoidTy())
502 // Add all of the function-local metadata.
503 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
504 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
507 void ValueEnumerator::purgeFunction() {
508 /// Remove purged values from the ValueMap.
509 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
510 ValueMap.erase(Values[i].first);
511 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
512 MDValueMap.erase(MDValues[i].first);
513 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
514 ValueMap.erase(BasicBlocks[i]);
516 Values.resize(NumModuleValues);
517 MDValues.resize(NumModuleMDValues);
519 FunctionLocalMDs.clear();
522 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
523 DenseMap<const BasicBlock*, unsigned> &IDMap) {
524 unsigned Counter = 0;
525 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
526 IDMap[BB] = ++Counter;
529 /// getGlobalBasicBlockID - This returns the function-specific ID for the
530 /// specified basic block. This is relatively expensive information, so it
531 /// should only be used by rare constructs such as address-of-label.
532 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
533 unsigned &Idx = GlobalBasicBlockIDs[BB];
537 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
538 return getGlobalBasicBlockID(BB);