1 //===-- PoolAllocate.cpp - Pool Allocation Pass ---------------------------===//
3 // This transform changes programs so that disjoint data structures are
4 // allocated out of different pools of memory, increasing locality.
6 //===----------------------------------------------------------------------===//
8 #define DEBUG_TYPE "PoolAllocation"
9 #include "llvm/Transforms/PoolAllocate.h"
10 #include "llvm/Transforms/Utils/Cloning.h"
11 #include "llvm/Analysis/DataStructure.h"
12 #include "llvm/Analysis/DSGraph.h"
13 #include "llvm/Module.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Target/TargetData.h"
18 #include "llvm/Support/InstVisitor.h"
19 #include "Support/Debug.h"
20 #include "Support/VectorExtras.h"
24 const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
26 // The type to allocate for a pool descriptor: { sbyte*, uint, uint }
27 // void *Data (the data)
28 // unsigned NodeSize (size of an allocated node)
29 // unsigned FreeablePool (are slabs in the pool freeable upon calls to
31 const Type *PoolDescType =
32 StructType::get(make_vector<const Type*>(VoidPtrTy, Type::UIntTy,
35 const PointerType *PoolDescPtr = PointerType::get(PoolDescType);
37 RegisterOpt<PoolAllocate>
38 X("poolalloc", "Pool allocate disjoint data structures");
41 void PoolAllocate::getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<BUDataStructures>();
43 AU.addRequired<TDDataStructures>();
44 AU.addRequired<TargetData>();
47 // Prints out the functions mapped to the leader of the equivalence class they
49 void PoolAllocate::printFuncECs() {
50 std::map<Function*, Function*> &leaderMap = FuncECs.getLeaderMap();
51 std::cerr << "Indirect Function Map \n";
52 for (std::map<Function*, Function*>::iterator LI = leaderMap.begin(),
53 LE = leaderMap.end(); LI != LE; ++LI) {
54 std::cerr << LI->first->getName() << ": leader is "
55 << LI->second->getName() << "\n";
59 static void printNTOMap(std::map<Value*, const Value*> &NTOM) {
60 std::cerr << "NTOM MAP\n";
61 for (std::map<Value*, const Value *>::iterator I = NTOM.begin(),
62 E = NTOM.end(); I != E; ++I) {
63 if (!isa<Function>(I->first) && !isa<BasicBlock>(I->first))
64 std::cerr << *I->first << " to " << *I->second << "\n";
68 void PoolAllocate::buildIndirectFunctionSets(Module &M) {
69 // Iterate over the module looking for indirect calls to functions
71 // Get top down DSGraph for the functions
72 TDDS = &getAnalysis<TDDataStructures>();
74 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI) {
76 DEBUG(std::cerr << "Processing indirect calls function:" << MI->getName() << "\n");
81 DSGraph &TDG = TDDS->getDSGraph(*MI);
83 std::vector<DSCallSite> callSites = TDG.getFunctionCalls();
85 // For each call site in the function
86 // All the functions that can be called at the call site are put in the
87 // same equivalence class.
88 for (std::vector<DSCallSite>::iterator CSI = callSites.begin(),
89 CSE = callSites.end(); CSI != CSE ; ++CSI) {
90 if (CSI->isIndirectCall()) {
91 DSNode *DSN = CSI->getCalleeNode();
92 if (DSN->isIncomplete())
93 std::cerr << "Incomplete node " << CSI->getCallInst();
94 // assert(DSN->isGlobalNode());
95 const std::vector<GlobalValue*> &Callees = DSN->getGlobals();
96 if (Callees.size() > 0) {
97 Function *firstCalledF = dyn_cast<Function>(*Callees.begin());
98 FuncECs.addElement(firstCalledF);
99 CallInstTargets.insert(std::pair<CallInst*,Function*>
100 (&CSI->getCallInst(),
102 if (Callees.size() > 1) {
103 for (std::vector<GlobalValue*>::const_iterator CalleesI =
104 Callees.begin()+1, CalleesE = Callees.end();
105 CalleesI != CalleesE; ++CalleesI) {
106 Function *calledF = dyn_cast<Function>(*CalleesI);
107 FuncECs.unionSetsWith(firstCalledF, calledF);
108 CallInstTargets.insert(std::pair<CallInst*,Function*>
109 (&CSI->getCallInst(), calledF));
113 std::cerr << "No targets " << CSI->getCallInst();
119 // Print the equivalence classes
120 DEBUG(printFuncECs());
123 bool PoolAllocate::run(Module &M) {
124 if (M.begin() == M.end()) return false;
128 BU = &getAnalysis<BUDataStructures>();
130 buildIndirectFunctionSets(M);
132 std::map<Function*, Function*> FuncMap;
134 // Loop over the functions in the original program finding the pool desc.
135 // arguments necessary for each function that is indirectly callable.
136 // For each equivalence class, make a list of pool arguments and update
137 // the PoolArgFirst and PoolArgLast values for each function.
138 Module::iterator LastOrigFunction = --M.end();
139 for (Module::iterator I = M.begin(); ; ++I) {
140 if (!I->isExternal())
141 FindFunctionPoolArgs(*I);
142 if (I == LastOrigFunction) break;
145 // Now clone a function using the pool arg list obtained in the previous
146 // pass over the modules.
147 // Loop over only the function initially in the program, don't traverse newly
148 // added ones. If the function uses memory, make its clone.
149 for (Module::iterator I = M.begin(); ; ++I) {
150 if (!I->isExternal())
151 if (Function *R = MakeFunctionClone(*I))
153 if (I == LastOrigFunction) break;
158 // Now that all call targets are available, rewrite the function bodies of the
160 for (Module::iterator I = M.begin(); I != LastOrigFunction; ++I)
161 if (!I->isExternal()) {
162 std::map<Function*, Function*>::iterator FI = FuncMap.find(I);
163 ProcessFunctionBody(*I, FI != FuncMap.end() ? *FI->second : *I);
170 // AddPoolPrototypes - Add prototypes for the pool functions to the specified
171 // module and update the Pool* instance variables to point to them.
173 void PoolAllocate::AddPoolPrototypes() {
174 CurModule->addTypeName("PoolDescriptor", PoolDescType);
176 // Get poolinit function...
177 FunctionType *PoolInitTy =
178 FunctionType::get(Type::VoidTy,
179 make_vector<const Type*>(PoolDescPtr, Type::UIntTy, 0),
181 PoolInit = CurModule->getOrInsertFunction("poolinit", PoolInitTy);
183 // Get pooldestroy function...
184 std::vector<const Type*> PDArgs(1, PoolDescPtr);
185 FunctionType *PoolDestroyTy =
186 FunctionType::get(Type::VoidTy, PDArgs, false);
187 PoolDestroy = CurModule->getOrInsertFunction("pooldestroy", PoolDestroyTy);
189 // Get the poolalloc function...
190 FunctionType *PoolAllocTy = FunctionType::get(VoidPtrTy, PDArgs, false);
191 PoolAlloc = CurModule->getOrInsertFunction("poolalloc", PoolAllocTy);
193 // Get the poolfree function...
194 PDArgs.push_back(VoidPtrTy); // Pointer to free
195 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, PDArgs, false);
196 PoolFree = CurModule->getOrInsertFunction("poolfree", PoolFreeTy);
198 // The poolallocarray function
199 FunctionType *PoolAllocArrayTy =
200 FunctionType::get(VoidPtrTy,
201 make_vector<const Type*>(PoolDescPtr, Type::UIntTy, 0),
203 PoolAllocArray = CurModule->getOrInsertFunction("poolallocarray",
208 // Inline the DSGraphs of functions corresponding to the potential targets at
209 // indirect call sites into the DS Graph of the callee.
210 // This is required to know what pools to create/pass at the call site in the
213 void PoolAllocate::InlineIndirectCalls(Function &F, DSGraph &G,
214 hash_set<Function*> &visited) {
215 std::vector<DSCallSite> callSites = G.getFunctionCalls();
219 // For each indirect call site in the function, inline all the potential
221 for (std::vector<DSCallSite>::iterator CSI = callSites.begin(),
222 CSE = callSites.end(); CSI != CSE; ++CSI) {
223 if (CSI->isIndirectCall()) {
224 CallInst &CI = CSI->getCallInst();
225 std::pair<std::multimap<CallInst*, Function*>::iterator,
226 std::multimap<CallInst*, Function*>::iterator> Targets =
227 CallInstTargets.equal_range(&CI);
228 for (std::multimap<CallInst*, Function*>::iterator TFI = Targets.first,
229 TFE = Targets.second; TFI != TFE; ++TFI) {
230 DSGraph &TargetG = BU->getDSGraph(*TFI->second);
231 // Call the function recursively if the callee is not yet inlined
232 // and if it hasn't been visited in this sequence of calls
233 // The latter is dependent on the fact that the graphs of all functions
234 // in an SCC are actually the same
235 if (InlinedFuncs.find(TFI->second) == InlinedFuncs.end() &&
236 visited.find(TFI->second) == visited.end()) {
237 InlineIndirectCalls(*TFI->second, TargetG, visited);
239 G.mergeInGraph(*CSI, *TFI->second, TargetG, DSGraph::KeepModRefBits |
240 DSGraph::KeepAllocaBit | DSGraph::DontCloneCallNodes |
241 DSGraph::DontCloneAuxCallNodes);
246 // Mark this function as one whose graph is inlined with its indirect
247 // function targets' DS Graphs. This ensures that every function is inlined
249 InlinedFuncs.insert(&F);
252 void PoolAllocate::FindFunctionPoolArgs(Function &F) {
254 // The DSGraph is merged with the globals graph.
255 DSGraph &G = BU->getDSGraph(F);
256 G.mergeInGlobalsGraph();
258 // Inline the potential targets of indirect calls
259 hash_set<Function*> visitedFuncs;
260 InlineIndirectCalls(F, G, visitedFuncs);
262 // At this point the DS Graphs have been modified in place including
263 // information about globals as well as indirect calls, making it useful
264 // for pool allocation
265 std::vector<DSNode*> &Nodes = G.getNodes();
266 if (Nodes.empty()) return ; // No memory activity, nothing is required
268 FuncInfo &FI = FunctionInfo[&F]; // Create a new entry for F
272 // Initialize the PoolArgFirst and PoolArgLast for the function depending
273 // on whether there have been other functions in the equivalence class
274 // that have pool arguments so far in the analysis.
275 if (!FuncECs.findClass(&F)) {
276 FI.PoolArgFirst = FI.PoolArgLast = 0;
278 if (EqClass2LastPoolArg.find(FuncECs.findClass(&F)) !=
279 EqClass2LastPoolArg.end())
280 FI.PoolArgFirst = FI.PoolArgLast =
281 EqClass2LastPoolArg[FuncECs.findClass(&F)] + 1;
283 FI.PoolArgFirst = FI.PoolArgLast = 0;
286 // Find DataStructure nodes which are allocated in pools non-local to the
287 // current function. This set will contain all of the DSNodes which require
288 // pools to be passed in from outside of the function.
289 hash_set<DSNode*> &MarkedNodes = FI.MarkedNodes;
291 // Mark globals and incomplete nodes as live... (this handles arguments)
292 if (F.getName() != "main")
293 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
294 if (Nodes[i]->isGlobalNode() && !Nodes[i]->isIncomplete())
295 DEBUG(std::cerr << "Global node is not Incomplete\n");
296 if ((Nodes[i]->isIncomplete() || Nodes[i]->isGlobalNode()) &&
297 Nodes[i]->isHeapNode())
298 Nodes[i]->markReachableNodes(MarkedNodes);
301 // Marked the returned node as alive...
302 if (DSNode *RetNode = G.getReturnNodeFor(F).getNode())
303 if (RetNode->isHeapNode())
304 RetNode->markReachableNodes(MarkedNodes);
306 if (MarkedNodes.empty()) // We don't need to clone the function if there
307 return; // are no incoming arguments to be added.
309 // Erase any marked node that is not a heap node
311 for (hash_set<DSNode*>::iterator I = MarkedNodes.begin(),
312 E = MarkedNodes.end(); I != E; ) {
313 // erase invalidates hash_set iterators if the iterator points to the
314 // element being erased
315 if (!(*I)->isHeapNode())
316 MarkedNodes.erase(I++);
321 FI.PoolArgLast += MarkedNodes.size();
324 if (FuncECs.findClass(&F)) {
325 // Update the equivalence class last pool argument information
326 // only if there actually were pool arguments to the function.
327 // Also, there is no entry for the Eq. class in EqClass2LastPoolArg
328 // if there are no functions in the equivalence class with pool arguments.
329 if (FI.PoolArgLast != FI.PoolArgFirst)
330 EqClass2LastPoolArg[FuncECs.findClass(&F)] = FI.PoolArgLast - 1;
335 // MakeFunctionClone - If the specified function needs to be modified for pool
336 // allocation support, make a clone of it, adding additional arguments as
337 // neccesary, and return it. If not, just return null.
339 Function *PoolAllocate::MakeFunctionClone(Function &F) {
341 DSGraph &G = BU->getDSGraph(F);
343 std::vector<DSNode*> &Nodes = G.getNodes();
347 FuncInfo &FI = FunctionInfo[&F];
349 hash_set<DSNode*> &MarkedNodes = FI.MarkedNodes;
351 if (!FuncECs.findClass(&F)) {
352 // Not in any equivalence class
353 if (MarkedNodes.empty())
356 // No need to clone if there are no pool arguments in any function in the
358 if (!EqClass2LastPoolArg.count(FuncECs.findClass(&F)))
362 // Figure out what the arguments are to be for the new version of the function
363 const FunctionType *OldFuncTy = F.getFunctionType();
364 std::vector<const Type*> ArgTys;
365 if (!FuncECs.findClass(&F)) {
366 ArgTys.reserve(OldFuncTy->getParamTypes().size() + MarkedNodes.size());
367 FI.ArgNodes.reserve(MarkedNodes.size());
368 for (hash_set<DSNode*>::iterator I = MarkedNodes.begin(),
369 E = MarkedNodes.end(); I != E; ++I) {
370 ArgTys.push_back(PoolDescPtr); // Add the appropriate # of pool descs
371 FI.ArgNodes.push_back(*I);
373 if (FI.ArgNodes.empty()) return 0; // No nodes to be pool allocated!
377 // This function is a member of an equivalence class and needs to be cloned
378 ArgTys.reserve(OldFuncTy->getParamTypes().size() +
379 EqClass2LastPoolArg[FuncECs.findClass(&F)] + 1);
380 FI.ArgNodes.reserve(EqClass2LastPoolArg[FuncECs.findClass(&F)] + 1);
382 for (int i = 0; i <= EqClass2LastPoolArg[FuncECs.findClass(&F)]; ++i) {
383 ArgTys.push_back(PoolDescPtr); // Add the appropriate # of pool
387 for (hash_set<DSNode*>::iterator I = MarkedNodes.begin(),
388 E = MarkedNodes.end(); I != E; ++I) {
389 FI.ArgNodes.push_back(*I);
392 assert ((FI.ArgNodes.size() == (unsigned) (FI.PoolArgLast -
394 "Number of ArgNodes equal to the number of pool arguments used by this function");
398 ArgTys.insert(ArgTys.end(), OldFuncTy->getParamTypes().begin(),
399 OldFuncTy->getParamTypes().end());
402 // Create the new function prototype
403 FunctionType *FuncTy = FunctionType::get(OldFuncTy->getReturnType(), ArgTys,
404 OldFuncTy->isVarArg());
405 // Create the new function...
406 Function *New = new Function(FuncTy, GlobalValue::InternalLinkage,
407 F.getName(), F.getParent());
409 // Set the rest of the new arguments names to be PDa<n> and add entries to the
410 // pool descriptors map
411 std::map<DSNode*, Value*> &PoolDescriptors = FI.PoolDescriptors;
412 Function::aiterator NI = New->abegin();
414 if (FuncECs.findClass(&F)) {
415 for (int i = 0; i <= EqClass2LastPoolArg[FuncECs.findClass(&F)]; ++i,
420 if (FI.PoolArgFirst > 0)
421 for (int i = 0; i < FI.PoolArgFirst; ++NI, ++i)
424 if (FI.ArgNodes.size() > 0)
425 for (unsigned i = 0, e = FI.ArgNodes.size(); i != e; ++i, ++NI)
426 PoolDescriptors.insert(std::make_pair(FI.ArgNodes[i], NI));
429 if (EqClass2LastPoolArg.count(FuncECs.findClass(&F)))
430 for (int i = 0; i <= EqClass2LastPoolArg[FuncECs.findClass(&F)]; ++i, ++NI)
433 if (FI.ArgNodes.size())
434 for (unsigned i = 0, e = FI.ArgNodes.size(); i != e; ++i, ++NI) {
435 NI->setName("PDa"); // Add pd entry
436 PoolDescriptors.insert(std::make_pair(FI.ArgNodes[i], NI));
439 if (FI.ArgNodes.size())
440 for (unsigned i = 0; i < FI.ArgNodes.size(); ++NI, ++i)
444 // Map the existing arguments of the old function to the corresponding
445 // arguments of the new function.
446 std::map<const Value*, Value*> ValueMap;
447 if (NI != New->aend())
448 for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++NI) {
450 NI->setName(I->getName());
453 // Populate the value map with all of the globals in the program.
454 // FIXME: This should be unneccesary!
455 Module &M = *F.getParent();
456 for (Module::iterator I = M.begin(), E=M.end(); I!=E; ++I) ValueMap[I] = I;
457 for (Module::giterator I = M.gbegin(), E=M.gend(); I!=E; ++I) ValueMap[I] = I;
459 // Perform the cloning.
460 std::vector<ReturnInst*> Returns;
461 CloneFunctionInto(New, &F, ValueMap, Returns);
463 // Invert the ValueMap into the NewToOldValueMap
464 std::map<Value*, const Value*> &NewToOldValueMap = FI.NewToOldValueMap;
465 for (std::map<const Value*, Value*>::iterator I = ValueMap.begin(),
466 E = ValueMap.end(); I != E; ++I)
467 NewToOldValueMap.insert(std::make_pair(I->second, I->first));
469 return FI.Clone = New;
473 // processFunction - Pool allocate any data structures which are contained in
474 // the specified function...
476 void PoolAllocate::ProcessFunctionBody(Function &F, Function &NewF) {
477 DSGraph &G = BU->getDSGraph(F);
479 std::vector<DSNode*> &Nodes = G.getNodes();
480 if (Nodes.empty()) return; // Quick exit if nothing to do...
482 FuncInfo &FI = FunctionInfo[&F]; // Get FuncInfo for F
483 hash_set<DSNode*> &MarkedNodes = FI.MarkedNodes;
485 DEBUG(std::cerr << "[" << F.getName() << "] Pool Allocate: ");
487 // Loop over all of the nodes which are non-escaping, adding pool-allocatable
488 // ones to the NodesToPA vector.
489 std::vector<DSNode*> NodesToPA;
490 for (unsigned i = 0, e = Nodes.size(); i != e; ++i)
491 if (Nodes[i]->isHeapNode() && // Pick nodes with heap elems
492 !MarkedNodes.count(Nodes[i])) // Can't be marked
493 NodesToPA.push_back(Nodes[i]);
495 DEBUG(std::cerr << NodesToPA.size() << " nodes to pool allocate\n");
496 if (!NodesToPA.empty()) {
497 // Create pool construction/destruction code
498 std::map<DSNode*, Value*> &PoolDescriptors = FI.PoolDescriptors;
499 CreatePools(NewF, NodesToPA, PoolDescriptors);
502 // Transform the body of the function now...
503 TransformFunctionBody(NewF, F, G, FI);
507 // CreatePools - This creates the pool initialization and destruction code for
508 // the DSNodes specified by the NodesToPA list. This adds an entry to the
509 // PoolDescriptors map for each DSNode.
511 void PoolAllocate::CreatePools(Function &F,
512 const std::vector<DSNode*> &NodesToPA,
513 std::map<DSNode*, Value*> &PoolDescriptors) {
514 // Find all of the return nodes in the CFG...
515 std::vector<BasicBlock*> ReturnNodes;
516 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
517 if (isa<ReturnInst>(I->getTerminator()))
518 ReturnNodes.push_back(I);
520 TargetData &TD = getAnalysis<TargetData>();
522 // Loop over all of the pools, inserting code into the entry block of the
523 // function for the initialization and code in the exit blocks for
526 Instruction *InsertPoint = F.front().begin();
527 for (unsigned i = 0, e = NodesToPA.size(); i != e; ++i) {
528 DSNode *Node = NodesToPA[i];
530 // Create a new alloca instruction for the pool...
531 Value *AI = new AllocaInst(PoolDescType, 0, "PD", InsertPoint);
535 // Void types in DS graph are never used
536 if (Node->getType() != Type::VoidTy)
537 ElSize = ConstantUInt::get(Type::UIntTy, TD.getTypeSize(Node->getType()));
539 std::cerr << "Potential node collapsing in " << F.getName() << "\n";
540 ElSize = ConstantUInt::get(Type::UIntTy, 0);
543 // Insert the call to initialize the pool...
544 new CallInst(PoolInit, make_vector(AI, ElSize, 0), "", InsertPoint);
546 // Update the PoolDescriptors map
547 PoolDescriptors.insert(std::make_pair(Node, AI));
549 // Insert a call to pool destroy before each return inst in the function
550 for (unsigned r = 0, e = ReturnNodes.size(); r != e; ++r)
551 new CallInst(PoolDestroy, make_vector(AI, 0), "",
552 ReturnNodes[r]->getTerminator());
558 /// FuncTransform - This class implements transformation required of pool
559 /// allocated functions.
560 struct FuncTransform : public InstVisitor<FuncTransform> {
561 PoolAllocate &PAInfo;
562 DSGraph &G; // The Bottom-up DS Graph
563 DSGraph &TDG; // The Top-down DS Graph
566 FuncTransform(PoolAllocate &P, DSGraph &g, DSGraph &tdg, FuncInfo &fi)
567 : PAInfo(P), G(g), TDG(tdg), FI(fi) {
570 void visitMallocInst(MallocInst &MI);
571 void visitFreeInst(FreeInst &FI);
572 void visitCallInst(CallInst &CI);
574 // The following instructions are never modified by pool allocation
575 void visitBranchInst(BranchInst &I) { }
576 void visitBinaryOperator(Instruction &I) { }
577 void visitShiftInst (ShiftInst &I) { }
578 void visitSwitchInst (SwitchInst &I) { }
579 void visitCastInst (CastInst &I) { }
580 void visitAllocaInst(AllocaInst &I) { }
581 void visitLoadInst(LoadInst &I) { }
582 void visitGetElementPtrInst (GetElementPtrInst &I) { }
584 void visitReturnInst(ReturnInst &I);
585 void visitStoreInst (StoreInst &I);
586 void visitPHINode(PHINode &I);
588 void visitInstruction(Instruction &I) {
589 std::cerr << "PoolAllocate does not recognize this instruction\n";
594 DSNodeHandle& getDSNodeHFor(Value *V) {
595 // if (isa<Constant>(V))
596 // return DSNodeHandle();
598 if (!FI.NewToOldValueMap.empty()) {
599 // If the NewToOldValueMap is in effect, use it.
600 std::map<Value*,const Value*>::iterator I = FI.NewToOldValueMap.find(V);
601 if (I != FI.NewToOldValueMap.end())
602 V = (Value*)I->second;
605 return G.getScalarMap()[V];
608 Value *getPoolHandle(Value *V) {
609 DSNode *Node = getDSNodeHFor(V).getNode();
610 // Get the pool handle for this DSNode...
611 std::map<DSNode*, Value*>::iterator I = FI.PoolDescriptors.find(Node);
612 return I != FI.PoolDescriptors.end() ? I->second : 0;
615 bool isFuncPtr(Value *V);
617 Function* getFuncClass(Value *V);
619 Value* retCloneIfFunc(Value *V);
623 void PoolAllocate::TransformFunctionBody(Function &F, Function &OldF,
624 DSGraph &G, FuncInfo &FI) {
625 FuncTransform(*this, G, TDDS->getDSGraph(OldF), FI).visit(F);
628 // Returns true if V is a function pointer
629 bool FuncTransform::isFuncPtr(Value *V) {
630 if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
631 return isa<FunctionType>(PTy->getElementType());
635 // Given a function pointer, return the function eq. class if one exists
636 Function* FuncTransform::getFuncClass(Value *V) {
637 // Look at DSGraph and see if the set of of functions it could point to
638 // are pool allocated.
644 // if V is a constant
645 if (Function *theFunc = dyn_cast<Function>(V)) {
646 if (!PAInfo.FuncECs.findClass(theFunc))
647 // If this function does not belong to any equivalence class
649 if (PAInfo.EqClass2LastPoolArg.count(PAInfo.FuncECs.findClass(theFunc)))
650 return PAInfo.FuncECs.findClass(theFunc);
655 // if V is not a constant
656 DSNode *DSN = TDG.getNodeForValue(V).getNode();
660 const std::vector<GlobalValue*> &Callees = DSN->getGlobals();
661 if (Callees.size() > 0) {
662 Function *calledF = dyn_cast<Function>(*Callees.begin());
663 assert(PAInfo.FuncECs.findClass(calledF) && "should exist in some eq. class");
664 if (PAInfo.EqClass2LastPoolArg.count(PAInfo.FuncECs.findClass(calledF)))
665 return PAInfo.FuncECs.findClass(calledF);
671 // Returns the clone if V is a static function (not a pointer) and belongs
672 // to an equivalence class i.e. is pool allocated
673 Value* FuncTransform::retCloneIfFunc(Value *V) {
674 if (Function *fixedFunc = dyn_cast<Function>(V))
676 return PAInfo.getFuncInfo(*fixedFunc)->Clone;
681 void FuncTransform::visitReturnInst (ReturnInst &RI) {
682 if (RI.getNumOperands())
683 if (Value *clonedFunc = retCloneIfFunc(RI.getOperand(0))) {
684 // Cast the clone of RI.getOperand(0) to the non-pool-allocated type
685 CastInst *CastI = new CastInst(clonedFunc, RI.getOperand(0)->getType(),
687 // Insert return instruction that returns the casted value
688 ReturnInst *RetI = new ReturnInst(CastI, &RI);
690 // Remove original return instruction
691 RI.getParent()->getInstList().erase(&RI);
693 if (!FI.NewToOldValueMap.empty()) {
694 std::map<Value*,const Value*>::iterator II =
695 FI.NewToOldValueMap.find(&RI);
696 assert(II != FI.NewToOldValueMap.end() &&
697 "RI not found in clone?");
698 FI.NewToOldValueMap.insert(std::make_pair(RetI, II->second));
699 FI.NewToOldValueMap.erase(II);
704 void FuncTransform::visitStoreInst (StoreInst &SI) {
705 // Check if a constant function is being stored
706 if (Value *clonedFunc = retCloneIfFunc(SI.getOperand(0))) {
707 CastInst *CastI = new CastInst(clonedFunc, SI.getOperand(0)->getType(),
709 StoreInst *StoreI = new StoreInst(CastI, SI.getOperand(1), &SI);
710 SI.getParent()->getInstList().erase(&SI);
712 // Update the NewToOldValueMap if this is a clone
713 if (!FI.NewToOldValueMap.empty()) {
714 std::map<Value*,const Value*>::iterator II =
715 FI.NewToOldValueMap.find(&SI);
716 assert(II != FI.NewToOldValueMap.end() &&
717 "SI not found in clone?");
718 FI.NewToOldValueMap.insert(std::make_pair(StoreI, II->second));
719 FI.NewToOldValueMap.erase(II);
724 void FuncTransform::visitPHINode(PHINode &PI) {
725 // If any of the operands of the PHI node is a constant function pointer
726 // that is cloned, the cast instruction has to be inserted at the end of the
727 // previous basic block
729 if (isFuncPtr(&PI)) {
730 PHINode *V = new PHINode(PI.getType(), PI.getName(), &PI);
731 for (unsigned i = 0 ; i < PI.getNumIncomingValues(); ++i) {
732 if (Value *clonedFunc = retCloneIfFunc(PI.getIncomingValue(i))) {
733 // Insert CastInst at the end of PI.getIncomingBlock(i)
734 BasicBlock::iterator BBI = --PI.getIncomingBlock(i)->end();
735 // BBI now points to the terminator instruction of the basic block.
736 CastInst *CastI = new CastInst(clonedFunc, PI.getType(), "tmp", BBI);
737 V->addIncoming(CastI, PI.getIncomingBlock(i));
739 V->addIncoming(PI.getIncomingValue(i), PI.getIncomingBlock(i));
743 PI.replaceAllUsesWith(V);
744 PI.getParent()->getInstList().erase(&PI);
746 DSGraph::ScalarMapTy &SM = G.getScalarMap();
747 DSGraph::ScalarMapTy::iterator PII = SM.find(&PI);
749 // Update Scalar map of DSGraph if this is one of the original functions
750 // Otherwise update the NewToOldValueMap
751 if (PII != SM.end()) {
752 SM.insert(std::make_pair(V, PII->second));
753 SM.erase(PII); // Destroy the PHINode
755 std::map<Value*,const Value*>::iterator II =
756 FI.NewToOldValueMap.find(&PI);
757 assert(II != FI.NewToOldValueMap.end() &&
758 "PhiI not found in clone?");
759 FI.NewToOldValueMap.insert(std::make_pair(V, II->second));
760 FI.NewToOldValueMap.erase(II);
765 void FuncTransform::visitMallocInst(MallocInst &MI) {
766 // Get the pool handle for the node that this contributes to...
767 Value *PH = getPoolHandle(&MI);
770 // Insert a call to poolalloc
772 if (MI.isArrayAllocation())
773 V = new CallInst(PAInfo.PoolAllocArray,
774 make_vector(PH, MI.getOperand(0), 0),
777 V = new CallInst(PAInfo.PoolAlloc, make_vector(PH, 0),
780 MI.setName(""); // Nuke MIs name
784 // Cast to the appropriate type if necessary
785 if (V->getType() != MI.getType()) {
786 Casted = new CastInst(V, MI.getType(), V->getName(), &MI);
789 // Update def-use info
790 MI.replaceAllUsesWith(Casted);
792 // Remove old malloc instruction
793 MI.getParent()->getInstList().erase(&MI);
795 DSGraph::ScalarMapTy &SM = G.getScalarMap();
796 DSGraph::ScalarMapTy::iterator MII = SM.find(&MI);
798 // If we are modifying the original function, update the DSGraph...
799 if (MII != SM.end()) {
800 // V and Casted now point to whatever the original malloc did...
801 SM.insert(std::make_pair(V, MII->second));
803 SM.insert(std::make_pair(Casted, MII->second));
804 SM.erase(MII); // The malloc is now destroyed
805 } else { // Otherwise, update the NewToOldValueMap
806 std::map<Value*,const Value*>::iterator MII =
807 FI.NewToOldValueMap.find(&MI);
808 assert(MII != FI.NewToOldValueMap.end() && "MI not found in clone?");
809 FI.NewToOldValueMap.insert(std::make_pair(V, MII->second));
811 FI.NewToOldValueMap.insert(std::make_pair(Casted, MII->second));
812 FI.NewToOldValueMap.erase(MII);
816 void FuncTransform::visitFreeInst(FreeInst &FrI) {
817 Value *Arg = FrI.getOperand(0);
818 Value *PH = getPoolHandle(Arg); // Get the pool handle for this DSNode...
820 // Insert a cast and a call to poolfree...
822 if (Arg->getType() != PointerType::get(Type::SByteTy))
823 Casted = new CastInst(Arg, PointerType::get(Type::SByteTy),
824 Arg->getName()+".casted", &FrI);
826 CallInst *FreeI = new CallInst(PAInfo.PoolFree, make_vector(PH, Casted, 0),
828 // Delete the now obsolete free instruction...
829 FrI.getParent()->getInstList().erase(&FrI);
831 // Update the NewToOldValueMap if this is a clone
832 if (!FI.NewToOldValueMap.empty()) {
833 std::map<Value*,const Value*>::iterator II =
834 FI.NewToOldValueMap.find(&FrI);
835 assert(II != FI.NewToOldValueMap.end() &&
836 "FrI not found in clone?");
837 FI.NewToOldValueMap.insert(std::make_pair(FreeI, II->second));
838 FI.NewToOldValueMap.erase(II);
842 static void CalcNodeMapping(DSNodeHandle& Caller, DSNodeHandle& Callee,
843 std::map<DSNode*, DSNode*> &NodeMapping) {
844 DSNode *CalleeNode = Callee.getNode();
845 DSNode *CallerNode = Caller.getNode();
847 unsigned CalleeOffset = Callee.getOffset();
848 unsigned CallerOffset = Caller.getOffset();
850 if (CalleeNode == 0) return;
852 // If callee has a node and caller doesn't, then a constant argument was
853 // passed by the caller
854 if (CallerNode == 0) {
855 NodeMapping.insert(NodeMapping.end(), std::make_pair(CalleeNode,
859 // Map the callee node to the caller node.
860 // NB: The callee node could be of a different type. Eg. if it points to the
861 // field of a struct that the caller points to
862 std::map<DSNode*, DSNode*>::iterator I = NodeMapping.find(CalleeNode);
863 if (I != NodeMapping.end()) { // Node already in map...
864 assert(I->second == CallerNode &&
865 "Node maps to different nodes on paths?");
867 NodeMapping.insert(I, std::make_pair(CalleeNode, CallerNode));
869 if (CalleeNode->getType() != CallerNode->getType() && CallerOffset == 0)
870 DEBUG(std::cerr << "NB: Mapping of nodes between different types\n");
872 // Recursively map the callee links to the caller links starting from the
873 // offset in the node into which they are mapped.
874 // Being a BU Graph, the callee ought to have smaller number of links unless
875 // there is collapsing in the caller
876 unsigned numCallerLinks = CallerNode->getNumLinks() - CallerOffset;
877 unsigned numCalleeLinks = CalleeNode->getNumLinks() - CalleeOffset;
879 if (numCallerLinks > 0) {
880 if (numCallerLinks < numCalleeLinks) {
881 std::cerr << "Potential node collapsing in caller\n";
882 for (unsigned i = 0, e = numCalleeLinks; i != e; ++i)
883 CalcNodeMapping(CallerNode->getLink(((i%numCallerLinks) << DS::PointerShift) + CallerOffset), CalleeNode->getLink((i << DS::PointerShift) + CalleeOffset), NodeMapping);
885 for (unsigned i = 0, e = numCalleeLinks; i != e; ++i)
886 CalcNodeMapping(CallerNode->getLink((i << DS::PointerShift) + CallerOffset), CalleeNode->getLink((i << DS::PointerShift) + CalleeOffset), NodeMapping);
888 } else if (numCalleeLinks > 0) {
890 "Caller has unexpanded node, due to indirect call perhaps!\n";
895 void FuncTransform::visitCallInst(CallInst &CI) {
896 Function *CF = CI.getCalledFunction();
898 // optimization for function pointers that are basically gotten from a cast
899 // with only one use and constant expressions with casts in them
901 if (CastInst* CastI = dyn_cast<CastInst>(CI.getCalledValue())) {
902 if (isa<Function>(CastI->getOperand(0)) &&
903 CastI->getOperand(0)->getType() == CastI->getType())
904 CF = dyn_cast<Function>(CastI->getOperand(0));
905 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI.getOperand(0))) {
906 if (CE->getOpcode() == Instruction::Cast) {
907 if (isa<ConstantPointerRef>(CE->getOperand(0)))
910 assert(0 && "Function pointer cast not handled as called function\n");
916 DSGraph &CallerG = G;
918 std::vector<Value*> Args;
919 if (!CF) { // Indirect call
920 DEBUG(std::cerr << " Handling call: " << CI);
922 std::map<unsigned, Value*> PoolArgs;
925 std::pair<std::multimap<CallInst*, Function*>::iterator,
926 std::multimap<CallInst*, Function*>::iterator> Targets =
927 PAInfo.CallInstTargets.equal_range(&CI);
928 for (std::multimap<CallInst*, Function*>::iterator TFI = Targets.first,
929 TFE = Targets.second; TFI != TFE; ++TFI) {
930 if (TFI == Targets.first) {
931 FuncClass = PAInfo.FuncECs.findClass(TFI->second);
932 // Nothing to transform if there are no pool arguments in this
933 // equivalence class of functions.
934 if (!PAInfo.EqClass2LastPoolArg.count(FuncClass))
938 FuncInfo *CFI = PAInfo.getFuncInfo(*TFI->second);
940 if (!CFI->ArgNodes.size()) continue; // Nothing to transform...
942 DSGraph &CG = PAInfo.getBUDataStructures().getDSGraph(*TFI->second);
943 std::map<DSNode*, DSNode*> NodeMapping;
945 Function::aiterator AI = TFI->second->abegin(), AE = TFI->second->aend();
947 for ( ; AI != AE; ++AI, ++OpNum) {
948 if (!isa<Constant>(CI.getOperand(OpNum)))
949 CalcNodeMapping(getDSNodeHFor(CI.getOperand(OpNum)),
950 CG.getScalarMap()[AI], NodeMapping);
952 assert(OpNum == CI.getNumOperands() && "Varargs calls not handled yet!");
954 if (CI.getType() != Type::VoidTy)
955 CalcNodeMapping(getDSNodeHFor(&CI),
956 CG.getReturnNodeFor(*TFI->second), NodeMapping);
958 // Map the nodes that are pointed to by globals.
959 // For all globals map getDSNodeForGlobal(g)->CG.getDSNodeForGlobal(g)
960 for (DSGraph::ScalarMapTy::iterator SMI = G.getScalarMap().begin(),
961 SME = G.getScalarMap().end(); SMI != SME; ++SMI)
962 if (isa<GlobalValue>(SMI->first)) {
963 CalcNodeMapping(SMI->second,
964 CG.getScalarMap()[SMI->first], NodeMapping);
967 unsigned idx = CFI->PoolArgFirst;
969 // The following loop determines the pool pointers corresponding to
971 for (unsigned i = 0, e = CFI->ArgNodes.size(); i != e; ++i, ++idx) {
972 if (NodeMapping.count(CFI->ArgNodes[i])) {
973 assert(NodeMapping.count(CFI->ArgNodes[i]) && "Node not in mapping!");
974 DSNode *LocalNode = NodeMapping.find(CFI->ArgNodes[i])->second;
976 assert(FI.PoolDescriptors.count(LocalNode) &&
977 "Node not pool allocated?");
978 PoolArgs[idx] = FI.PoolDescriptors.find(LocalNode)->second;
981 // LocalNode is null when a constant is passed in as a parameter
982 PoolArgs[idx] = Constant::getNullValue(PoolDescPtr);
984 PoolArgs[idx] = Constant::getNullValue(PoolDescPtr);
989 // Push the pool arguments into Args.
990 if (PAInfo.EqClass2LastPoolArg.count(FuncClass)) {
991 for (int i = 0; i <= PAInfo.EqClass2LastPoolArg[FuncClass]; ++i) {
992 if (PoolArgs.find(i) != PoolArgs.end())
993 Args.push_back(PoolArgs[i]);
995 Args.push_back(Constant::getNullValue(PoolDescPtr));
998 assert(Args.size()== (unsigned) PAInfo.EqClass2LastPoolArg[FuncClass] + 1
999 && "Call has same number of pool args as the called function");
1002 // Add the rest of the arguments (the original arguments of the function)...
1003 Args.insert(Args.end(), CI.op_begin()+1, CI.op_end());
1005 std::string Name = CI.getName();
1008 if (Args.size() > CI.getNumOperands() - 1) {
1009 // If there are any pool arguments
1011 new CastInst(CI.getOperand(0),
1012 PAInfo.getFuncInfo(*FuncClass)->Clone->getType(), "tmp",
1014 NewCall = new CallInst(CastI, Args, Name, &CI);
1016 NewCall = new CallInst(CI.getOperand(0), Args, Name, &CI);
1019 CI.replaceAllUsesWith(NewCall);
1020 DEBUG(std::cerr << " Result Call: " << *NewCall);
1022 if (CI.getType() != Type::VoidTy) {
1023 // If we are modifying the original function, update the DSGraph...
1024 DSGraph::ScalarMapTy &SM = G.getScalarMap();
1025 DSGraph::ScalarMapTy::iterator CII = SM.find(&CI);
1026 if (CII != SM.end()) {
1027 SM.insert(std::make_pair(NewCall, CII->second));
1028 SM.erase(CII); // Destroy the CallInst
1030 // Otherwise update the NewToOldValueMap with the new CI return value
1031 std::map<Value*,const Value*>::iterator CII =
1032 FI.NewToOldValueMap.find(&CI);
1033 assert(CII != FI.NewToOldValueMap.end() && "CI not found in clone?");
1034 FI.NewToOldValueMap.insert(std::make_pair(NewCall, CII->second));
1035 FI.NewToOldValueMap.erase(CII);
1037 } else if (!FI.NewToOldValueMap.empty()) {
1038 std::map<Value*,const Value*>::iterator II =
1039 FI.NewToOldValueMap.find(&CI);
1040 assert(II != FI.NewToOldValueMap.end() &&
1041 "CI not found in clone?");
1042 FI.NewToOldValueMap.insert(std::make_pair(NewCall, II->second));
1043 FI.NewToOldValueMap.erase(II);
1048 FuncInfo *CFI = PAInfo.getFuncInfo(*CF);
1050 if (CFI == 0 || CFI->Clone == 0) return; // Nothing to transform...
1052 DEBUG(std::cerr << " Handling call: " << CI);
1054 DSGraph &CG = PAInfo.getBUDataStructures().getDSGraph(*CF); // Callee graph
1056 // We need to figure out which local pool descriptors correspond to the pool
1057 // descriptor arguments passed into the function call. Calculate a mapping
1058 // from callee DSNodes to caller DSNodes. We construct a partial isomophism
1059 // between the graphs to figure out which pool descriptors need to be passed
1060 // in. The roots of this mapping is found from arguments and return values.
1062 std::map<DSNode*, DSNode*> NodeMapping;
1064 Function::aiterator AI = CF->abegin(), AE = CF->aend();
1066 for (; AI != AE; ++AI, ++OpNum) {
1067 Value *callOp = CI.getOperand(OpNum);
1068 if (!isa<Constant>(callOp))
1069 CalcNodeMapping(getDSNodeHFor(callOp), CG.getScalarMap()[AI],
1072 assert(OpNum == CI.getNumOperands() && "Varargs calls not handled yet!");
1074 // Map the return value as well...
1075 if (CI.getType() != Type::VoidTy)
1076 CalcNodeMapping(getDSNodeHFor(&CI), CG.getReturnNodeFor(*CF),
1079 // Map the nodes that are pointed to by globals.
1080 // For all globals map getDSNodeForGlobal(g)->CG.getDSNodeForGlobal(g)
1081 for (DSGraph::ScalarMapTy::iterator SMI = G.getScalarMap().begin(),
1082 SME = G.getScalarMap().end(); SMI != SME; ++SMI)
1083 if (isa<GlobalValue>(SMI->first)) {
1084 CalcNodeMapping(SMI->second,
1085 CG.getScalarMap()[SMI->first], NodeMapping);
1088 // Okay, now that we have established our mapping, we can figure out which
1089 // pool descriptors to pass in...
1091 // Add an argument for each pool which must be passed in...
1092 if (CFI->PoolArgFirst != 0) {
1093 for (int i = 0; i < CFI->PoolArgFirst; ++i)
1094 Args.push_back(Constant::getNullValue(PoolDescPtr));
1097 for (unsigned i = 0, e = CFI->ArgNodes.size(); i != e; ++i) {
1098 if (NodeMapping.count(CFI->ArgNodes[i])) {
1100 DSNode *LocalNode = NodeMapping.find(CFI->ArgNodes[i])->second;
1102 assert(FI.PoolDescriptors.count(LocalNode) &&
1103 "Node not pool allocated?");
1104 Args.push_back(FI.PoolDescriptors.find(LocalNode)->second);
1106 Args.push_back(Constant::getNullValue(PoolDescPtr));
1108 Args.push_back(Constant::getNullValue(PoolDescPtr));
1112 Function *FuncClass = PAInfo.FuncECs.findClass(CF);
1114 if (PAInfo.EqClass2LastPoolArg.count(FuncClass))
1115 for (unsigned i = CFI->PoolArgLast;
1116 i <= PAInfo.EqClass2LastPoolArg.count(FuncClass); ++i)
1117 Args.push_back(Constant::getNullValue(PoolDescPtr));
1119 // Add the rest of the arguments...
1120 Args.insert(Args.end(), CI.op_begin()+1, CI.op_end());
1122 std::string Name = CI.getName();
1124 std::map<Value*,const Value*>::iterator CNewII;
1126 Value *NewCall = new CallInst(CFI->Clone, Args, Name, &CI);
1128 CI.replaceAllUsesWith(NewCall);
1129 DEBUG(std::cerr << " Result Call: " << *NewCall);
1131 if (CI.getType() != Type::VoidTy) {
1132 // If we are modifying the original function, update the DSGraph...
1133 DSGraph::ScalarMapTy &SM = G.getScalarMap();
1134 DSGraph::ScalarMapTy::iterator CII = SM.find(&CI);
1135 if (CII != SM.end()) {
1136 SM.insert(std::make_pair(NewCall, CII->second));
1137 SM.erase(CII); // Destroy the CallInst
1139 // Otherwise update the NewToOldValueMap with the new CI return value
1140 std::map<Value*,const Value*>::iterator CNII =
1141 FI.NewToOldValueMap.find(&CI);
1142 assert(CNII != FI.NewToOldValueMap.end() && CNII->second &&
1143 "CI not found in clone?");
1144 FI.NewToOldValueMap.insert(std::make_pair(NewCall, CNII->second));
1145 FI.NewToOldValueMap.erase(CNII);
1147 } else if (!FI.NewToOldValueMap.empty()) {
1148 std::map<Value*,const Value*>::iterator II =
1149 FI.NewToOldValueMap.find(&CI);
1150 assert(II != FI.NewToOldValueMap.end() && "CI not found in clone?");
1151 FI.NewToOldValueMap.insert(std::make_pair(NewCall, II->second));
1152 FI.NewToOldValueMap.erase(II);
1156 CI.getParent()->getInstList().erase(&CI);