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 and shrinking
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/IPO/PoolAllocate.h"
10 #include "llvm/Transforms/CloneFunction.h"
11 #include "llvm/Analysis/DataStructure.h"
12 #include "llvm/Analysis/DataStructureGraph.h"
13 #include "llvm/Pass.h"
14 #include "llvm/Module.h"
15 #include "llvm/Function.h"
16 #include "llvm/BasicBlock.h"
17 #include "llvm/iMemory.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iOther.h"
20 #include "llvm/ConstantVals.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Support/InstVisitor.h"
23 #include "llvm/Argument.h"
24 #include "Support/DepthFirstIterator.h"
25 #include "Support/STLExtras.h"
29 // FIXME: This is dependant on the sparc backend layout conventions!!
30 static TargetData TargetData("test");
33 // ScalarInfo - Information about an LLVM value that we know points to some
34 // datastructure we are processing.
37 Value *Val; // Scalar value in Current Function
38 DSNode *Node; // DataStructure node it points to
39 Value *PoolHandle; // PoolTy* LLVM value
41 ScalarInfo(Value *V, DSNode *N, Value *PH)
42 : Val(V), Node(N), PoolHandle(PH) {
43 assert(V && N && PH && "Null value passed to ScalarInfo ctor!");
47 // CallArgInfo - Information on one operand for a call that got expanded.
49 int ArgNo; // Call argument number this corresponds to
50 DSNode *Node; // The graph node for the pool
51 Value *PoolHandle; // The LLVM value that is the pool pointer
53 CallArgInfo(int Arg, DSNode *N, Value *PH)
54 : ArgNo(Arg), Node(N), PoolHandle(PH) {
55 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
58 // operator< when sorting, sort by argument number.
59 bool operator<(const CallArgInfo &CAI) const {
60 return ArgNo < CAI.ArgNo;
64 // TransformFunctionInfo - Information about how a function eeds to be
67 struct TransformFunctionInfo {
68 // ArgInfo - Maintain information about the arguments that need to be
69 // processed. Each pair corresponds to an argument (whose number is the
70 // first element) that needs to have a pool pointer (the second element)
71 // passed into the transformed function with it.
73 // As a special case, "argument" number -1 corresponds to the return value.
75 vector<CallArgInfo> ArgInfo;
77 // Func - The function to be transformed...
80 // The call instruction that is used to map CallArgInfo PoolHandle values
81 // into the new function values.
85 TransformFunctionInfo() : Func(0), Call(0) {}
87 bool operator<(const TransformFunctionInfo &TFI) const {
88 if (Func < TFI.Func) return true;
89 if (Func > TFI.Func) return false;
90 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
91 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
92 return ArgInfo < TFI.ArgInfo;
95 void finalizeConstruction() {
96 // Sort the vector so that the return value is first, followed by the
97 // argument records, in order. Note that this must be a stable sort so
98 // that the entries with the same sorting criteria (ie they are multiple
99 // pool entries for the same argument) are kept in depth first order.
100 stable_sort(ArgInfo.begin(), ArgInfo.end());
105 // Define the pass class that we implement...
106 class PoolAllocate : public Pass {
107 // PoolTy - The type of a scalar value that contains a pool pointer.
112 // Initialize the PoolTy instance variable, since the type never changes.
113 vector<const Type*> PoolElements;
114 PoolElements.push_back(PointerType::get(Type::SByteTy));
115 PoolElements.push_back(Type::UIntTy);
116 PoolTy = PointerType::get(StructType::get(PoolElements));
117 // PoolTy = { sbyte*, uint }*
119 CurModule = 0; DS = 0;
120 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
125 // getAnalysisUsageInfo - This function requires data structure information
126 // to be able to see what is pool allocatable.
128 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
129 Pass::AnalysisSet &,Pass::AnalysisSet &) {
130 Required.push_back(DataStructure::ID);
134 // CurModule - The module being processed.
137 // DS - The data structure graph for the module being processed.
140 // Prototypes that we add to support pool allocation...
141 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
143 // The map of already transformed functions... note that the keys of this
144 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
145 // of the ArgInfo elements.
147 map<TransformFunctionInfo, Function*> TransformedFunctions;
149 // getTransformedFunction - Get a transformed function, or return null if
150 // the function specified hasn't been transformed yet.
152 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
153 map<TransformFunctionInfo, Function*>::const_iterator I =
154 TransformedFunctions.find(TFI);
155 if (I != TransformedFunctions.end()) return I->second;
160 // addPoolPrototypes - Add prototypes for the pool methods to the specified
161 // module and update the Pool* instance variables to point to them.
163 void addPoolPrototypes(Module *M);
166 // CreatePools - Insert instructions into the function we are processing to
167 // create all of the memory pool objects themselves. This also inserts
168 // destruction code. Add an alloca for each pool that is allocated to the
169 // PoolDescriptors map.
171 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
172 map<DSNode*, Value*> &PoolDescriptors);
174 // processFunction - Convert a function to use pool allocation where
177 bool processFunction(Function *F);
179 // transformFunctionBody - This transforms the instruction in 'F' to use the
180 // pools specified in PoolDescriptors when modifying data structure nodes
181 // specified in the PoolDescriptors map. IPFGraph is the closed data
182 // structure graph for F, of which the PoolDescriptor nodes come from.
184 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
185 map<DSNode*, Value*> &PoolDescriptors);
187 // transformFunction - Transform the specified function the specified way.
188 // It we have already transformed that function that way, don't do anything.
189 // The nodes in the TransformFunctionInfo come out of callers data structure
192 void transformFunction(TransformFunctionInfo &TFI,
193 FunctionDSGraph &CallerIPGraph);
200 // isNotPoolableAlloc - This is a predicate that returns true if the specified
201 // allocation node in a data structure graph is eligable for pool allocation.
203 static bool isNotPoolableAlloc(const AllocDSNode *DS) {
204 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
206 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
207 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
208 return true; // Do not allow variable size allocations...
213 // processFunction - Convert a function to use pool allocation where
216 bool PoolAllocate::processFunction(Function *F) {
217 // Get the closed datastructure graph for the current function... if there are
218 // any allocations in this graph that are not escaping, we need to pool
219 // allocate them here!
221 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
223 // Get all of the allocations that do not escape the current function. Since
224 // they are still live (they exist in the graph at all), this means we must
225 // have scalar references to these nodes, but the scalars are never returned.
227 vector<AllocDSNode*> Allocs;
228 IPGraph.getNonEscapingAllocations(Allocs);
230 // Filter out allocations that we cannot handle. Currently, this includes
231 // variable sized array allocations and alloca's (which we do not want to
234 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
238 if (Allocs.empty()) return false; // Nothing to do.
240 // Insert instructions into the function we are processing to create all of
241 // the memory pool objects themselves. This also inserts destruction code.
242 // This fills in the PoolDescriptors map to associate the alloc node with the
243 // allocation of the memory pool corresponding to it.
245 map<DSNode*, Value*> PoolDescriptors;
246 CreatePools(F, Allocs, PoolDescriptors);
248 // Now we need to figure out what called methods we need to transform, and
249 // how. To do this, we look at all of the scalars, seeing which functions are
250 // either used as a scalar value (so they return a data structure), or are
251 // passed one of our scalar values.
253 transformFunctionBody(F, IPGraph, PoolDescriptors);
259 class FunctionBodyTransformer : public InstVisitor<FunctionBodyTransformer> {
260 PoolAllocate &PoolAllocator;
261 vector<ScalarInfo> &Scalars;
262 map<CallInst*, TransformFunctionInfo> &CallMap;
264 const ScalarInfo &getScalar(const Value *V) {
265 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
266 if (Scalars[i].Val == V) return Scalars[i];
267 assert(0 && "Scalar not found in getScalar!");
272 // updateScalars - Map the scalars array entries that look like 'From' to look
275 void updateScalars(Value *From, Value *To) {
276 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
277 if (Scalars[i].Val == From) Scalars[i].Val = To;
281 FunctionBodyTransformer(PoolAllocate &PA, vector<ScalarInfo> &S,
282 map<CallInst*, TransformFunctionInfo> &C)
283 : PoolAllocator(PA), Scalars(S), CallMap(C) {}
285 void visitMemAccessInst(MemAccessInst *MAI) {
286 // Don't do anything to load, store, or GEP yet...
289 // Convert a malloc instruction into a call to poolalloc
290 void visitMallocInst(MallocInst *I) {
291 const ScalarInfo &SC = getScalar(I);
292 BasicBlock *BB = I->getParent();
293 BasicBlock::iterator MI = find(BB->begin(), BB->end(), I);
294 BB->getInstList().remove(MI); // Remove the Malloc instruction from the BB
296 // Create a new call to poolalloc before the malloc instruction
298 Args.push_back(SC.PoolHandle);
299 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
300 MI = BB->getInstList().insert(MI, Call)+1;
302 // If the type desired is not void*, cast it now...
304 if (Call->getType() != I->getType()) {
305 CastInst *CI = new CastInst(Ptr, I->getType(), I->getName());
306 BB->getInstList().insert(MI, CI);
310 // Change everything that used the malloc to now use the pool alloc...
311 I->replaceAllUsesWith(Ptr);
313 // Update the scalars array...
314 updateScalars(I, Ptr);
316 // Delete the instruction now.
320 // Convert the free instruction into a call to poolfree
321 void visitFreeInst(FreeInst *I) {
322 Value *Ptr = I->getOperand(0);
323 const ScalarInfo &SC = getScalar(Ptr);
324 BasicBlock *BB = I->getParent();
325 BasicBlock::iterator FI = find(BB->begin(), BB->end(), I);
327 // If the value is not an sbyte*, convert it now!
328 if (Ptr->getType() != PointerType::get(Type::SByteTy)) {
329 CastInst *CI = new CastInst(Ptr, PointerType::get(Type::SByteTy),
331 FI = BB->getInstList().insert(FI, CI)+1;
335 // Create a new call to poolfree before the free instruction
337 Args.push_back(SC.PoolHandle);
339 CallInst *Call = new CallInst(PoolAllocator.PoolFree, Args);
340 FI = BB->getInstList().insert(FI, Call)+1;
342 // Remove the old free instruction...
343 delete BB->getInstList().remove(FI);
346 // visitCallInst - Create a new call instruction with the extra arguments for
347 // all of the memory pools that the call needs.
349 void visitCallInst(CallInst *I) {
350 TransformFunctionInfo &TI = CallMap[I];
351 BasicBlock *BB = I->getParent();
352 BasicBlock::iterator CI = find(BB->begin(), BB->end(), I);
353 BB->getInstList().remove(CI); // Remove the old call instruction
355 // Start with all of the old arguments...
356 vector<Value*> Args(I->op_begin()+1, I->op_end());
358 // Add all of the pool arguments...
359 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
360 Args.push_back(TI.ArgInfo[i].PoolHandle);
362 Function *NF = PoolAllocator.getTransformedFunction(TI);
363 CallInst *NewCall = new CallInst(NF, Args, I->getName());
364 BB->getInstList().insert(CI, NewCall);
366 // Change everything that used the malloc to now use the pool alloc...
367 if (I->getType() != Type::VoidTy) {
368 I->replaceAllUsesWith(NewCall);
370 // Update the scalars array...
371 updateScalars(I, NewCall);
374 delete I; // Delete the old call instruction now...
377 void visitPHINode(PHINode *PN) {
381 void visitReturnInst(ReturnInst *I) {
382 // Nothing of interest
385 void visitSetCondInst(SetCondInst *SCI) {
386 // hrm, notice a pattern?
389 void visitInstruction(Instruction *I) {
390 cerr << "Unknown instruction to FunctionBodyTransformer:\n";
397 static void addCallInfo(DataStructure *DS,
398 TransformFunctionInfo &TFI, CallInst *CI, int Arg,
400 map<DSNode*, Value*> &PoolDescriptors) {
401 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
402 assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
403 "Function call record should always call the same function!");
404 assert(TFI.Call == 0 || TFI.Call == CI &&
405 "Call element already filled in with different value!");
406 TFI.Func = CI->getCalledFunction();
408 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(TFI.Func);
410 // For now, add the entire graph that is pointed to by the call argument.
411 // This graph can and should be pruned to only what the function itself will
412 // use, because often this will be a dramatically smaller subset of what we
415 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
417 TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescriptors[*I]));
422 // transformFunctionBody - This transforms the instruction in 'F' to use the
423 // pools specified in PoolDescriptors when modifying data structure nodes
424 // specified in the PoolDescriptors map. Specifically, scalar values specified
425 // in the Scalars vector must be remapped. IPFGraph is the closed data
426 // structure graph for F, of which the PoolDescriptor nodes come from.
428 void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
429 map<DSNode*, Value*> &PoolDescriptors) {
431 // Loop through the value map looking for scalars that refer to nonescaping
432 // allocations. Add them to the Scalars vector. Note that we may have
433 // multiple entries in the Scalars vector for each value if it points to more
436 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
437 vector<ScalarInfo> Scalars;
439 cerr << "Building scalar map:\n";
441 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
442 E = ValMap.end(); I != E; ++I) {
443 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
445 cerr << "Scalar Mapping from:"; I->first->dump();
446 cerr << "\nScalar Mapping to: "; PVS.print(cerr);
448 // Check to see if the scalar points to a data structure node...
449 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
450 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
452 // If the allocation is in the nonescaping set...
453 map<DSNode*, Value*>::iterator AI = PoolDescriptors.find(PVS[i].Node);
454 if (AI != PoolDescriptors.end()) // Add it to the list of scalars
455 Scalars.push_back(ScalarInfo(I->first, PVS[i].Node, AI->second));
461 cerr << "\nIn '" << F->getName()
462 << "': Found the following values that point to poolable nodes:\n";
464 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
465 Scalars[i].Val->dump();
467 // CallMap - Contain an entry for every call instruction that needs to be
468 // transformed. Each entry in the map contains information about what we need
469 // to do to each call site to change it to work.
471 map<CallInst*, TransformFunctionInfo> CallMap;
473 // Now we need to figure out what called methods we need to transform, and
474 // how. To do this, we look at all of the scalars, seeing which functions are
475 // either used as a scalar value (so they return a data structure), or are
476 // passed one of our scalar values.
478 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
479 Value *ScalarVal = Scalars[i].Val;
481 // Check to see if the scalar _IS_ a call...
482 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
483 // If so, add information about the pool it will be returning...
484 addCallInfo(DS, CallMap[CI], CI, -1, Scalars[i].Node, PoolDescriptors);
486 // Check to see if the scalar is an operand to a call...
487 for (Value::use_iterator UI = ScalarVal->use_begin(),
488 UE = ScalarVal->use_end(); UI != UE; ++UI) {
489 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
490 // Find out which operand this is to the call instruction...
491 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
492 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
493 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
495 // FIXME: This is broken if the same pointer is passed to a call more
496 // than once! It will get multiple entries for the first pointer.
498 // Add the operand number and pool handle to the call table...
499 addCallInfo(DS, CallMap[CI], CI, OI-CI->op_begin()-1, Scalars[i].Node,
505 // Print out call map...
506 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
507 I != CallMap.end(); ++I) {
508 cerr << "\nFor call: ";
510 I->second.finalizeConstruction();
511 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
512 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
513 cerr << I->second.ArgInfo[i].ArgNo << ", ";
517 // Loop through all of the call nodes, recursively creating the new functions
518 // that we want to call... This uses a map to prevent infinite recursion and
519 // to avoid duplicating functions unneccesarily.
521 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
522 E = CallMap.end(); I != E; ++I) {
523 // Make sure the entries are sorted.
524 I->second.finalizeConstruction();
526 // Transform all of the functions we need, or at least ensure there is a
527 // cached version available.
528 transformFunction(I->second, IPFGraph);
531 // Now that all of the functions that we want to call are available, transform
532 // the local method so that it uses the pools locally and passes them to the
533 // functions that we just hacked up.
536 // First step, find the instructions to be modified.
537 vector<Instruction*> InstToFix;
538 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
539 Value *ScalarVal = Scalars[i].Val;
541 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
542 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
543 InstToFix.push_back(Inst);
545 // All all of the instructions that use the scalar as an operand...
546 for (Value::use_iterator UI = ScalarVal->use_begin(),
547 UE = ScalarVal->use_end(); UI != UE; ++UI)
548 InstToFix.push_back(dyn_cast<Instruction>(*UI));
551 // Eliminate duplicates by sorting, then removing equal neighbors.
552 sort(InstToFix.begin(), InstToFix.end());
553 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
555 // Use a FunctionBodyTransformer to transform all of the involved instructions
556 FunctionBodyTransformer FBT(*this, Scalars, CallMap);
557 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i)
558 FBT.visit(InstToFix[i]);
561 // Since we have liberally hacked the function to pieces, we want to inform
562 // the datastructure pass that its internal representation is out of date.
564 DS->invalidateFunction(F);
567 static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
568 map<DSNode*, PointerValSet> &NodeMapping) {
569 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
570 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
571 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
572 DSNode *DestNode = PVS[i].Node;
574 // Loop over all of the outgoing links in the mapped graph
575 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
576 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
577 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
579 // Add all of the node mappings now!
580 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
581 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
582 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
588 // CalculateNodeMapping - There is a partial isomorphism between the graph
589 // passed in and the graph that is actually used by the function. We need to
590 // figure out what this mapping is so that we can transformFunctionBody the
591 // instructions in the function itself. Note that every node in the graph that
592 // we are interested in must be both in the local graph of the called function,
593 // and in the local graph of the calling function. Because of this, we only
594 // define the mapping for these nodes [conveniently these are the only nodes we
595 // CAN define a mapping for...]
597 // The roots of the graph that we are transforming is rooted in the arguments
598 // passed into the function from the caller. This is where we start our
599 // mapping calculation.
601 // The NodeMapping calculated maps from the callers graph to the called graph.
603 static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
604 FunctionDSGraph &CallerGraph,
605 FunctionDSGraph &CalledGraph,
606 map<DSNode*, PointerValSet> &NodeMapping) {
608 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
609 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
612 // Only consider first node of sequence. Extra nodes may may be added
613 // to the TFI if the data structure requires more nodes than just the
614 // one the argument points to. We are only interested in the one the
615 // argument points to though.
617 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
618 if (TFI.ArgInfo[i].ArgNo == -1) {
619 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
622 // Figure out which node argument # ArgNo points to in the called graph.
623 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
624 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
627 LastArgNo = TFI.ArgInfo[i].ArgNo;
633 // transformFunction - Transform the specified function the specified way. It
634 // we have already transformed that function that way, don't do anything. The
635 // nodes in the TransformFunctionInfo come out of callers data structure graph.
637 void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
638 FunctionDSGraph &CallerIPGraph) {
639 if (getTransformedFunction(TFI)) return; // Function xformation already done?
641 cerr << "**********\nEntering transformFunction for "
642 << TFI.Func->getName() << ":\n";
643 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
644 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
648 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
650 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
652 // Build the type for the new function that we are transforming
653 vector<const Type*> ArgTys;
654 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
655 ArgTys.push_back(OldFuncType->getParamType(i));
657 // Add one pool pointer for every argument that needs to be supplemented.
658 ArgTys.insert(ArgTys.end(), TFI.ArgInfo.size(), PoolTy);
660 // Build the new function type...
661 const // FIXME when types are not const
662 FunctionType *NewFuncType = FunctionType::get(OldFuncType->getReturnType(),
663 ArgTys,OldFuncType->isVarArg());
665 // The new function is internal, because we know that only we can call it.
666 // This also helps subsequent IP transformations to eliminate duplicated pool
667 // pointers. [in the future when they are implemented].
669 Function *NewFunc = new Function(NewFuncType, true,
670 TFI.Func->getName()+".poolxform");
671 CurModule->getFunctionList().push_back(NewFunc);
673 // Add the newly formed function to the TransformedFunctions table so that
674 // infinite recursion does not occur!
676 TransformedFunctions[TFI] = NewFunc;
678 // Add arguments to the function... starting with all of the old arguments
679 vector<Value*> ArgMap;
680 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
681 const Argument *OFA = TFI.Func->getArgumentList()[i];
682 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
683 NewFunc->getArgumentList().push_back(NFA);
684 ArgMap.push_back(NFA); // Keep track of the arguments
687 // Now add all of the arguments corresponding to pools passed in...
688 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
690 if (TFI.ArgInfo[i].ArgNo == -1)
693 Name = ArgMap[TFI.ArgInfo[i].ArgNo]->getName(); // Get the arg name
694 Argument *NFA = new Argument(PoolTy, Name+".pool");
695 NewFunc->getArgumentList().push_back(NFA);
698 // Now clone the body of the old function into the new function...
699 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
701 // Okay, now we have a function that is identical to the old one, except that
702 // it has extra arguments for the pools coming in. Now we have to get the
703 // data structure graph for the function we are replacing, and figure out how
704 // our graph nodes map to the graph nodes in the dest function.
706 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
708 // NodeMapping - Multimap from callers graph to called graph.
710 map<DSNode*, PointerValSet> NodeMapping;
712 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
715 // Print out the node mapping...
716 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
717 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
718 I != NodeMapping.end(); ++I) {
719 cerr << "Map: "; I->first->print(cerr);
720 cerr << "To: "; I->second.print(cerr);
724 // Fill in the PoolDescriptor information for the transformed function so that
725 // it can determine which value holds the pool descriptor for each data
726 // structure node that it accesses.
728 map<DSNode*, Value*> PoolDescriptors;
730 cerr << "\nCalculating the pool descriptor map:\n";
732 // All of the pool descriptors must be passed in as arguments...
733 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
734 DSNode *CallerNode = TFI.ArgInfo[i].Node;
735 Value *CallerPool = TFI.ArgInfo[i].PoolHandle;
737 cerr << "Mapped caller node: "; CallerNode->print(cerr);
738 cerr << "Mapped caller pool: "; CallerPool->dump();
740 // Calculate the argument number that the pool is to the function call...
741 // The call instruction should not have the pool operands added yet.
742 unsigned ArgNo = TFI.Call->getNumOperands()-1+i;
743 cerr << "Should be argument #: " << ArgNo << "[i = " << i << "]\n";
744 assert(ArgNo < NewFunc->getArgumentList().size() &&
745 "Call already has pool arguments added??");
747 // Map the pool argument into the called function...
748 Value *CalleePool = NewFunc->getArgumentList()[ArgNo];
750 // Map the DSNode into the callee's DSGraph
751 const PointerValSet &CalleeNodes = NodeMapping[CallerNode];
752 for (unsigned n = 0, ne = CalleeNodes.size(); n != ne; ++n) {
753 assert(CalleeNodes[n].Index == 0 && "Indexed node not handled yet!");
754 DSNode *CalleeNode = CalleeNodes[n].Node;
756 cerr << "*** to callee node: "; CalleeNode->print(cerr);
757 cerr << "*** to callee pool: "; CalleePool->dump();
760 assert(CalleeNode && CalleePool && "Invalid nodes!");
761 Value *&PV = PoolDescriptors[CalleeNode];
762 //assert((PV == 0 || PV == CalleePool) && "Invalid node remapping!");
763 PV = CalleePool; // Update the pool descriptor map!
767 // We must destroy the node mapping so that we don't have latent references
768 // into the data structure graph for the new function. Otherwise we get
769 // assertion failures when transformFunctionBody tries to invalidate the
774 // Now that we know everything we need about the function, transform the body
777 transformFunctionBody(NewFunc, DSGraph, PoolDescriptors);
779 cerr << "Function after transformation:\n";
784 // CreatePools - Insert instructions into the function we are processing to
785 // create all of the memory pool objects themselves. This also inserts
786 // destruction code. Add an alloca for each pool that is allocated to the
787 // PoolDescriptors vector.
789 void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
790 map<DSNode*, Value*> &PoolDescriptors) {
791 // FIXME: This should use an IP version of the UnifyAllExits pass!
792 vector<BasicBlock*> ReturnNodes;
793 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
794 if (isa<ReturnInst>((*I)->getTerminator()))
795 ReturnNodes.push_back(*I);
798 // Create the code that goes in the entry and exit nodes for the method...
799 vector<Instruction*> EntryNodeInsts;
800 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
801 // Add an allocation and a free for each pool...
802 AllocaInst *PoolAlloc = new AllocaInst(PoolTy, 0, "pool");
803 EntryNodeInsts.push_back(PoolAlloc);
804 PoolDescriptors[Allocs[i]] = PoolAlloc; // Keep track of pool allocas
805 AllocationInst *AI = Allocs[i]->getAllocation();
807 // Initialize the pool. We need to know how big each allocation is. For
808 // our purposes here, we assume we are allocating a scalar, or array of
811 unsigned ElSize = TargetData.getTypeSize(AI->getAllocatedType());
812 ElSize *= cast<ConstantUInt>(AI->getArraySize())->getValue();
815 Args.push_back(PoolAlloc); // Pool to initialize
816 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
817 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
819 // Destroy the pool...
822 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
823 Instruction *Destroy = new CallInst(PoolDestroy, Args);
825 // Insert it before the return instruction...
826 BasicBlock *RetNode = ReturnNodes[EN];
827 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
831 // Insert the entry node code into the entry block...
832 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
833 EntryNodeInsts.begin(),
834 EntryNodeInsts.end());
838 // addPoolPrototypes - Add prototypes for the pool methods to the specified
839 // module and update the Pool* instance variables to point to them.
841 void PoolAllocate::addPoolPrototypes(Module *M) {
842 // Get PoolInit function...
843 vector<const Type*> Args;
844 Args.push_back(PoolTy); // Pool to initialize
845 Args.push_back(Type::UIntTy); // Num bytes per element
846 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, false);
847 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
849 // Get pooldestroy function...
850 Args.pop_back(); // Only takes a pool...
851 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, false);
852 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
854 const Type *PtrVoid = PointerType::get(Type::SByteTy);
856 // Get the poolalloc function...
857 FunctionType *PoolAllocTy = FunctionType::get(PtrVoid, Args, false);
858 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
860 // Get the poolfree function...
861 Args.push_back(PtrVoid);
862 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, false);
863 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
865 // Add the %PoolTy type to the symbol table of the module...
866 M->addTypeName("PoolTy", PoolTy->getElementType());
870 bool PoolAllocate::run(Module *M) {
871 addPoolPrototypes(M);
874 DS = &getAnalysis<DataStructure>();
875 bool Changed = false;
877 // We cannot use an iterator here because it will get invalidated when we add
878 // functions to the module later...
879 for (unsigned i = 0; i != M->size(); ++i)
880 if (!M->getFunctionList()[i]->isExternal()) {
881 Changed |= processFunction(M->getFunctionList()[i]);
883 cerr << "Only processing one function\n";
894 // createPoolAllocatePass - Global function to access the functionality of this
897 Pass *createPoolAllocatePass() { return new PoolAllocate(); }