blob: 0776ad79fe2e50736ea64c7c716690771b8265b9 [file] [log] [blame]
Chris Lattner64fd9352002-03-28 18:08:31 +00001//===-- PoolAllocate.cpp - Pool Allocation Pass ---------------------------===//
2//
3// This transform changes programs so that disjoint data structures are
4// allocated out of different pools of memory, increasing locality and shrinking
5// pointer size.
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Transforms/IPO/PoolAllocate.h"
Chris Lattner291a1b12002-03-29 19:05:48 +000010#include "llvm/Transforms/CloneFunction.h"
Chris Lattner64fd9352002-03-28 18:08:31 +000011#include "llvm/Analysis/DataStructure.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000012#include "llvm/Analysis/DataStructureGraph.h"
Chris Lattner64fd9352002-03-28 18:08:31 +000013#include "llvm/Pass.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000014#include "llvm/Module.h"
15#include "llvm/Function.h"
Chris Lattnerd92b01c2002-04-09 18:37:46 +000016#include "llvm/BasicBlock.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000017#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000018#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000019#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000020#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000021#include "llvm/DerivedTypes.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "llvm/ConstantVals.h"
23#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000024#include "llvm/Support/InstVisitor.h"
Chris Lattner2e9fa6d2002-04-09 19:48:49 +000025#include "llvm/Argument.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000026#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000027#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000028#include <algorithm>
Chris Lattner64fd9352002-03-28 18:08:31 +000029
Chris Lattner441e16f2002-04-12 20:23:15 +000030// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
31// creation phase in the top level function of a transformed data structure.
32//
33#define DEBUG_CREATE_POOLS 1
34
Chris Lattner50e3d322002-04-13 23:13:18 +000035#include "Support/CommandLine.h"
36enum PtrSize {
37 Ptr8bits, Ptr16bits, Ptr32bits
38};
39
40static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
41 "Set pointer size for pool allocation",
42 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
43 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
44 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"), 0);
45
Chris Lattner441e16f2002-04-12 20:23:15 +000046const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000047
Chris Lattnere0618ca2002-03-29 05:50:20 +000048// FIXME: This is dependant on the sparc backend layout conventions!!
49static TargetData TargetData("test");
50
Chris Lattner50e3d322002-04-13 23:13:18 +000051static const Type *getPointerTransformedType(const Type *Ty) {
52 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
53 return POINTERTYPE;
54 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
55 vector<const Type *> NewElTypes;
56 NewElTypes.reserve(STy->getElementTypes().size());
57 for (StructType::ElementTypes::const_iterator
58 I = STy->getElementTypes().begin(),
59 E = STy->getElementTypes().end(); I != E; ++I)
60 NewElTypes.push_back(getPointerTransformedType(*I));
61 return StructType::get(NewElTypes);
62 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
63 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
64 ATy->getNumElements());
65 } else {
66 assert(Ty->isPrimitiveType() && "Unknown derived type!");
67 return Ty;
68 }
69}
70
Chris Lattner64fd9352002-03-28 18:08:31 +000071namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000072 struct PoolInfo {
73 DSNode *Node; // The node this pool allocation represents
74 Value *Handle; // LLVM value of the pool in the current context
75 const Type *NewType; // The transformed type of the memory objects
76 const Type *PoolType; // The type of the pool
77
78 const Type *getOldType() const { return Node->getType(); }
79
80 PoolInfo() { // Define a default ctor for map::operator[]
81 cerr << "Map subscript used to get element that doesn't exist!\n";
82 abort(); // Invalid
83 }
84
85 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
86 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
87 // Handle can be null...
88 assert(N && NT && PT && "Pool info null!");
89 }
90
91 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
92 assert(N && "Invalid pool info!");
93
94 // The new type of the memory object is the same as the old type, except
95 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +000096 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +000097 }
98 };
99
Chris Lattner692ad5d2002-03-29 17:13:46 +0000100 // ScalarInfo - Information about an LLVM value that we know points to some
101 // datastructure we are processing.
102 //
103 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000104 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000105 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000106
Chris Lattner441e16f2002-04-12 20:23:15 +0000107 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
108 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000109 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000110 };
111
Chris Lattner396d5d72002-03-30 04:02:31 +0000112 // CallArgInfo - Information on one operand for a call that got expanded.
113 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000114 int ArgNo; // Call argument number this corresponds to
115 DSNode *Node; // The graph node for the pool
116 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000117
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000118 CallArgInfo(int Arg, DSNode *N, Value *PH)
119 : ArgNo(Arg), Node(N), PoolHandle(PH) {
120 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000121 }
122
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000123 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000124 bool operator<(const CallArgInfo &CAI) const {
125 return ArgNo < CAI.ArgNo;
126 }
127 };
128
Chris Lattner692ad5d2002-03-29 17:13:46 +0000129 // TransformFunctionInfo - Information about how a function eeds to be
130 // transformed.
131 //
132 struct TransformFunctionInfo {
133 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000134 // processed. Each CallArgInfo corresponds to an argument that needs to
135 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000136 //
137 // As a special case, "argument" number -1 corresponds to the return value.
138 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000139 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000140
141 // Func - The function to be transformed...
142 Function *Func;
143
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000144 // The call instruction that is used to map CallArgInfo PoolHandle values
145 // into the new function values.
146 CallInst *Call;
147
Chris Lattner692ad5d2002-03-29 17:13:46 +0000148 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000149 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000150
Chris Lattner396d5d72002-03-30 04:02:31 +0000151 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000152 if (Func < TFI.Func) return true;
153 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000154 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
155 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000156 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000157 }
158
159 void finalizeConstruction() {
160 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000161 // argument records, in order. Note that this must be a stable sort so
162 // that the entries with the same sorting criteria (ie they are multiple
163 // pool entries for the same argument) are kept in depth first order.
164 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000165 }
166 };
167
168
169 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000170 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000171 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000172 switch (ReqPointerSize) {
173 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
174 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
175 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
176 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000177
178 CurModule = 0; DS = 0;
179 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000180 }
181
Chris Lattner441e16f2002-04-12 20:23:15 +0000182 // getPoolType - Get the type used by the backend for a pool of a particular
183 // type. This pool record is used to allocate nodes of type NodeType.
184 //
185 // Here, PoolTy = { NodeType*, sbyte*, uint }*
186 //
187 const StructType *getPoolType(const Type *NodeType) {
188 vector<const Type*> PoolElements;
189 PoolElements.push_back(PointerType::get(NodeType));
190 PoolElements.push_back(PointerType::get(Type::SByteTy));
191 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000192 StructType *Result = StructType::get(PoolElements);
193
194 // Add a name to the symbol table to correspond to the backend
195 // representation of this pool...
196 assert(CurModule && "No current module!?");
197 string Name = CurModule->getTypeName(NodeType);
198 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
199 CurModule->addTypeName(Name+"oolbe", Result);
200
201 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000202 }
203
Chris Lattner175f37c2002-03-29 03:40:59 +0000204 bool run(Module *M);
205
206 // getAnalysisUsageInfo - This function requires data structure information
207 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000208 //
209 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000210 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000211 Required.push_back(DataStructure::ID);
212 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000213
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000214 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000215 // CurModule - The module being processed.
216 Module *CurModule;
217
218 // DS - The data structure graph for the module being processed.
219 DataStructure *DS;
220
221 // Prototypes that we add to support pool allocation...
222 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
223
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000224 // The map of already transformed functions... note that the keys of this
225 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
226 // of the ArgInfo elements.
227 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000228 map<TransformFunctionInfo, Function*> TransformedFunctions;
229
230 // getTransformedFunction - Get a transformed function, or return null if
231 // the function specified hasn't been transformed yet.
232 //
233 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
234 map<TransformFunctionInfo, Function*>::const_iterator I =
235 TransformedFunctions.find(TFI);
236 if (I != TransformedFunctions.end()) return I->second;
237 return 0;
238 }
239
240
Chris Lattner441e16f2002-04-12 20:23:15 +0000241 // addPoolPrototypes - Add prototypes for the pool functions to the
242 // specified module and update the Pool* instance variables to point to
243 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000244 //
245 void addPoolPrototypes(Module *M);
246
Chris Lattner66df97d2002-03-29 06:21:38 +0000247
248 // CreatePools - Insert instructions into the function we are processing to
249 // create all of the memory pool objects themselves. This also inserts
250 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000251 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000252 //
253 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000254 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000255
Chris Lattner175f37c2002-03-29 03:40:59 +0000256 // processFunction - Convert a function to use pool allocation where
257 // available.
258 //
259 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000260
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000261 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000262 // pools specified in PoolDescs when modifying data structure nodes
263 // specified in the PoolDescs map. IPFGraph is the closed data structure
264 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000265 //
266 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000267 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000268
269 // transformFunction - Transform the specified function the specified way.
270 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000271 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000272 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000273 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000274 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000275 FunctionDSGraph &CallerIPGraph,
276 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000277
Chris Lattner64fd9352002-03-28 18:08:31 +0000278 };
279}
280
Chris Lattner692ad5d2002-03-29 17:13:46 +0000281// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000282// allocation node in a data structure graph is eligable for pool allocation.
283//
284static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000285 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattner175f37c2002-03-29 03:40:59 +0000286
287 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
288 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
Chris Lattnere0618ca2002-03-29 05:50:20 +0000289 return true; // Do not allow variable size allocations...
Chris Lattner175f37c2002-03-29 03:40:59 +0000290
Chris Lattnere0618ca2002-03-29 05:50:20 +0000291 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000292}
293
Chris Lattner175f37c2002-03-29 03:40:59 +0000294// processFunction - Convert a function to use pool allocation where
295// available.
296//
297bool PoolAllocate::processFunction(Function *F) {
298 // Get the closed datastructure graph for the current function... if there are
299 // any allocations in this graph that are not escaping, we need to pool
300 // allocate them here!
301 //
302 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
303
304 // Get all of the allocations that do not escape the current function. Since
305 // they are still live (they exist in the graph at all), this means we must
306 // have scalar references to these nodes, but the scalars are never returned.
307 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000308 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000309 IPGraph.getNonEscapingAllocations(Allocs);
310
311 // Filter out allocations that we cannot handle. Currently, this includes
312 // variable sized array allocations and alloca's (which we do not want to
313 // pool allocate)
314 //
315 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
316 Allocs.end());
317
318
319 if (Allocs.empty()) return false; // Nothing to do.
320
Chris Lattner692ad5d2002-03-29 17:13:46 +0000321 // Insert instructions into the function we are processing to create all of
322 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000323 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000324 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000325 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000326 map<DSNode*, PoolInfo> PoolDescs;
327 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000328
Chris Lattner441e16f2002-04-12 20:23:15 +0000329 cerr << "Transformed Entry Function: \n" << F;
330
331 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000332 // how. To do this, we look at all of the scalars, seeing which functions are
333 // either used as a scalar value (so they return a data structure), or are
334 // passed one of our scalar values.
335 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000336 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000337
338 return true;
339}
340
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000341
Chris Lattner441e16f2002-04-12 20:23:15 +0000342//===----------------------------------------------------------------------===//
343//
344// NewInstructionCreator - This class is used to traverse the function being
345// modified, changing each instruction visit'ed to use and provide pointer
346// indexes instead of real pointers. This is what changes the body of a
347// function to use pool allocation.
348//
349class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000350 PoolAllocate &PoolAllocator;
351 vector<ScalarInfo> &Scalars;
352 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000353 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000354
Chris Lattner441e16f2002-04-12 20:23:15 +0000355 struct RefToUpdate {
356 Instruction *I; // Instruction to update
357 unsigned OpNum; // Operand number to update
358 Value *OldVal; // The old value it had
359
360 RefToUpdate(Instruction *i, unsigned o, Value *ov)
361 : I(i), OpNum(o), OldVal(ov) {}
362 };
363 vector<RefToUpdate> ReferencesToUpdate;
364
365 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000366 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
367 if (Scalars[i].Val == V) return Scalars[i];
368 assert(0 && "Scalar not found in getScalar!");
369 abort();
370 return Scalars[0];
371 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000372
373 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000374 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000375 if (Scalars[i].Val == V) return &Scalars[i];
376 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000377 }
378
Chris Lattner441e16f2002-04-12 20:23:15 +0000379 BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
380 BasicBlock *BB = I->getParent();
381 BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
382 BB->getInstList().replaceWith(RI, New);
383 XFormMap[I] = New;
384 return RI;
385 }
386
387 LoadInst *createPoolBaseInstruction(Value *PtrVal) {
388 const ScalarInfo &SC = getScalarRef(PtrVal);
389 vector<Value*> Args(3);
390 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
391 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
392 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
393 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
394 }
395
396
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000397public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000398 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
399 map<CallInst*, TransformFunctionInfo> &C,
400 map<Value*, Value*> &X)
401 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000402
Chris Lattner441e16f2002-04-12 20:23:15 +0000403
404 // updateReferences - The NewInstructionCreator is responsible for creating
405 // new instructions to replace the old ones in the function, and then link up
406 // references to values to their new values. For it to do this, however, it
407 // keeps track of information about the value mapping of old values to new
408 // values that need to be patched up. Given this value map and a set of
409 // instruction operands to patch, updateReferences performs the updates.
410 //
411 void updateReferences() {
412 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
413 RefToUpdate &Ref = ReferencesToUpdate[i];
414 Value *NewVal = XFormMap[Ref.OldVal];
415
416 if (NewVal == 0) {
417 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
418 cast<Constant>(Ref.OldVal)->isNullValue()) {
419 // Transform the null pointer into a null index... caching in XFormMap
420 XFormMap[Ref.OldVal] = NewVal =Constant::getNullConstant(POINTERTYPE);
421 //} else if (isa<Argument>(Ref.OldVal)) {
422 } else {
423 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
424 assert(XFormMap[Ref.OldVal] &&
425 "Reference to value that was not updated found!");
426 }
427 }
428
429 Ref.I->setOperand(Ref.OpNum, NewVal);
430 }
431 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000432 }
433
Chris Lattner441e16f2002-04-12 20:23:15 +0000434 //===--------------------------------------------------------------------===//
435 // Transformation methods:
436 // These methods specify how each type of instruction is transformed by the
437 // NewInstructionCreator instance...
438 //===--------------------------------------------------------------------===//
439
440 void visitGetElementPtrInst(GetElementPtrInst *I) {
441 assert(0 && "Cannot transform get element ptr instructions yet!");
442 }
443
444 // Replace the load instruction with a new one.
445 void visitLoadInst(LoadInst *I) {
446 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
447
448 // Cast our index to be a UIntTy so we can use it to index into the pool...
449 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
450 Type::UIntTy, I->getOperand(0)->getName());
451
452 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
453
454 vector<Value*> Indices(I->idx_begin(), I->idx_end());
455 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
456 "Cannot handle array indexing yet!");
457 Indices[0] = Index;
458 Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
459
460 // Replace the load instruction with the new load instruction...
461 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
462
463 // Add the pool base calculator instruction before the load...
464 II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
465
466 // Add the cast before the load instruction...
467 NewLoad->getParent()->getInstList().insert(II, Index);
468
469 // If not yielding a pool allocated pointer, use the new load value as the
470 // value in the program instead of the old load value...
471 //
472 if (!getScalar(I))
473 I->replaceAllUsesWith(NewLoad);
474 }
475
476 // Replace the store instruction with a new one. In the store instruction,
477 // the value stored could be a pointer type, meaning that the new store may
478 // have to change one or both of it's operands.
479 //
480 void visitStoreInst(StoreInst *I) {
481 assert(getScalar(I->getOperand(1)) &&
482 "Store inst found only storing pool allocated pointer. "
483 "Not imp yet!");
484
485 Value *Val = I->getOperand(0); // The value to store...
486 // Check to see if the value we are storing is a data structure pointer...
487 if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
488 Val = Constant::getNullConstant(POINTERTYPE); // Yes, store a dummy
489
490 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
491
492 // Cast our index to be a UIntTy so we can use it to index into the pool...
493 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
494 Type::UIntTy, I->getOperand(1)->getName());
495 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
496
497 vector<Value*> Indices(I->idx_begin(), I->idx_end());
498 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
499 "Cannot handle array indexing yet!");
500 Indices[0] = Index;
501 Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
502
503 if (Val != I->getOperand(0)) // Value stored was a pointer?
504 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
505
506
507 // Replace the store instruction with the cast instruction...
508 BasicBlock::iterator II = ReplaceInstWith(I, Index);
509
510 // Add the pool base calculator instruction before the index...
511 II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
512
513 // Add the store after the cast instruction...
514 Index->getParent()->getInstList().insert(II, NewStore);
515 }
516
517
518 // Create call to poolalloc for every malloc instruction
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000519 void visitMallocInst(MallocInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000520 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000521 Args.push_back(getScalarRef(I).Pool.Handle);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000522 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000523 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000524 }
525
Chris Lattner441e16f2002-04-12 20:23:15 +0000526 // Convert a call to poolfree for every free instruction...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000527 void visitFreeInst(FreeInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000528 // Create a new call to poolfree before the free instruction
529 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000530 Args.push_back(Constant::getNullConstant(POINTERTYPE));
531 Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
532 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
533 ReplaceInstWith(I, NewCall);
534 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 0, I->getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000535 }
536
537 // visitCallInst - Create a new call instruction with the extra arguments for
538 // all of the memory pools that the call needs.
539 //
540 void visitCallInst(CallInst *I) {
541 TransformFunctionInfo &TI = CallMap[I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000542
543 // Start with all of the old arguments...
544 vector<Value*> Args(I->op_begin()+1, I->op_end());
545
Chris Lattner441e16f2002-04-12 20:23:15 +0000546 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
547 // Replace all of the pointer arguments with our new pointer typed values.
548 if (TI.ArgInfo[i].ArgNo != -1)
549 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullConstant(POINTERTYPE);
550
551 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000552 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000553 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000554
555 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner441e16f2002-04-12 20:23:15 +0000556 Instruction *NewCall = new CallInst(NF, Args, I->getName());
557 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000558
Chris Lattner441e16f2002-04-12 20:23:15 +0000559 // Keep track of the mapping of operands so that we can resolve them to real
560 // values later.
561 Value *RetVal = NewCall;
562 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
563 if (TI.ArgInfo[i].ArgNo != -1)
564 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
565 I->getOperand(TI.ArgInfo[i].ArgNo+1)));
566 else
567 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000568
Chris Lattner441e16f2002-04-12 20:23:15 +0000569 // If not returning a pointer, use the new call as the value in the program
570 // instead of the old call...
571 //
572 if (RetVal)
573 I->replaceAllUsesWith(RetVal);
574 }
575
576 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
577 // nodes...
578 //
579 void visitPHINode(PHINode *PN) {
580 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
581 PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
582 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
583 NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
584 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
585 PN->getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000586 }
587
Chris Lattner441e16f2002-04-12 20:23:15 +0000588 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000589 }
590
Chris Lattner441e16f2002-04-12 20:23:15 +0000591 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner847b6e22002-03-30 20:53:14 +0000592 void visitReturnInst(ReturnInst *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000593 Instruction *Ret = new ReturnInst(Constant::getNullConstant(POINTERTYPE));
594 ReplaceInstWith(I, Ret);
595 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000596 }
597
Chris Lattner441e16f2002-04-12 20:23:15 +0000598 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000599 void visitSetCondInst(SetCondInst *SCI) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000600 BinaryOperator *I = (BinaryOperator*)SCI;
601 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
602 BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
603 DummyVal, I->getName());
604 ReplaceInstWith(I, New);
605
606 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
607 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
608
609 // Make sure branches refer to the new condition...
610 I->replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000611 }
612
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000613 void visitInstruction(Instruction *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000614 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000615 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000616};
617
618
Chris Lattner441e16f2002-04-12 20:23:15 +0000619
620
Chris Lattner0dc225c2002-03-31 07:17:46 +0000621static void addCallInfo(DataStructure *DS,
622 TransformFunctionInfo &TFI, CallInst *CI, int Arg,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000623 DSNode *GraphNode,
Chris Lattner441e16f2002-04-12 20:23:15 +0000624 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000625 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
626 assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
627 "Function call record should always call the same function!");
628 assert(TFI.Call == 0 || TFI.Call == CI &&
629 "Call element already filled in with different value!");
630 TFI.Func = CI->getCalledFunction();
631 TFI.Call = CI;
632 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(TFI.Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000633
634 // For now, add the entire graph that is pointed to by the call argument.
635 // This graph can and should be pruned to only what the function itself will
636 // use, because often this will be a dramatically smaller subset of what we
637 // are providing.
638 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000639 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000640 I != E; ++I)
641 TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
Chris Lattner396d5d72002-03-30 04:02:31 +0000642}
643
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000644
645// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000646// pools specified in PoolDescs when modifying data structure nodes specified in
647// the PoolDescs map. Specifically, scalar values specified in the Scalars
648// vector must be remapped. IPFGraph is the closed data structure graph for F,
649// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000650//
651void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000652 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000653
654 // Loop through the value map looking for scalars that refer to nonescaping
655 // allocations. Add them to the Scalars vector. Note that we may have
656 // multiple entries in the Scalars vector for each value if it points to more
657 // than one object.
658 //
659 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
660 vector<ScalarInfo> Scalars;
661
Chris Lattner847b6e22002-03-30 20:53:14 +0000662 cerr << "Building scalar map:\n";
663
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000664 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
665 E = ValMap.end(); I != E; ++I) {
666 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
667
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000668 // Check to see if the scalar points to a data structure node...
669 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
670 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
671
672 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +0000673 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
674 if (AI != PoolDescs.end()) { // Add it to the list of scalars
675 Scalars.push_back(ScalarInfo(I->first, AI->second));
676 cerr << "\nScalar Mapping from:" << I->first
677 << "Scalar Mapping to: "; PVS.print(cerr);
678 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000679 }
680 }
681
682
683
Chris Lattner847b6e22002-03-30 20:53:14 +0000684 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +0000685 << "': Found the following values that point to poolable nodes:\n";
686
687 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000688 cerr << Scalars[i].Val;
689 cerr << "\n";
Chris Lattnere0618ca2002-03-29 05:50:20 +0000690
Chris Lattner692ad5d2002-03-29 17:13:46 +0000691 // CallMap - Contain an entry for every call instruction that needs to be
692 // transformed. Each entry in the map contains information about what we need
693 // to do to each call site to change it to work.
694 //
695 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +0000696
Chris Lattner441e16f2002-04-12 20:23:15 +0000697 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000698 // how. To do this, we look at all of the scalars, seeing which functions are
699 // either used as a scalar value (so they return a data structure), or are
700 // passed one of our scalar values.
701 //
702 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
703 Value *ScalarVal = Scalars[i].Val;
704
705 // Check to see if the scalar _IS_ a call...
706 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
707 // If so, add information about the pool it will be returning...
Chris Lattner441e16f2002-04-12 20:23:15 +0000708 addCallInfo(DS, CallMap[CI], CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000709
710 // Check to see if the scalar is an operand to a call...
711 for (Value::use_iterator UI = ScalarVal->use_begin(),
712 UE = ScalarVal->use_end(); UI != UE; ++UI) {
713 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
714 // Find out which operand this is to the call instruction...
715 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
716 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
717 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
718
719 // FIXME: This is broken if the same pointer is passed to a call more
720 // than once! It will get multiple entries for the first pointer.
721
722 // Add the operand number and pool handle to the call table...
Chris Lattner441e16f2002-04-12 20:23:15 +0000723 addCallInfo(DS, CallMap[CI], CI, OI-CI->op_begin()-1,
724 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000725 }
726 }
727 }
728
729 // Print out call map...
730 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
731 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000732 cerr << "For call: " << I->first;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000733 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000734 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000735 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000736 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +0000737 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000738 }
739
740 // Loop through all of the call nodes, recursively creating the new functions
741 // that we want to call... This uses a map to prevent infinite recursion and
742 // to avoid duplicating functions unneccesarily.
743 //
744 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
745 E = CallMap.end(); I != E; ++I) {
746 // Make sure the entries are sorted.
747 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000748
749 // Transform all of the functions we need, or at least ensure there is a
750 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +0000751 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000752 }
753
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000754 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +0000755 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000756 // functions that we just hacked up.
757 //
758
759 // First step, find the instructions to be modified.
760 vector<Instruction*> InstToFix;
761 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
762 Value *ScalarVal = Scalars[i].Val;
763
764 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
765 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
766 InstToFix.push_back(Inst);
767
768 // All all of the instructions that use the scalar as an operand...
769 for (Value::use_iterator UI = ScalarVal->use_begin(),
770 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +0000771 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000772 }
773
Chris Lattner50e3d322002-04-13 23:13:18 +0000774 // Make sure that we get return instructions that return a null value from the
775 // function...
776 //
777 if (!IPFGraph.getRetNodes().empty()) {
778 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
779 PointerVal RetNode = IPFGraph.getRetNodes()[0];
780 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
781
782 // Only process return instructions if the return value of this function is
783 // part of one of the data structures we are transforming...
784 //
785 if (PoolDescs.count(RetNode.Node)) {
786 // Loop over all of the basic blocks, adding return instructions...
787 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
788 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
789 InstToFix.push_back(RI);
790 }
791 }
792
793
794
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000795 // Eliminate duplicates by sorting, then removing equal neighbors.
796 sort(InstToFix.begin(), InstToFix.end());
797 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
798
Chris Lattner441e16f2002-04-12 20:23:15 +0000799 // Loop over all of the instructions to transform, creating the new
800 // replacement instructions for them. This also unlinks them from the
801 // function so they can be safely deleted later.
802 //
803 map<Value*, Value*> XFormMap;
804 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000805
Chris Lattner441e16f2002-04-12 20:23:15 +0000806 // Visit all instructions... creating the new instructions that we need and
807 // unlinking the old instructions from the function...
808 //
809 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
810 cerr << "Fixing: " << InstToFix[i];
811 NIC.visit(InstToFix[i]);
812 }
813 //NIC.visit(InstToFix.begin(), InstToFix.end());
814
815 // Make all instructions we will delete "let go" of their operands... so that
816 // we can safely delete Arguments whose types have changed...
817 //
818 for_each(InstToFix.begin(), InstToFix.end(),
819 mem_fun(&Instruction::dropAllReferences));
820
821 // Loop through all of the pointer arguments coming into the function,
822 // replacing them with arguments of POINTERTYPE to match the function type of
823 // the function.
824 //
825 FunctionType::ParamTypes::const_iterator TI =
826 F->getFunctionType()->getParamTypes().begin();
827 for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
828 E = F->getArgumentList().end(); I != E; ++I, ++TI) {
829 Argument *Arg = *I;
830 if (Arg->getType() != *TI) {
831 assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
832 Argument *NewArg = new Argument(*TI, Arg->getName());
833 XFormMap[Arg] = NewArg; // Map old arg into new arg...
834
835
836 // Replace the old argument and then delete it...
837 delete F->getArgumentList().replaceWith(I, NewArg);
838 }
839 }
840
841 // Now that all of the new instructions have been created, we can update all
842 // of the references to dummy values to be references to the actual values
843 // that are computed.
844 //
845 NIC.updateReferences();
846
847 cerr << "TRANSFORMED FUNCTION:\n" << F;
848
849
850 // Delete all of the "instructions to fix"
851 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000852
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000853 // Since we have liberally hacked the function to pieces, we want to inform
854 // the datastructure pass that its internal representation is out of date.
855 //
856 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000857}
858
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000859static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
860 map<DSNode*, PointerValSet> &NodeMapping) {
861 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
862 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
863 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
864 DSNode *DestNode = PVS[i].Node;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000865
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000866 // Loop over all of the outgoing links in the mapped graph
867 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
868 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
869 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000870
871 // Add all of the node mappings now!
872 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
873 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
874 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
875 }
876 }
877 }
878}
879
880// CalculateNodeMapping - There is a partial isomorphism between the graph
881// passed in and the graph that is actually used by the function. We need to
882// figure out what this mapping is so that we can transformFunctionBody the
883// instructions in the function itself. Note that every node in the graph that
884// we are interested in must be both in the local graph of the called function,
885// and in the local graph of the calling function. Because of this, we only
886// define the mapping for these nodes [conveniently these are the only nodes we
887// CAN define a mapping for...]
Chris Lattner692ad5d2002-03-29 17:13:46 +0000888//
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000889// The roots of the graph that we are transforming is rooted in the arguments
890// passed into the function from the caller. This is where we start our
891// mapping calculation.
892//
893// The NodeMapping calculated maps from the callers graph to the called graph.
894//
Chris Lattner847b6e22002-03-30 20:53:14 +0000895static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000896 FunctionDSGraph &CallerGraph,
897 FunctionDSGraph &CalledGraph,
898 map<DSNode*, PointerValSet> &NodeMapping) {
899 int LastArgNo = -2;
900 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
901 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
902 // corresponds to...
903 //
904 // Only consider first node of sequence. Extra nodes may may be added
905 // to the TFI if the data structure requires more nodes than just the
906 // one the argument points to. We are only interested in the one the
907 // argument points to though.
908 //
909 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
910 if (TFI.ArgInfo[i].ArgNo == -1) {
911 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
912 NodeMapping);
913 } else {
914 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner847b6e22002-03-30 20:53:14 +0000915 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000916 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
917 NodeMapping);
918 }
919 LastArgNo = TFI.ArgInfo[i].ArgNo;
920 }
921 }
922}
923
924
925// transformFunction - Transform the specified function the specified way. It
926// we have already transformed that function that way, don't do anything. The
927// nodes in the TransformFunctionInfo come out of callers data structure graph.
928//
929void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000930 FunctionDSGraph &CallerIPGraph,
931 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +0000932 if (getTransformedFunction(TFI)) return; // Function xformation already done?
933
Chris Lattner441e16f2002-04-12 20:23:15 +0000934 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +0000935 << TFI.Func->getName() << ":\n";
936 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
937 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
938 cerr << "\n";
939
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000940 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +0000941
Chris Lattner291a1b12002-03-29 19:05:48 +0000942 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +0000943
Chris Lattner291a1b12002-03-29 19:05:48 +0000944 // Build the type for the new function that we are transforming
945 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +0000946 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +0000947 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
948 ArgTys.push_back(OldFuncType->getParamType(i));
949
Chris Lattner441e16f2002-04-12 20:23:15 +0000950 const Type *RetType = OldFuncType->getReturnType();
951
Chris Lattner291a1b12002-03-29 19:05:48 +0000952 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +0000953 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
954 if (TFI.ArgInfo[i].ArgNo == -1)
955 RetType = POINTERTYPE; // Return a pointer
956 else
957 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
958 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
959 ->second.PoolType));
960 }
Chris Lattner291a1b12002-03-29 19:05:48 +0000961
962 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +0000963 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
964 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +0000965
966 // The new function is internal, because we know that only we can call it.
967 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +0000968 // pointers (which look like the same value is always passed into a parameter,
969 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +0000970 //
971 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000972 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +0000973 CurModule->getFunctionList().push_back(NewFunc);
974
Chris Lattner441e16f2002-04-12 20:23:15 +0000975
976 cerr << "Created function prototype: " << NewFunc << "\n";
977
Chris Lattner291a1b12002-03-29 19:05:48 +0000978 // Add the newly formed function to the TransformedFunctions table so that
979 // infinite recursion does not occur!
980 //
981 TransformedFunctions[TFI] = NewFunc;
982
983 // Add arguments to the function... starting with all of the old arguments
984 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000985 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
Chris Lattner2e9fa6d2002-04-09 19:48:49 +0000986 const Argument *OFA = TFI.Func->getArgumentList()[i];
987 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +0000988 NewFunc->getArgumentList().push_back(NFA);
989 ArgMap.push_back(NFA); // Keep track of the arguments
990 }
991
992 // Now add all of the arguments corresponding to pools passed in...
993 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000994 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +0000995 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +0000996 if (AI.ArgNo == -1)
997 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +0000998 else
Chris Lattner441e16f2002-04-12 20:23:15 +0000999 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1000 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1001 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001002 NewFunc->getArgumentList().push_back(NFA);
1003 }
1004
1005 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001006 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001007
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001008 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001009 // it has extra arguments for the pools coming in. Now we have to get the
1010 // data structure graph for the function we are replacing, and figure out how
1011 // our graph nodes map to the graph nodes in the dest function.
1012 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001013 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001014
Chris Lattner441e16f2002-04-12 20:23:15 +00001015 // NodeMapping - Multimap from callers graph to called graph. We are
1016 // guaranteed that the called function graph has more nodes than the caller,
1017 // or exactly the same number of nodes. This is because the called function
1018 // might not know that two nodes are merged when considering the callers
1019 // context, but the caller obviously does. Because of this, a single node in
1020 // the calling function's data structure graph can map to multiple nodes in
1021 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001022 //
1023 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001024
Chris Lattner847b6e22002-03-30 20:53:14 +00001025 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001026 NodeMapping);
1027
1028 // Print out the node mapping...
Chris Lattner847b6e22002-03-30 20:53:14 +00001029 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001030 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1031 I != NodeMapping.end(); ++I) {
1032 cerr << "Map: "; I->first->print(cerr);
1033 cerr << "To: "; I->second.print(cerr);
1034 cerr << "\n";
1035 }
1036
1037 // Fill in the PoolDescriptor information for the transformed function so that
1038 // it can determine which value holds the pool descriptor for each data
1039 // structure node that it accesses.
1040 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001041 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001042
Chris Lattner847b6e22002-03-30 20:53:14 +00001043 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001044
Chris Lattner441e16f2002-04-12 20:23:15 +00001045 // Calculate as much of the pool descriptor map as possible. Since we have
1046 // the node mapping between the caller and callee functions, and we have the
1047 // pool descriptor information of the caller, we can calculate a partical pool
1048 // descriptor map for the called function.
1049 //
1050 // The nodes that we do not have complete information for are the ones that
1051 // are accessed by loading pointers derived from arguments passed in, but that
1052 // are not passed in directly. In this case, we have all of the information
1053 // except a pool value. If the called function refers to this pool, the pool
1054 // value will be loaded from the pool graph and added to the map as neccesary.
1055 //
1056 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1057 I != NodeMapping.end(); ++I) {
1058 DSNode *CallerNode = I->first;
1059 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001060
Chris Lattner441e16f2002-04-12 20:23:15 +00001061 // Check to see if we have a node pointer passed in for this value...
1062 Value *CalleeValue = 0;
1063 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1064 if (TFI.ArgInfo[a].Node == CallerNode) {
1065 // Calculate the argument number that the pool is to the function
1066 // call... The call instruction should not have the pool operands added
1067 // yet.
1068 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
1069 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
1070 assert(ArgNo < NewFunc->getArgumentList().size() &&
1071 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001072
Chris Lattner441e16f2002-04-12 20:23:15 +00001073 // Map the pool argument into the called function...
1074 CalleeValue = NewFunc->getArgumentList()[ArgNo];
1075 break; // Found value, quit loop
1076 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001077
Chris Lattner441e16f2002-04-12 20:23:15 +00001078 // Loop over all of the data structure nodes that this incoming node maps to
1079 // Creating a PoolInfo structure for them.
1080 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1081 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1082 DSNode *CalleeNode = I->second[i].Node;
1083
1084 // Add the descriptor. We already know everything about it by now, much
1085 // of it is the same as the caller info.
1086 //
1087 PoolDescs.insert(make_pair(CalleeNode,
1088 PoolInfo(CalleeNode, CalleeValue,
1089 CallerPI.NewType,
1090 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001091 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001092 }
1093
1094 // We must destroy the node mapping so that we don't have latent references
1095 // into the data structure graph for the new function. Otherwise we get
1096 // assertion failures when transformFunctionBody tries to invalidate the
1097 // graph.
1098 //
1099 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001100
1101 // Now that we know everything we need about the function, transform the body
1102 // now!
1103 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001104 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1105
1106 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattner66df97d2002-03-29 06:21:38 +00001107}
1108
Chris Lattner8f796d62002-04-13 19:25:57 +00001109static unsigned countPointerTypes(const Type *Ty) {
1110 if (isa<PointerType>(Ty)) {
1111 return 1;
1112 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1113 unsigned Num = 0;
1114 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1115 Num += countPointerTypes(STy->getElementTypes()[i]);
1116 return Num;
1117 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1118 return countPointerTypes(ATy->getElementType());
1119 } else {
1120 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1121 return 0;
1122 }
1123}
Chris Lattner66df97d2002-03-29 06:21:38 +00001124
1125// CreatePools - Insert instructions into the function we are processing to
1126// create all of the memory pool objects themselves. This also inserts
1127// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001128// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001129//
1130void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001131 map<DSNode*, PoolInfo> &PoolDescs) {
1132 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001133 vector<BasicBlock*> ReturnNodes;
1134 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1135 if (isa<ReturnInst>((*I)->getTerminator()))
1136 ReturnNodes.push_back(*I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001137
Chris Lattner441e16f2002-04-12 20:23:15 +00001138 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1139
1140 // First pass over the allocations to process...
1141 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1142 // Create the pooldescriptor mapping... with null entries for everything
1143 // except the node & NewType fields.
1144 //
1145 map<DSNode*, PoolInfo>::iterator PI =
1146 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1147
Chris Lattner8f796d62002-04-13 19:25:57 +00001148 // Add a symbol table entry for the new type if there was one for the old
1149 // type...
1150 string OldName = CurModule->getTypeName(Allocs[i]->getType());
1151 if (!OldName.empty())
1152 CurModule->addTypeName(OldName+".p", PI->second.NewType);
1153
Chris Lattner441e16f2002-04-12 20:23:15 +00001154 // Create the abstract pool types that will need to be resolved in a second
1155 // pass once an abstract type is created for each pool.
1156 //
1157 // Can only handle limited shapes for now...
1158 StructType *OldNodeTy = cast<StructType>(Allocs[i]->getType());
1159 vector<const Type*> PoolTypes;
1160
1161 // Pool type is the first element of the pool descriptor type...
1162 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001163
1164 unsigned NumPointers = countPointerTypes(OldNodeTy);
1165 while (NumPointers--) // Add a different opaque type for each pointer
1166 PoolTypes.push_back(OpaqueType::get());
1167
Chris Lattner441e16f2002-04-12 20:23:15 +00001168 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1169 "Node should have same number of pointers as pool!");
1170
Chris Lattner8f796d62002-04-13 19:25:57 +00001171 StructType *PoolType = StructType::get(PoolTypes);
1172
1173 // Add a symbol table entry for the pooltype if possible...
1174 if (!OldName.empty()) CurModule->addTypeName(OldName+".pool", PoolType);
1175
Chris Lattner441e16f2002-04-12 20:23:15 +00001176 // Create the pool type, with opaque values for pointers...
Chris Lattner8f796d62002-04-13 19:25:57 +00001177 AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001178#ifdef DEBUG_CREATE_POOLS
1179 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1180#endif
1181 }
1182
1183 // Now that we have types for all of the pool types, link them all together.
1184 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1185 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1186
1187 // Resolve all of the outgoing pointer types of this pool node...
1188 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1189 PointerValSet &PVS = Allocs[i]->getLink(p);
1190 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1191 " probably just leave the type opaque or something dumb.");
1192 unsigned Out;
1193 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1194 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1195
1196 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1197
1198 // The actual struct type could change each time through the loop, so it's
1199 // NOT loop invariant.
1200 StructType *PoolTy = cast<StructType>(PoolTyH.get());
1201
1202 // Get the opaque type...
1203 DerivedType *ElTy =
1204 cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1205
1206#ifdef DEBUG_CREATE_POOLS
1207 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1208 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1209#endif
1210
1211 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1212 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1213
1214#ifdef DEBUG_CREATE_POOLS
1215 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1216#endif
1217 }
1218 }
1219
1220 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001221 vector<Instruction*> EntryNodeInsts;
1222 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001223 PoolInfo &PI = PoolDescs[Allocs[i]];
1224
1225 // Fill in the pool type for this pool...
1226 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1227 assert(!PI.PoolType->isAbstract() &&
1228 "Pool type should not be abstract anymore!");
1229
Chris Lattnere0618ca2002-03-29 05:50:20 +00001230 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001231 AllocaInst *PoolAlloc
1232 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1233 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001234 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001235 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001236 AllocationInst *AI = Allocs[i]->getAllocation();
1237
1238 // Initialize the pool. We need to know how big each allocation is. For
1239 // our purposes here, we assume we are allocating a scalar, or array of
1240 // constant size.
1241 //
1242 unsigned ElSize = TargetData.getTypeSize(AI->getAllocatedType());
1243 ElSize *= cast<ConstantUInt>(AI->getArraySize())->getValue();
1244
1245 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001246 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001247 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001248 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1249
Chris Lattner441e16f2002-04-12 20:23:15 +00001250 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001251 Args.clear();
1252 Args.push_back(PoolAlloc); // Pool to initialize
1253
Chris Lattnere0618ca2002-03-29 05:50:20 +00001254 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1255 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1256
1257 // Insert it before the return instruction...
1258 BasicBlock *RetNode = ReturnNodes[EN];
1259 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1260 }
1261 }
1262
Chris Lattner5da145b2002-04-13 19:52:54 +00001263 // Now that all of the pool descriptors have been created, link them together
1264 // so that called functions can get links as neccesary...
1265 //
1266 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1267 PoolInfo &PI = PoolDescs[Allocs[i]];
1268
1269 // For every pointer in the data structure, initialize a link that
1270 // indicates which pool to access...
1271 //
1272 vector<Value*> Indices(2);
1273 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1274 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1275 // Only store an entry for the field if the field is used!
1276 if (!PI.Node->getLink(l).empty()) {
1277 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1278 PointerVal PV = PI.Node->getLink(l)[0];
1279 assert(PV.Index == 0 && "Subindexing not supported yet!");
1280 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1281 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1282
1283 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1284 Indices));
1285 }
1286 }
1287
Chris Lattnere0618ca2002-03-29 05:50:20 +00001288 // Insert the entry node code into the entry block...
1289 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1290 EntryNodeInsts.begin(),
1291 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001292}
1293
1294
Chris Lattner441e16f2002-04-12 20:23:15 +00001295// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001296// module and update the Pool* instance variables to point to them.
1297//
1298void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001299 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001300 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001301 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001302 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001303 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001304
Chris Lattnere0618ca2002-03-29 05:50:20 +00001305 // Get pooldestroy function...
1306 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001307 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001308 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1309
Chris Lattnere0618ca2002-03-29 05:50:20 +00001310 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001311 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001312 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1313
1314 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001315 Args.push_back(POINTERTYPE); // Pointer to free
1316 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001317 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1318
1319 // Add the %PoolTy type to the symbol table of the module...
Chris Lattner441e16f2002-04-12 20:23:15 +00001320 //M->addTypeName("PoolTy", PoolTy->getElementType());
Chris Lattner175f37c2002-03-29 03:40:59 +00001321}
1322
1323
1324bool PoolAllocate::run(Module *M) {
1325 addPoolPrototypes(M);
1326 CurModule = M;
1327
1328 DS = &getAnalysis<DataStructure>();
1329 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001330
1331 // We cannot use an iterator here because it will get invalidated when we add
1332 // functions to the module later...
1333 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001334 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +00001335 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001336 if (Changed) {
1337 cerr << "Only processing one function\n";
1338 break;
1339 }
1340 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001341
1342 CurModule = 0;
1343 DS = 0;
1344 return false;
1345}
1346
1347
1348// createPoolAllocatePass - Global function to access the functionality of this
1349// pass...
1350//
Chris Lattner64fd9352002-03-28 18:08:31 +00001351Pass *createPoolAllocatePass() { return new PoolAllocate(); }