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/UseListOrder.h"
22 #include "llvm/IR/ValueSymbolTable.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
30 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
31 unsigned LastGlobalConstantID;
32 unsigned LastGlobalValueID;
34 OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {}
36 bool isGlobalConstant(unsigned ID) const {
37 return ID <= LastGlobalConstantID;
39 bool isGlobalValue(unsigned ID) const {
40 return ID <= LastGlobalValueID && !isGlobalConstant(ID);
43 unsigned size() const { return IDs.size(); }
44 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
45 std::pair<unsigned, bool> lookup(const Value *V) const {
51 static void orderValue(const Value *V, OrderMap &OM) {
52 if (OM.lookup(V).first)
55 if (const Constant *C = dyn_cast<Constant>(V))
56 if (C->getNumOperands() && !isa<GlobalValue>(C))
57 for (const Value *Op : C->operands())
58 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
61 // Note: we cannot cache this lookup above, since inserting into the map
62 // changes the map's size, and thus affects the ID.
63 OM[V].first = OM.size() + 1;
66 static OrderMap orderModule(const Module *M) {
67 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
68 // and ValueEnumerator::incorporateFunction().
71 // In the reader, initializers of GlobalValues are set *after* all the
72 // globals have been read. Rather than awkwardly modeling this behaviour
73 // directly in predictValueUseListOrderImpl(), just assign IDs to
74 // initializers of GlobalValues before GlobalValues themselves to model this
76 for (const GlobalVariable &G : M->globals())
77 if (G.hasInitializer())
78 orderValue(G.getInitializer(), OM);
79 for (const GlobalAlias &A : M->aliases())
80 orderValue(A.getAliasee(), OM);
81 for (const Function &F : *M)
82 if (F.hasPrefixData())
83 orderValue(F.getPrefixData(), OM);
84 OM.LastGlobalConstantID = OM.size();
86 // Initializers of GlobalValues are processed in
87 // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather
88 // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
89 // by giving IDs in reverse order.
91 // Since GlobalValues never reference each other directly (just through
92 // initializers), their relative IDs only matter for determining order of
93 // uses in their initializers.
94 for (const Function &F : *M)
96 for (const GlobalAlias &A : M->aliases())
98 for (const GlobalVariable &G : M->globals())
100 OM.LastGlobalValueID = OM.size();
102 for (const Function &F : *M) {
103 if (F.isDeclaration())
105 // Here we need to match the union of ValueEnumerator::incorporateFunction()
106 // and WriteFunction(). Basic blocks are implicitly declared before
107 // anything else (by declaring their size).
108 for (const BasicBlock &BB : F)
110 for (const Argument &A : F.args())
112 for (const BasicBlock &BB : F)
113 for (const Instruction &I : BB)
114 for (const Value *Op : I.operands())
115 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
118 for (const BasicBlock &BB : F)
119 for (const Instruction &I : BB)
125 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
126 unsigned ID, const OrderMap &OM,
127 UseListOrderStack &Stack) {
128 // Predict use-list order for this one.
129 typedef std::pair<const Use *, unsigned> Entry;
130 SmallVector<Entry, 64> List;
131 for (const Use &U : V->uses())
132 // Check if this user will be serialized.
133 if (OM.lookup(U.getUser()).first)
134 List.push_back(std::make_pair(&U, List.size()));
137 // We may have lost some users.
140 bool IsGlobalValue = OM.isGlobalValue(ID);
141 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
142 const Use *LU = L.first;
143 const Use *RU = R.first;
147 auto LID = OM.lookup(LU->getUser()).first;
148 auto RID = OM.lookup(RU->getUser()).first;
150 // Global values are processed in reverse order.
152 // Moreover, initializers of GlobalValues are set *after* all the globals
153 // have been read (despite having earlier IDs). Rather than awkwardly
154 // modeling this behaviour here, orderModule() has assigned IDs to
155 // initializers of GlobalValues before GlobalValues themselves.
156 if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
159 // If ID is 4, then expect: 7 6 5 1 2 3.
162 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
168 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
173 // LID and RID are equal, so we have different operands of the same user.
174 // Assume operands are added in order for all instructions.
176 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
177 return LU->getOperandNo() < RU->getOperandNo();
178 return LU->getOperandNo() > RU->getOperandNo();
182 List.begin(), List.end(),
183 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
184 // Order is already correct.
187 // Store the shuffle.
188 Stack.emplace_back(V, F, List.size());
189 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
190 for (size_t I = 0, E = List.size(); I != E; ++I)
191 Stack.back().Shuffle[I] = List[I].second;
194 static void predictValueUseListOrder(const Value *V, const Function *F,
195 OrderMap &OM, UseListOrderStack &Stack) {
196 auto &IDPair = OM[V];
197 assert(IDPair.first && "Unmapped value");
199 // Already predicted.
202 // Do the actual prediction.
203 IDPair.second = true;
204 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
205 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
207 // Recursive descent into constants.
208 if (const Constant *C = dyn_cast<Constant>(V))
209 if (C->getNumOperands() && !isa<GlobalValue>(C))
210 for (const Value *Op : C->operands())
211 if (isa<Constant>(Op) && !isa<GlobalValue>(Op))
212 predictValueUseListOrder(Op, F, OM, Stack);
215 static UseListOrderStack predictUseListOrder(const Module *M) {
216 OrderMap OM = orderModule(M);
218 // Use-list orders need to be serialized after all the users have been added
219 // to a value, or else the shuffles will be incomplete. Store them per
220 // function in a stack.
222 // Aside from function order, the order of values doesn't matter much here.
223 UseListOrderStack Stack;
225 // We want to visit the functions backward now so we can list function-local
226 // constants in the last Function they're used in. Module-level constants
227 // have already been visited above.
228 for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
229 const Function &F = *I;
230 if (F.isDeclaration())
232 for (const BasicBlock &BB : F)
233 predictValueUseListOrder(&BB, &F, OM, Stack);
234 for (const Argument &A : F.args())
235 predictValueUseListOrder(&A, &F, OM, Stack);
236 for (const BasicBlock &BB : F)
237 for (const Instruction &I : BB)
238 for (const Value *Op : I.operands())
239 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
241 predictValueUseListOrder(Op, &F, OM, Stack);
242 for (const BasicBlock &BB : F)
243 for (const Instruction &I : BB)
244 predictValueUseListOrder(&I, &F, OM, Stack);
247 // Visit globals last, since the module-level use-list block will be seen
248 // before the function bodies are processed.
249 for (const GlobalVariable &G : M->globals())
250 predictValueUseListOrder(&G, nullptr, OM, Stack);
251 for (const Function &F : *M)
252 predictValueUseListOrder(&F, nullptr, OM, Stack);
253 for (const GlobalAlias &A : M->aliases())
254 predictValueUseListOrder(&A, nullptr, OM, Stack);
255 for (const GlobalVariable &G : M->globals())
256 if (G.hasInitializer())
257 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
258 for (const GlobalAlias &A : M->aliases())
259 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
260 for (const Function &F : *M)
261 if (F.hasPrefixData())
262 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
267 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
268 return V.first->getType()->isIntOrIntVectorTy();
271 /// ValueEnumerator - Enumerate module-level information.
272 ValueEnumerator::ValueEnumerator(const Module *M) {
273 if (shouldPreserveBitcodeUseListOrder())
274 UseListOrders = predictUseListOrder(M);
276 // Enumerate the global variables.
277 for (Module::const_global_iterator I = M->global_begin(),
279 E = M->global_end(); I != E; ++I)
282 // Enumerate the functions.
283 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
285 EnumerateAttributes(cast<Function>(I)->getAttributes());
288 // Enumerate the aliases.
289 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
293 // Remember what is the cutoff between globalvalue's and other constants.
294 unsigned FirstConstant = Values.size();
296 // Enumerate the global variable initializers.
297 for (Module::const_global_iterator I = M->global_begin(),
298 E = M->global_end(); I != E; ++I)
299 if (I->hasInitializer())
300 EnumerateValue(I->getInitializer());
302 // Enumerate the aliasees.
303 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
305 EnumerateValue(I->getAliasee());
307 // Enumerate the prefix data constants.
308 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
309 if (I->hasPrefixData())
310 EnumerateValue(I->getPrefixData());
312 // Insert constants and metadata that are named at module level into the slot
313 // pool so that the module symbol table can refer to them...
314 EnumerateValueSymbolTable(M->getValueSymbolTable());
315 EnumerateNamedMetadata(M);
317 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
319 // Enumerate types used by function bodies and argument lists.
320 for (const Function &F : *M) {
321 for (const Argument &A : F.args())
322 EnumerateType(A.getType());
324 for (const BasicBlock &BB : F)
325 for (const Instruction &I : BB) {
326 for (const Use &Op : I.operands()) {
327 if (MDNode *MD = dyn_cast<MDNode>(&Op))
328 if (MD->isFunctionLocal() && MD->getFunction())
329 // These will get enumerated during function-incorporation.
331 EnumerateOperandType(Op);
333 EnumerateType(I.getType());
334 if (const CallInst *CI = dyn_cast<CallInst>(&I))
335 EnumerateAttributes(CI->getAttributes());
336 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
337 EnumerateAttributes(II->getAttributes());
339 // Enumerate metadata attached with this instruction.
341 I.getAllMetadataOtherThanDebugLoc(MDs);
342 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
343 EnumerateMetadata(MDs[i].second);
345 if (!I.getDebugLoc().isUnknown()) {
347 I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
348 if (Scope) EnumerateMetadata(Scope);
349 if (IA) EnumerateMetadata(IA);
354 // Optimize constant ordering.
355 OptimizeConstants(FirstConstant, Values.size());
358 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
359 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
360 assert(I != InstructionMap.end() && "Instruction is not mapped!");
364 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
365 unsigned ComdatID = Comdats.idFor(C);
366 assert(ComdatID && "Comdat not found!");
370 void ValueEnumerator::setInstructionID(const Instruction *I) {
371 InstructionMap[I] = InstructionCount++;
374 unsigned ValueEnumerator::getValueID(const Value *V) const {
375 if (isa<MDNode>(V) || isa<MDString>(V)) {
376 ValueMapType::const_iterator I = MDValueMap.find(V);
377 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
381 ValueMapType::const_iterator I = ValueMap.find(V);
382 assert(I != ValueMap.end() && "Value not in slotcalculator!");
386 void ValueEnumerator::dump() const {
387 print(dbgs(), ValueMap, "Default");
389 print(dbgs(), MDValueMap, "MetaData");
393 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
394 const char *Name) const {
396 OS << "Map Name: " << Name << "\n";
397 OS << "Size: " << Map.size() << "\n";
398 for (ValueMapType::const_iterator I = Map.begin(),
399 E = Map.end(); I != E; ++I) {
401 const Value *V = I->first;
403 OS << "Value: " << V->getName();
405 OS << "Value: [null]\n";
408 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
409 for (const Use &U : V->uses()) {
410 if (&U != &*V->use_begin())
413 OS << " " << U->getName();
422 /// OptimizeConstants - Reorder constant pool for denser encoding.
423 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
424 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
426 if (shouldPreserveBitcodeUseListOrder())
427 // Optimizing constants makes the use-list order difficult to predict.
428 // Disable it for now when trying to preserve the order.
431 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
432 [this](const std::pair<const Value *, unsigned> &LHS,
433 const std::pair<const Value *, unsigned> &RHS) {
435 if (LHS.first->getType() != RHS.first->getType())
436 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
437 // Then by frequency.
438 return LHS.second > RHS.second;
441 // Ensure that integer and vector of integer constants are at the start of the
442 // constant pool. This is important so that GEP structure indices come before
443 // gep constant exprs.
444 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
445 isIntOrIntVectorValue);
447 // Rebuild the modified portion of ValueMap.
448 for (; CstStart != CstEnd; ++CstStart)
449 ValueMap[Values[CstStart].first] = CstStart+1;
453 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
454 /// table into the values table.
455 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
456 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
458 EnumerateValue(VI->getValue());
461 /// EnumerateNamedMetadata - Insert all of the values referenced by
462 /// named metadata in the specified module.
463 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
464 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
465 E = M->named_metadata_end(); I != E; ++I)
466 EnumerateNamedMDNode(I);
469 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
470 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
471 EnumerateMetadata(MD->getOperand(i));
474 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
475 /// and types referenced by the given MDNode.
476 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
477 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
478 if (Value *V = N->getOperand(i)) {
479 if (isa<MDNode>(V) || isa<MDString>(V))
480 EnumerateMetadata(V);
481 else if (!isa<Instruction>(V) && !isa<Argument>(V))
484 EnumerateType(Type::getVoidTy(N->getContext()));
488 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
489 assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
491 // Enumerate the type of this value.
492 EnumerateType(MD->getType());
494 const MDNode *N = dyn_cast<MDNode>(MD);
496 // In the module-level pass, skip function-local nodes themselves, but
497 // do walk their operands.
498 if (N && N->isFunctionLocal() && N->getFunction()) {
499 EnumerateMDNodeOperands(N);
503 // Check to see if it's already in!
504 unsigned &MDValueID = MDValueMap[MD];
506 // Increment use count.
507 MDValues[MDValueID-1].second++;
510 MDValues.push_back(std::make_pair(MD, 1U));
511 MDValueID = MDValues.size();
513 // Enumerate all non-function-local operands.
515 EnumerateMDNodeOperands(N);
518 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
519 /// information reachable from the given MDNode.
520 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
521 assert(N->isFunctionLocal() && N->getFunction() &&
522 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
524 // Enumerate the type of this value.
525 EnumerateType(N->getType());
527 // Check to see if it's already in!
528 unsigned &MDValueID = MDValueMap[N];
530 // Increment use count.
531 MDValues[MDValueID-1].second++;
534 MDValues.push_back(std::make_pair(N, 1U));
535 MDValueID = MDValues.size();
537 // To incoroporate function-local information visit all function-local
538 // MDNodes and all function-local values they reference.
539 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
540 if (Value *V = N->getOperand(i)) {
541 if (MDNode *O = dyn_cast<MDNode>(V)) {
542 if (O->isFunctionLocal() && O->getFunction())
543 EnumerateFunctionLocalMetadata(O);
544 } else if (isa<Instruction>(V) || isa<Argument>(V))
548 // Also, collect all function-local MDNodes for easy access.
549 FunctionLocalMDs.push_back(N);
552 void ValueEnumerator::EnumerateValue(const Value *V) {
553 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
554 assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
555 "EnumerateValue doesn't handle Metadata!");
557 // Check to see if it's already in!
558 unsigned &ValueID = ValueMap[V];
560 // Increment use count.
561 Values[ValueID-1].second++;
565 if (auto *GO = dyn_cast<GlobalObject>(V))
566 if (const Comdat *C = GO->getComdat())
569 // Enumerate the type of this value.
570 EnumerateType(V->getType());
572 if (const Constant *C = dyn_cast<Constant>(V)) {
573 if (isa<GlobalValue>(C)) {
574 // Initializers for globals are handled explicitly elsewhere.
575 } else if (C->getNumOperands()) {
576 // If a constant has operands, enumerate them. This makes sure that if a
577 // constant has uses (for example an array of const ints), that they are
580 // We prefer to enumerate them with values before we enumerate the user
581 // itself. This makes it more likely that we can avoid forward references
582 // in the reader. We know that there can be no cycles in the constants
583 // graph that don't go through a global variable.
584 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
586 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
589 // Finally, add the value. Doing this could make the ValueID reference be
590 // dangling, don't reuse it.
591 Values.push_back(std::make_pair(V, 1U));
592 ValueMap[V] = Values.size();
598 Values.push_back(std::make_pair(V, 1U));
599 ValueID = Values.size();
603 void ValueEnumerator::EnumerateType(Type *Ty) {
604 unsigned *TypeID = &TypeMap[Ty];
606 // We've already seen this type.
610 // If it is a non-anonymous struct, mark the type as being visited so that we
611 // don't recursively visit it. This is safe because we allow forward
612 // references of these in the bitcode reader.
613 if (StructType *STy = dyn_cast<StructType>(Ty))
614 if (!STy->isLiteral())
617 // Enumerate all of the subtypes before we enumerate this type. This ensures
618 // that the type will be enumerated in an order that can be directly built.
619 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
623 // Refresh the TypeID pointer in case the table rehashed.
624 TypeID = &TypeMap[Ty];
626 // Check to see if we got the pointer another way. This can happen when
627 // enumerating recursive types that hit the base case deeper than they start.
629 // If this is actually a struct that we are treating as forward ref'able,
630 // then emit the definition now that all of its contents are available.
631 if (*TypeID && *TypeID != ~0U)
634 // Add this type now that its contents are all happily enumerated.
637 *TypeID = Types.size();
640 // Enumerate the types for the specified value. If the value is a constant,
641 // walk through it, enumerating the types of the constant.
642 void ValueEnumerator::EnumerateOperandType(const Value *V) {
643 EnumerateType(V->getType());
645 if (const Constant *C = dyn_cast<Constant>(V)) {
646 // If this constant is already enumerated, ignore it, we know its type must
648 if (ValueMap.count(V)) return;
650 // This constant may have operands, make sure to enumerate the types in
652 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
653 const Value *Op = C->getOperand(i);
655 // Don't enumerate basic blocks here, this happens as operands to
657 if (isa<BasicBlock>(Op)) continue;
659 EnumerateOperandType(Op);
662 if (const MDNode *N = dyn_cast<MDNode>(V)) {
663 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
664 if (Value *Elem = N->getOperand(i))
665 EnumerateOperandType(Elem);
667 } else if (isa<MDString>(V) || isa<MDNode>(V))
668 EnumerateMetadata(V);
671 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
672 if (PAL.isEmpty()) return; // null is always 0.
675 unsigned &Entry = AttributeMap[PAL];
677 // Never saw this before, add it.
678 Attribute.push_back(PAL);
679 Entry = Attribute.size();
682 // Do lookups for all attribute groups.
683 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
684 AttributeSet AS = PAL.getSlotAttributes(i);
685 unsigned &Entry = AttributeGroupMap[AS];
687 AttributeGroups.push_back(AS);
688 Entry = AttributeGroups.size();
693 void ValueEnumerator::incorporateFunction(const Function &F) {
694 InstructionCount = 0;
695 NumModuleValues = Values.size();
696 NumModuleMDValues = MDValues.size();
698 // Adding function arguments to the value table.
699 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
703 FirstFuncConstantID = Values.size();
705 // Add all function-level constants to the value table.
706 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
707 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
708 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
710 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
714 BasicBlocks.push_back(BB);
715 ValueMap[BB] = BasicBlocks.size();
718 // Optimize the constant layout.
719 OptimizeConstants(FirstFuncConstantID, Values.size());
721 // Add the function's parameter attributes so they are available for use in
722 // the function's instruction.
723 EnumerateAttributes(F.getAttributes());
725 FirstInstID = Values.size();
727 SmallVector<MDNode *, 8> FnLocalMDVector;
728 // Add all of the instructions.
729 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
730 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
731 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
733 if (MDNode *MD = dyn_cast<MDNode>(*OI))
734 if (MD->isFunctionLocal() && MD->getFunction())
735 // Enumerate metadata after the instructions they might refer to.
736 FnLocalMDVector.push_back(MD);
739 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
740 I->getAllMetadataOtherThanDebugLoc(MDs);
741 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
742 MDNode *N = MDs[i].second;
743 if (N->isFunctionLocal() && N->getFunction())
744 FnLocalMDVector.push_back(N);
747 if (!I->getType()->isVoidTy())
752 // Add all of the function-local metadata.
753 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
754 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
757 void ValueEnumerator::purgeFunction() {
758 /// Remove purged values from the ValueMap.
759 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
760 ValueMap.erase(Values[i].first);
761 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
762 MDValueMap.erase(MDValues[i].first);
763 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
764 ValueMap.erase(BasicBlocks[i]);
766 Values.resize(NumModuleValues);
767 MDValues.resize(NumModuleMDValues);
769 FunctionLocalMDs.clear();
772 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
773 DenseMap<const BasicBlock*, unsigned> &IDMap) {
774 unsigned Counter = 0;
775 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
776 IDMap[BB] = ++Counter;
779 /// getGlobalBasicBlockID - This returns the function-specific ID for the
780 /// specified basic block. This is relatively expensive information, so it
781 /// should only be used by rare constructs such as address-of-label.
782 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
783 unsigned &Idx = GlobalBasicBlockIDs[BB];
787 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
788 return getGlobalBasicBlockID(BB);