blob: b76323f5c504b956537d1bbe4d1bd2714bb21325 [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 Lattner175f37c2002-03-29 03:40:59 +000013#include "llvm/Module.h"
14#include "llvm/Function.h"
Chris Lattnerd92b01c2002-04-09 18:37:46 +000015#include "llvm/BasicBlock.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000016#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000017#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000018#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000019#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000020#include "llvm/DerivedTypes.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000021#include "llvm/ConstantVals.h"
22#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000023#include "llvm/Support/InstVisitor.h"
Chris Lattner2e9fa6d2002-04-09 19:48:49 +000024#include "llvm/Argument.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000025#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000026#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000027#include <algorithm>
Chris Lattner64fd9352002-03-28 18:08:31 +000028
Chris Lattner441e16f2002-04-12 20:23:15 +000029// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
30// creation phase in the top level function of a transformed data structure.
31//
Chris Lattneracf19022002-04-14 06:14:41 +000032//#define DEBUG_CREATE_POOLS 1
33
34// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
35// the transformation is doing.
36//
37//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000038
Chris Lattner50e3d322002-04-13 23:13:18 +000039#include "Support/CommandLine.h"
40enum PtrSize {
41 Ptr8bits, Ptr16bits, Ptr32bits
42};
43
44static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
Chris Lattneracf19022002-04-14 06:14:41 +000045 "Set pointer size for -poolalloc pass",
Chris Lattner50e3d322002-04-13 23:13:18 +000046 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
47 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
48 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"), 0);
49
Chris Lattner441e16f2002-04-12 20:23:15 +000050const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000051
Chris Lattnere0618ca2002-03-29 05:50:20 +000052// FIXME: This is dependant on the sparc backend layout conventions!!
53static TargetData TargetData("test");
54
Chris Lattner50e3d322002-04-13 23:13:18 +000055static const Type *getPointerTransformedType(const Type *Ty) {
56 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
57 return POINTERTYPE;
58 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
59 vector<const Type *> NewElTypes;
60 NewElTypes.reserve(STy->getElementTypes().size());
61 for (StructType::ElementTypes::const_iterator
62 I = STy->getElementTypes().begin(),
63 E = STy->getElementTypes().end(); I != E; ++I)
64 NewElTypes.push_back(getPointerTransformedType(*I));
65 return StructType::get(NewElTypes);
66 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
67 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
68 ATy->getNumElements());
69 } else {
70 assert(Ty->isPrimitiveType() && "Unknown derived type!");
71 return Ty;
72 }
73}
74
Chris Lattner64fd9352002-03-28 18:08:31 +000075namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000076 struct PoolInfo {
77 DSNode *Node; // The node this pool allocation represents
78 Value *Handle; // LLVM value of the pool in the current context
79 const Type *NewType; // The transformed type of the memory objects
80 const Type *PoolType; // The type of the pool
81
82 const Type *getOldType() const { return Node->getType(); }
83
84 PoolInfo() { // Define a default ctor for map::operator[]
85 cerr << "Map subscript used to get element that doesn't exist!\n";
86 abort(); // Invalid
87 }
88
89 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
90 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
91 // Handle can be null...
92 assert(N && NT && PT && "Pool info null!");
93 }
94
95 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
96 assert(N && "Invalid pool info!");
97
98 // The new type of the memory object is the same as the old type, except
99 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000100 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000101 }
102 };
103
Chris Lattner692ad5d2002-03-29 17:13:46 +0000104 // ScalarInfo - Information about an LLVM value that we know points to some
105 // datastructure we are processing.
106 //
107 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000108 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000109 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000110
Chris Lattner441e16f2002-04-12 20:23:15 +0000111 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
112 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000113 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000114 };
115
Chris Lattner396d5d72002-03-30 04:02:31 +0000116 // CallArgInfo - Information on one operand for a call that got expanded.
117 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000118 int ArgNo; // Call argument number this corresponds to
119 DSNode *Node; // The graph node for the pool
120 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000121
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000122 CallArgInfo(int Arg, DSNode *N, Value *PH)
123 : ArgNo(Arg), Node(N), PoolHandle(PH) {
124 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000125 }
126
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000127 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000128 bool operator<(const CallArgInfo &CAI) const {
129 return ArgNo < CAI.ArgNo;
130 }
131 };
132
Chris Lattner692ad5d2002-03-29 17:13:46 +0000133 // TransformFunctionInfo - Information about how a function eeds to be
134 // transformed.
135 //
136 struct TransformFunctionInfo {
137 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000138 // processed. Each CallArgInfo corresponds to an argument that needs to
139 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000140 //
141 // As a special case, "argument" number -1 corresponds to the return value.
142 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000143 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000144
145 // Func - The function to be transformed...
146 Function *Func;
147
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000148 // The call instruction that is used to map CallArgInfo PoolHandle values
149 // into the new function values.
150 CallInst *Call;
151
Chris Lattner692ad5d2002-03-29 17:13:46 +0000152 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000153 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000154
Chris Lattner396d5d72002-03-30 04:02:31 +0000155 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000156 if (Func < TFI.Func) return true;
157 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000158 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
159 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000160 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000161 }
162
163 void finalizeConstruction() {
164 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000165 // argument records, in order. Note that this must be a stable sort so
166 // that the entries with the same sorting criteria (ie they are multiple
167 // pool entries for the same argument) are kept in depth first order.
168 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000169 }
170 };
171
172
173 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000174 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000175 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000176 switch (ReqPointerSize) {
177 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
178 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
179 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
180 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000181
182 CurModule = 0; DS = 0;
183 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000184 }
185
Chris Lattner441e16f2002-04-12 20:23:15 +0000186 // getPoolType - Get the type used by the backend for a pool of a particular
187 // type. This pool record is used to allocate nodes of type NodeType.
188 //
189 // Here, PoolTy = { NodeType*, sbyte*, uint }*
190 //
191 const StructType *getPoolType(const Type *NodeType) {
192 vector<const Type*> PoolElements;
193 PoolElements.push_back(PointerType::get(NodeType));
194 PoolElements.push_back(PointerType::get(Type::SByteTy));
195 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000196 StructType *Result = StructType::get(PoolElements);
197
198 // Add a name to the symbol table to correspond to the backend
199 // representation of this pool...
200 assert(CurModule && "No current module!?");
201 string Name = CurModule->getTypeName(NodeType);
202 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
203 CurModule->addTypeName(Name+"oolbe", Result);
204
205 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000206 }
207
Chris Lattner175f37c2002-03-29 03:40:59 +0000208 bool run(Module *M);
209
210 // getAnalysisUsageInfo - This function requires data structure information
211 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000212 //
213 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000214 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000215 Required.push_back(DataStructure::ID);
216 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000217
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000218 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000219 // CurModule - The module being processed.
220 Module *CurModule;
221
222 // DS - The data structure graph for the module being processed.
223 DataStructure *DS;
224
225 // Prototypes that we add to support pool allocation...
226 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
227
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000228 // The map of already transformed functions... note that the keys of this
229 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
230 // of the ArgInfo elements.
231 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000232 map<TransformFunctionInfo, Function*> TransformedFunctions;
233
234 // getTransformedFunction - Get a transformed function, or return null if
235 // the function specified hasn't been transformed yet.
236 //
237 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
238 map<TransformFunctionInfo, Function*>::const_iterator I =
239 TransformedFunctions.find(TFI);
240 if (I != TransformedFunctions.end()) return I->second;
241 return 0;
242 }
243
244
Chris Lattner441e16f2002-04-12 20:23:15 +0000245 // addPoolPrototypes - Add prototypes for the pool functions to the
246 // specified module and update the Pool* instance variables to point to
247 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000248 //
249 void addPoolPrototypes(Module *M);
250
Chris Lattner66df97d2002-03-29 06:21:38 +0000251
252 // CreatePools - Insert instructions into the function we are processing to
253 // create all of the memory pool objects themselves. This also inserts
254 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000255 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000256 //
257 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000258 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000259
Chris Lattner175f37c2002-03-29 03:40:59 +0000260 // processFunction - Convert a function to use pool allocation where
261 // available.
262 //
263 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000264
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000265 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000266 // pools specified in PoolDescs when modifying data structure nodes
267 // specified in the PoolDescs map. IPFGraph is the closed data structure
268 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000269 //
270 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000271 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000272
273 // transformFunction - Transform the specified function the specified way.
274 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000275 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000276 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000277 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000278 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000279 FunctionDSGraph &CallerIPGraph,
280 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000281
Chris Lattner64fd9352002-03-28 18:08:31 +0000282 };
283}
284
Chris Lattner692ad5d2002-03-29 17:13:46 +0000285// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000286// allocation node in a data structure graph is eligable for pool allocation.
287//
288static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000289 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattner175f37c2002-03-29 03:40:59 +0000290
291 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
292 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
Chris Lattnere0618ca2002-03-29 05:50:20 +0000293 return true; // Do not allow variable size allocations...
Chris Lattner175f37c2002-03-29 03:40:59 +0000294
Chris Lattnere0618ca2002-03-29 05:50:20 +0000295 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000296}
297
Chris Lattner175f37c2002-03-29 03:40:59 +0000298// processFunction - Convert a function to use pool allocation where
299// available.
300//
301bool PoolAllocate::processFunction(Function *F) {
302 // Get the closed datastructure graph for the current function... if there are
303 // any allocations in this graph that are not escaping, we need to pool
304 // allocate them here!
305 //
306 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
307
308 // Get all of the allocations that do not escape the current function. Since
309 // they are still live (they exist in the graph at all), this means we must
310 // have scalar references to these nodes, but the scalars are never returned.
311 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000312 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000313 IPGraph.getNonEscapingAllocations(Allocs);
314
315 // Filter out allocations that we cannot handle. Currently, this includes
316 // variable sized array allocations and alloca's (which we do not want to
317 // pool allocate)
318 //
319 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
320 Allocs.end());
321
322
323 if (Allocs.empty()) return false; // Nothing to do.
324
Chris Lattner692ad5d2002-03-29 17:13:46 +0000325 // Insert instructions into the function we are processing to create all of
326 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000327 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000328 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000329 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000330 map<DSNode*, PoolInfo> PoolDescs;
331 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000332
Chris Lattneracf19022002-04-14 06:14:41 +0000333#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000334 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000335#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000336
337 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000338 // how. To do this, we look at all of the scalars, seeing which functions are
339 // either used as a scalar value (so they return a data structure), or are
340 // passed one of our scalar values.
341 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000342 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000343
344 return true;
345}
346
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000347
Chris Lattner441e16f2002-04-12 20:23:15 +0000348//===----------------------------------------------------------------------===//
349//
350// NewInstructionCreator - This class is used to traverse the function being
351// modified, changing each instruction visit'ed to use and provide pointer
352// indexes instead of real pointers. This is what changes the body of a
353// function to use pool allocation.
354//
355class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000356 PoolAllocate &PoolAllocator;
357 vector<ScalarInfo> &Scalars;
358 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000359 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000360
Chris Lattner441e16f2002-04-12 20:23:15 +0000361 struct RefToUpdate {
362 Instruction *I; // Instruction to update
363 unsigned OpNum; // Operand number to update
364 Value *OldVal; // The old value it had
365
366 RefToUpdate(Instruction *i, unsigned o, Value *ov)
367 : I(i), OpNum(o), OldVal(ov) {}
368 };
369 vector<RefToUpdate> ReferencesToUpdate;
370
371 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000372 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
373 if (Scalars[i].Val == V) return Scalars[i];
374 assert(0 && "Scalar not found in getScalar!");
375 abort();
376 return Scalars[0];
377 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000378
379 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000380 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000381 if (Scalars[i].Val == V) return &Scalars[i];
382 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000383 }
384
Chris Lattner441e16f2002-04-12 20:23:15 +0000385 BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
386 BasicBlock *BB = I->getParent();
387 BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
388 BB->getInstList().replaceWith(RI, New);
389 XFormMap[I] = New;
390 return RI;
391 }
392
393 LoadInst *createPoolBaseInstruction(Value *PtrVal) {
394 const ScalarInfo &SC = getScalarRef(PtrVal);
395 vector<Value*> Args(3);
396 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
397 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
398 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
399 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
400 }
401
402
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000403public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000404 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
405 map<CallInst*, TransformFunctionInfo> &C,
406 map<Value*, Value*> &X)
407 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000408
Chris Lattner441e16f2002-04-12 20:23:15 +0000409
410 // updateReferences - The NewInstructionCreator is responsible for creating
411 // new instructions to replace the old ones in the function, and then link up
412 // references to values to their new values. For it to do this, however, it
413 // keeps track of information about the value mapping of old values to new
414 // values that need to be patched up. Given this value map and a set of
415 // instruction operands to patch, updateReferences performs the updates.
416 //
417 void updateReferences() {
418 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
419 RefToUpdate &Ref = ReferencesToUpdate[i];
420 Value *NewVal = XFormMap[Ref.OldVal];
421
422 if (NewVal == 0) {
423 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
424 cast<Constant>(Ref.OldVal)->isNullValue()) {
425 // Transform the null pointer into a null index... caching in XFormMap
426 XFormMap[Ref.OldVal] = NewVal =Constant::getNullConstant(POINTERTYPE);
427 //} else if (isa<Argument>(Ref.OldVal)) {
428 } else {
429 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
430 assert(XFormMap[Ref.OldVal] &&
431 "Reference to value that was not updated found!");
432 }
433 }
434
435 Ref.I->setOperand(Ref.OpNum, NewVal);
436 }
437 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000438 }
439
Chris Lattner441e16f2002-04-12 20:23:15 +0000440 //===--------------------------------------------------------------------===//
441 // Transformation methods:
442 // These methods specify how each type of instruction is transformed by the
443 // NewInstructionCreator instance...
444 //===--------------------------------------------------------------------===//
445
446 void visitGetElementPtrInst(GetElementPtrInst *I) {
447 assert(0 && "Cannot transform get element ptr instructions yet!");
448 }
449
450 // Replace the load instruction with a new one.
451 void visitLoadInst(LoadInst *I) {
452 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
453
454 // Cast our index to be a UIntTy so we can use it to index into the pool...
455 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
456 Type::UIntTy, I->getOperand(0)->getName());
457
458 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
459
460 vector<Value*> Indices(I->idx_begin(), I->idx_end());
461 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
462 "Cannot handle array indexing yet!");
463 Indices[0] = Index;
464 Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
465
466 // Replace the load instruction with the new load instruction...
467 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
468
469 // Add the pool base calculator instruction before the load...
470 II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
471
472 // Add the cast before the load instruction...
473 NewLoad->getParent()->getInstList().insert(II, Index);
474
475 // If not yielding a pool allocated pointer, use the new load value as the
476 // value in the program instead of the old load value...
477 //
478 if (!getScalar(I))
479 I->replaceAllUsesWith(NewLoad);
480 }
481
482 // Replace the store instruction with a new one. In the store instruction,
483 // the value stored could be a pointer type, meaning that the new store may
484 // have to change one or both of it's operands.
485 //
486 void visitStoreInst(StoreInst *I) {
487 assert(getScalar(I->getOperand(1)) &&
488 "Store inst found only storing pool allocated pointer. "
489 "Not imp yet!");
490
491 Value *Val = I->getOperand(0); // The value to store...
492 // Check to see if the value we are storing is a data structure pointer...
493 if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
494 Val = Constant::getNullConstant(POINTERTYPE); // Yes, store a dummy
495
496 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
497
498 // Cast our index to be a UIntTy so we can use it to index into the pool...
499 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
500 Type::UIntTy, I->getOperand(1)->getName());
501 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
502
503 vector<Value*> Indices(I->idx_begin(), I->idx_end());
504 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
505 "Cannot handle array indexing yet!");
506 Indices[0] = Index;
507 Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
508
509 if (Val != I->getOperand(0)) // Value stored was a pointer?
510 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
511
512
513 // Replace the store instruction with the cast instruction...
514 BasicBlock::iterator II = ReplaceInstWith(I, Index);
515
516 // Add the pool base calculator instruction before the index...
517 II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
518
519 // Add the store after the cast instruction...
520 Index->getParent()->getInstList().insert(II, NewStore);
521 }
522
523
524 // Create call to poolalloc for every malloc instruction
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000525 void visitMallocInst(MallocInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000526 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000527 Args.push_back(getScalarRef(I).Pool.Handle);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000528 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000529 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000530 }
531
Chris Lattner441e16f2002-04-12 20:23:15 +0000532 // Convert a call to poolfree for every free instruction...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000533 void visitFreeInst(FreeInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000534 // Create a new call to poolfree before the free instruction
535 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000536 Args.push_back(Constant::getNullConstant(POINTERTYPE));
537 Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
538 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
539 ReplaceInstWith(I, NewCall);
540 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 0, I->getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000541 }
542
543 // visitCallInst - Create a new call instruction with the extra arguments for
544 // all of the memory pools that the call needs.
545 //
546 void visitCallInst(CallInst *I) {
547 TransformFunctionInfo &TI = CallMap[I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000548
549 // Start with all of the old arguments...
550 vector<Value*> Args(I->op_begin()+1, I->op_end());
551
Chris Lattner441e16f2002-04-12 20:23:15 +0000552 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
553 // Replace all of the pointer arguments with our new pointer typed values.
554 if (TI.ArgInfo[i].ArgNo != -1)
555 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullConstant(POINTERTYPE);
556
557 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000558 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000559 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000560
561 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner441e16f2002-04-12 20:23:15 +0000562 Instruction *NewCall = new CallInst(NF, Args, I->getName());
563 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000564
Chris Lattner441e16f2002-04-12 20:23:15 +0000565 // Keep track of the mapping of operands so that we can resolve them to real
566 // values later.
567 Value *RetVal = NewCall;
568 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
569 if (TI.ArgInfo[i].ArgNo != -1)
570 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
571 I->getOperand(TI.ArgInfo[i].ArgNo+1)));
572 else
573 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000574
Chris Lattner441e16f2002-04-12 20:23:15 +0000575 // If not returning a pointer, use the new call as the value in the program
576 // instead of the old call...
577 //
578 if (RetVal)
579 I->replaceAllUsesWith(RetVal);
580 }
581
582 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
583 // nodes...
584 //
585 void visitPHINode(PHINode *PN) {
586 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
587 PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
588 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
589 NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
590 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
591 PN->getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000592 }
593
Chris Lattner441e16f2002-04-12 20:23:15 +0000594 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000595 }
596
Chris Lattner441e16f2002-04-12 20:23:15 +0000597 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner847b6e22002-03-30 20:53:14 +0000598 void visitReturnInst(ReturnInst *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000599 Instruction *Ret = new ReturnInst(Constant::getNullConstant(POINTERTYPE));
600 ReplaceInstWith(I, Ret);
601 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000602 }
603
Chris Lattner441e16f2002-04-12 20:23:15 +0000604 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000605 void visitSetCondInst(SetCondInst *SCI) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000606 BinaryOperator *I = (BinaryOperator*)SCI;
607 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
608 BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
609 DummyVal, I->getName());
610 ReplaceInstWith(I, New);
611
612 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
613 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
614
615 // Make sure branches refer to the new condition...
616 I->replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000617 }
618
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000619 void visitInstruction(Instruction *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000620 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000621 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000622};
623
624
Chris Lattner441e16f2002-04-12 20:23:15 +0000625
626
Chris Lattner0dc225c2002-03-31 07:17:46 +0000627static void addCallInfo(DataStructure *DS,
628 TransformFunctionInfo &TFI, CallInst *CI, int Arg,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000629 DSNode *GraphNode,
Chris Lattner441e16f2002-04-12 20:23:15 +0000630 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000631 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
632 assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
633 "Function call record should always call the same function!");
634 assert(TFI.Call == 0 || TFI.Call == CI &&
635 "Call element already filled in with different value!");
636 TFI.Func = CI->getCalledFunction();
637 TFI.Call = CI;
638 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(TFI.Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000639
640 // For now, add the entire graph that is pointed to by the call argument.
641 // This graph can and should be pruned to only what the function itself will
642 // use, because often this will be a dramatically smaller subset of what we
643 // are providing.
644 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000645 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000646 I != E; ++I)
647 TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
Chris Lattner396d5d72002-03-30 04:02:31 +0000648}
649
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000650
651// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000652// pools specified in PoolDescs when modifying data structure nodes specified in
653// the PoolDescs map. Specifically, scalar values specified in the Scalars
654// vector must be remapped. IPFGraph is the closed data structure graph for F,
655// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000656//
657void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000658 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000659
660 // Loop through the value map looking for scalars that refer to nonescaping
661 // allocations. Add them to the Scalars vector. Note that we may have
662 // multiple entries in the Scalars vector for each value if it points to more
663 // than one object.
664 //
665 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
666 vector<ScalarInfo> Scalars;
667
Chris Lattneracf19022002-04-14 06:14:41 +0000668#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +0000669 cerr << "Building scalar map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +0000670#endif
Chris Lattner847b6e22002-03-30 20:53:14 +0000671
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000672 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
673 E = ValMap.end(); I != E; ++I) {
674 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
675
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000676 // Check to see if the scalar points to a data structure node...
677 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
678 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
679
680 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +0000681 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
682 if (AI != PoolDescs.end()) { // Add it to the list of scalars
683 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +0000684#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000685 cerr << "\nScalar Mapping from:" << I->first
686 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +0000687#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000688 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000689 }
690 }
691
Chris Lattneracf19022002-04-14 06:14:41 +0000692#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +0000693 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +0000694 << "': Found the following values that point to poolable nodes:\n";
695
696 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000697 cerr << Scalars[i].Val;
698 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +0000699#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +0000700
Chris Lattner692ad5d2002-03-29 17:13:46 +0000701 // CallMap - Contain an entry for every call instruction that needs to be
702 // transformed. Each entry in the map contains information about what we need
703 // to do to each call site to change it to work.
704 //
705 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +0000706
Chris Lattner441e16f2002-04-12 20:23:15 +0000707 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000708 // how. To do this, we look at all of the scalars, seeing which functions are
709 // either used as a scalar value (so they return a data structure), or are
710 // passed one of our scalar values.
711 //
712 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
713 Value *ScalarVal = Scalars[i].Val;
714
715 // Check to see if the scalar _IS_ a call...
716 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
717 // If so, add information about the pool it will be returning...
Chris Lattner441e16f2002-04-12 20:23:15 +0000718 addCallInfo(DS, CallMap[CI], CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000719
720 // Check to see if the scalar is an operand to a call...
721 for (Value::use_iterator UI = ScalarVal->use_begin(),
722 UE = ScalarVal->use_end(); UI != UE; ++UI) {
723 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
724 // Find out which operand this is to the call instruction...
725 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
726 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
727 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
728
729 // FIXME: This is broken if the same pointer is passed to a call more
730 // than once! It will get multiple entries for the first pointer.
731
732 // Add the operand number and pool handle to the call table...
Chris Lattner441e16f2002-04-12 20:23:15 +0000733 addCallInfo(DS, CallMap[CI], CI, OI-CI->op_begin()-1,
734 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000735 }
736 }
737 }
738
Chris Lattneracf19022002-04-14 06:14:41 +0000739#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +0000740 // Print out call map...
741 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
742 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000743 cerr << "For call: " << I->first;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000744 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000745 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000746 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000747 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +0000748 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000749 }
Chris Lattneracf19022002-04-14 06:14:41 +0000750#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +0000751
752 // Loop through all of the call nodes, recursively creating the new functions
753 // that we want to call... This uses a map to prevent infinite recursion and
754 // to avoid duplicating functions unneccesarily.
755 //
756 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
757 E = CallMap.end(); I != E; ++I) {
758 // Make sure the entries are sorted.
759 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000760
761 // Transform all of the functions we need, or at least ensure there is a
762 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +0000763 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000764 }
765
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000766 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +0000767 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000768 // functions that we just hacked up.
769 //
770
771 // First step, find the instructions to be modified.
772 vector<Instruction*> InstToFix;
773 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
774 Value *ScalarVal = Scalars[i].Val;
775
776 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
777 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
778 InstToFix.push_back(Inst);
779
780 // All all of the instructions that use the scalar as an operand...
781 for (Value::use_iterator UI = ScalarVal->use_begin(),
782 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +0000783 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000784 }
785
Chris Lattner50e3d322002-04-13 23:13:18 +0000786 // Make sure that we get return instructions that return a null value from the
787 // function...
788 //
789 if (!IPFGraph.getRetNodes().empty()) {
790 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
791 PointerVal RetNode = IPFGraph.getRetNodes()[0];
792 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
793
794 // Only process return instructions if the return value of this function is
795 // part of one of the data structures we are transforming...
796 //
797 if (PoolDescs.count(RetNode.Node)) {
798 // Loop over all of the basic blocks, adding return instructions...
799 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
800 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
801 InstToFix.push_back(RI);
802 }
803 }
804
805
806
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000807 // Eliminate duplicates by sorting, then removing equal neighbors.
808 sort(InstToFix.begin(), InstToFix.end());
809 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
810
Chris Lattner441e16f2002-04-12 20:23:15 +0000811 // Loop over all of the instructions to transform, creating the new
812 // replacement instructions for them. This also unlinks them from the
813 // function so they can be safely deleted later.
814 //
815 map<Value*, Value*> XFormMap;
816 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000817
Chris Lattner441e16f2002-04-12 20:23:15 +0000818 // Visit all instructions... creating the new instructions that we need and
819 // unlinking the old instructions from the function...
820 //
Chris Lattneracf19022002-04-14 06:14:41 +0000821#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000822 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
823 cerr << "Fixing: " << InstToFix[i];
824 NIC.visit(InstToFix[i]);
825 }
Chris Lattneracf19022002-04-14 06:14:41 +0000826#else
827 NIC.visit(InstToFix.begin(), InstToFix.end());
828#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000829
830 // Make all instructions we will delete "let go" of their operands... so that
831 // we can safely delete Arguments whose types have changed...
832 //
833 for_each(InstToFix.begin(), InstToFix.end(),
834 mem_fun(&Instruction::dropAllReferences));
835
836 // Loop through all of the pointer arguments coming into the function,
837 // replacing them with arguments of POINTERTYPE to match the function type of
838 // the function.
839 //
840 FunctionType::ParamTypes::const_iterator TI =
841 F->getFunctionType()->getParamTypes().begin();
842 for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
843 E = F->getArgumentList().end(); I != E; ++I, ++TI) {
844 Argument *Arg = *I;
845 if (Arg->getType() != *TI) {
846 assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
847 Argument *NewArg = new Argument(*TI, Arg->getName());
848 XFormMap[Arg] = NewArg; // Map old arg into new arg...
849
850
851 // Replace the old argument and then delete it...
852 delete F->getArgumentList().replaceWith(I, NewArg);
853 }
854 }
855
856 // Now that all of the new instructions have been created, we can update all
857 // of the references to dummy values to be references to the actual values
858 // that are computed.
859 //
860 NIC.updateReferences();
861
Chris Lattneracf19022002-04-14 06:14:41 +0000862#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000863 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000864#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000865
866 // Delete all of the "instructions to fix"
867 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000868
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000869 // Since we have liberally hacked the function to pieces, we want to inform
870 // the datastructure pass that its internal representation is out of date.
871 //
872 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000873}
874
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000875static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
876 map<DSNode*, PointerValSet> &NodeMapping) {
877 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
878 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
879 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
880 DSNode *DestNode = PVS[i].Node;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000881
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000882 // Loop over all of the outgoing links in the mapped graph
883 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
884 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
885 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000886
887 // Add all of the node mappings now!
888 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
889 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
890 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
891 }
892 }
893 }
894}
895
896// CalculateNodeMapping - There is a partial isomorphism between the graph
897// passed in and the graph that is actually used by the function. We need to
898// figure out what this mapping is so that we can transformFunctionBody the
899// instructions in the function itself. Note that every node in the graph that
900// we are interested in must be both in the local graph of the called function,
901// and in the local graph of the calling function. Because of this, we only
902// define the mapping for these nodes [conveniently these are the only nodes we
903// CAN define a mapping for...]
Chris Lattner692ad5d2002-03-29 17:13:46 +0000904//
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000905// The roots of the graph that we are transforming is rooted in the arguments
906// passed into the function from the caller. This is where we start our
907// mapping calculation.
908//
909// The NodeMapping calculated maps from the callers graph to the called graph.
910//
Chris Lattner847b6e22002-03-30 20:53:14 +0000911static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000912 FunctionDSGraph &CallerGraph,
913 FunctionDSGraph &CalledGraph,
914 map<DSNode*, PointerValSet> &NodeMapping) {
915 int LastArgNo = -2;
916 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
917 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
918 // corresponds to...
919 //
920 // Only consider first node of sequence. Extra nodes may may be added
921 // to the TFI if the data structure requires more nodes than just the
922 // one the argument points to. We are only interested in the one the
923 // argument points to though.
924 //
925 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
926 if (TFI.ArgInfo[i].ArgNo == -1) {
927 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
928 NodeMapping);
929 } else {
930 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner847b6e22002-03-30 20:53:14 +0000931 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000932 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
933 NodeMapping);
934 }
935 LastArgNo = TFI.ArgInfo[i].ArgNo;
936 }
937 }
938}
939
940
941// transformFunction - Transform the specified function the specified way. It
942// we have already transformed that function that way, don't do anything. The
943// nodes in the TransformFunctionInfo come out of callers data structure graph.
944//
945void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000946 FunctionDSGraph &CallerIPGraph,
947 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +0000948 if (getTransformedFunction(TFI)) return; // Function xformation already done?
949
Chris Lattneracf19022002-04-14 06:14:41 +0000950#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000951 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +0000952 << TFI.Func->getName() << ":\n";
953 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
954 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
955 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +0000956#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +0000957
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000958 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +0000959
Chris Lattner291a1b12002-03-29 19:05:48 +0000960 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +0000961
Chris Lattner291a1b12002-03-29 19:05:48 +0000962 // Build the type for the new function that we are transforming
963 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +0000964 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +0000965 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
966 ArgTys.push_back(OldFuncType->getParamType(i));
967
Chris Lattner441e16f2002-04-12 20:23:15 +0000968 const Type *RetType = OldFuncType->getReturnType();
969
Chris Lattner291a1b12002-03-29 19:05:48 +0000970 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +0000971 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
972 if (TFI.ArgInfo[i].ArgNo == -1)
973 RetType = POINTERTYPE; // Return a pointer
974 else
975 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
976 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
977 ->second.PoolType));
978 }
Chris Lattner291a1b12002-03-29 19:05:48 +0000979
980 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +0000981 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
982 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +0000983
984 // The new function is internal, because we know that only we can call it.
985 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +0000986 // pointers (which look like the same value is always passed into a parameter,
987 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +0000988 //
989 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000990 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +0000991 CurModule->getFunctionList().push_back(NewFunc);
992
Chris Lattner441e16f2002-04-12 20:23:15 +0000993
Chris Lattneracf19022002-04-14 06:14:41 +0000994#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000995 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +0000996#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000997
Chris Lattner291a1b12002-03-29 19:05:48 +0000998 // Add the newly formed function to the TransformedFunctions table so that
999 // infinite recursion does not occur!
1000 //
1001 TransformedFunctions[TFI] = NewFunc;
1002
1003 // Add arguments to the function... starting with all of the old arguments
1004 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001005 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
Chris Lattner2e9fa6d2002-04-09 19:48:49 +00001006 const Argument *OFA = TFI.Func->getArgumentList()[i];
1007 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001008 NewFunc->getArgumentList().push_back(NFA);
1009 ArgMap.push_back(NFA); // Keep track of the arguments
1010 }
1011
1012 // Now add all of the arguments corresponding to pools passed in...
1013 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001014 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001015 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001016 if (AI.ArgNo == -1)
1017 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001018 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001019 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1020 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1021 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001022 NewFunc->getArgumentList().push_back(NFA);
1023 }
1024
1025 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001026 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001027
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001028 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001029 // it has extra arguments for the pools coming in. Now we have to get the
1030 // data structure graph for the function we are replacing, and figure out how
1031 // our graph nodes map to the graph nodes in the dest function.
1032 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001033 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001034
Chris Lattner441e16f2002-04-12 20:23:15 +00001035 // NodeMapping - Multimap from callers graph to called graph. We are
1036 // guaranteed that the called function graph has more nodes than the caller,
1037 // or exactly the same number of nodes. This is because the called function
1038 // might not know that two nodes are merged when considering the callers
1039 // context, but the caller obviously does. Because of this, a single node in
1040 // the calling function's data structure graph can map to multiple nodes in
1041 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001042 //
1043 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001044
Chris Lattner847b6e22002-03-30 20:53:14 +00001045 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001046 NodeMapping);
1047
1048 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001049#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001050 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001051 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1052 I != NodeMapping.end(); ++I) {
1053 cerr << "Map: "; I->first->print(cerr);
1054 cerr << "To: "; I->second.print(cerr);
1055 cerr << "\n";
1056 }
Chris Lattneracf19022002-04-14 06:14:41 +00001057#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001058
1059 // Fill in the PoolDescriptor information for the transformed function so that
1060 // it can determine which value holds the pool descriptor for each data
1061 // structure node that it accesses.
1062 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001063 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001064
Chris Lattneracf19022002-04-14 06:14:41 +00001065#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001066 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001067#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001068
Chris Lattner441e16f2002-04-12 20:23:15 +00001069 // Calculate as much of the pool descriptor map as possible. Since we have
1070 // the node mapping between the caller and callee functions, and we have the
1071 // pool descriptor information of the caller, we can calculate a partical pool
1072 // descriptor map for the called function.
1073 //
1074 // The nodes that we do not have complete information for are the ones that
1075 // are accessed by loading pointers derived from arguments passed in, but that
1076 // are not passed in directly. In this case, we have all of the information
1077 // except a pool value. If the called function refers to this pool, the pool
1078 // value will be loaded from the pool graph and added to the map as neccesary.
1079 //
1080 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1081 I != NodeMapping.end(); ++I) {
1082 DSNode *CallerNode = I->first;
1083 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001084
Chris Lattner441e16f2002-04-12 20:23:15 +00001085 // Check to see if we have a node pointer passed in for this value...
1086 Value *CalleeValue = 0;
1087 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1088 if (TFI.ArgInfo[a].Node == CallerNode) {
1089 // Calculate the argument number that the pool is to the function
1090 // call... The call instruction should not have the pool operands added
1091 // yet.
1092 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001093#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001094 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001095#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001096 assert(ArgNo < NewFunc->getArgumentList().size() &&
1097 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001098
Chris Lattner441e16f2002-04-12 20:23:15 +00001099 // Map the pool argument into the called function...
1100 CalleeValue = NewFunc->getArgumentList()[ArgNo];
1101 break; // Found value, quit loop
1102 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001103
Chris Lattner441e16f2002-04-12 20:23:15 +00001104 // Loop over all of the data structure nodes that this incoming node maps to
1105 // Creating a PoolInfo structure for them.
1106 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1107 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1108 DSNode *CalleeNode = I->second[i].Node;
1109
1110 // Add the descriptor. We already know everything about it by now, much
1111 // of it is the same as the caller info.
1112 //
1113 PoolDescs.insert(make_pair(CalleeNode,
1114 PoolInfo(CalleeNode, CalleeValue,
1115 CallerPI.NewType,
1116 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001117 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001118 }
1119
1120 // We must destroy the node mapping so that we don't have latent references
1121 // into the data structure graph for the new function. Otherwise we get
1122 // assertion failures when transformFunctionBody tries to invalidate the
1123 // graph.
1124 //
1125 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001126
1127 // Now that we know everything we need about the function, transform the body
1128 // now!
1129 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001130 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1131
Chris Lattneracf19022002-04-14 06:14:41 +00001132#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001133 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001134#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001135}
1136
Chris Lattner8f796d62002-04-13 19:25:57 +00001137static unsigned countPointerTypes(const Type *Ty) {
1138 if (isa<PointerType>(Ty)) {
1139 return 1;
1140 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1141 unsigned Num = 0;
1142 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1143 Num += countPointerTypes(STy->getElementTypes()[i]);
1144 return Num;
1145 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1146 return countPointerTypes(ATy->getElementType());
1147 } else {
1148 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1149 return 0;
1150 }
1151}
Chris Lattner66df97d2002-03-29 06:21:38 +00001152
1153// CreatePools - Insert instructions into the function we are processing to
1154// create all of the memory pool objects themselves. This also inserts
1155// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001156// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001157//
1158void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001159 map<DSNode*, PoolInfo> &PoolDescs) {
1160 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001161 vector<BasicBlock*> ReturnNodes;
1162 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1163 if (isa<ReturnInst>((*I)->getTerminator()))
1164 ReturnNodes.push_back(*I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001165
Chris Lattner441e16f2002-04-12 20:23:15 +00001166 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1167
1168 // First pass over the allocations to process...
1169 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1170 // Create the pooldescriptor mapping... with null entries for everything
1171 // except the node & NewType fields.
1172 //
1173 map<DSNode*, PoolInfo>::iterator PI =
1174 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1175
Chris Lattner8f796d62002-04-13 19:25:57 +00001176 // Add a symbol table entry for the new type if there was one for the old
1177 // type...
1178 string OldName = CurModule->getTypeName(Allocs[i]->getType());
1179 if (!OldName.empty())
1180 CurModule->addTypeName(OldName+".p", PI->second.NewType);
1181
Chris Lattner441e16f2002-04-12 20:23:15 +00001182 // Create the abstract pool types that will need to be resolved in a second
1183 // pass once an abstract type is created for each pool.
1184 //
1185 // Can only handle limited shapes for now...
1186 StructType *OldNodeTy = cast<StructType>(Allocs[i]->getType());
1187 vector<const Type*> PoolTypes;
1188
1189 // Pool type is the first element of the pool descriptor type...
1190 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001191
1192 unsigned NumPointers = countPointerTypes(OldNodeTy);
1193 while (NumPointers--) // Add a different opaque type for each pointer
1194 PoolTypes.push_back(OpaqueType::get());
1195
Chris Lattner441e16f2002-04-12 20:23:15 +00001196 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1197 "Node should have same number of pointers as pool!");
1198
Chris Lattner8f796d62002-04-13 19:25:57 +00001199 StructType *PoolType = StructType::get(PoolTypes);
1200
1201 // Add a symbol table entry for the pooltype if possible...
1202 if (!OldName.empty()) CurModule->addTypeName(OldName+".pool", PoolType);
1203
Chris Lattner441e16f2002-04-12 20:23:15 +00001204 // Create the pool type, with opaque values for pointers...
Chris Lattner8f796d62002-04-13 19:25:57 +00001205 AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001206#ifdef DEBUG_CREATE_POOLS
1207 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1208#endif
1209 }
1210
1211 // Now that we have types for all of the pool types, link them all together.
1212 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1213 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1214
1215 // Resolve all of the outgoing pointer types of this pool node...
1216 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1217 PointerValSet &PVS = Allocs[i]->getLink(p);
1218 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1219 " probably just leave the type opaque or something dumb.");
1220 unsigned Out;
1221 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1222 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1223
1224 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1225
1226 // The actual struct type could change each time through the loop, so it's
1227 // NOT loop invariant.
1228 StructType *PoolTy = cast<StructType>(PoolTyH.get());
1229
1230 // Get the opaque type...
1231 DerivedType *ElTy =
1232 cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1233
1234#ifdef DEBUG_CREATE_POOLS
1235 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1236 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1237#endif
1238
1239 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1240 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1241
1242#ifdef DEBUG_CREATE_POOLS
1243 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1244#endif
1245 }
1246 }
1247
1248 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001249 vector<Instruction*> EntryNodeInsts;
1250 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001251 PoolInfo &PI = PoolDescs[Allocs[i]];
1252
1253 // Fill in the pool type for this pool...
1254 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1255 assert(!PI.PoolType->isAbstract() &&
1256 "Pool type should not be abstract anymore!");
1257
Chris Lattnere0618ca2002-03-29 05:50:20 +00001258 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001259 AllocaInst *PoolAlloc
1260 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1261 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001262 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001263 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001264 AllocationInst *AI = Allocs[i]->getAllocation();
1265
1266 // Initialize the pool. We need to know how big each allocation is. For
1267 // our purposes here, we assume we are allocating a scalar, or array of
1268 // constant size.
1269 //
Chris Lattneracf19022002-04-14 06:14:41 +00001270 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001271
1272 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001273 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001274 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001275 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1276
Chris Lattner441e16f2002-04-12 20:23:15 +00001277 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001278 Args.clear();
1279 Args.push_back(PoolAlloc); // Pool to initialize
1280
Chris Lattnere0618ca2002-03-29 05:50:20 +00001281 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1282 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1283
1284 // Insert it before the return instruction...
1285 BasicBlock *RetNode = ReturnNodes[EN];
1286 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1287 }
1288 }
1289
Chris Lattner5da145b2002-04-13 19:52:54 +00001290 // Now that all of the pool descriptors have been created, link them together
1291 // so that called functions can get links as neccesary...
1292 //
1293 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1294 PoolInfo &PI = PoolDescs[Allocs[i]];
1295
1296 // For every pointer in the data structure, initialize a link that
1297 // indicates which pool to access...
1298 //
1299 vector<Value*> Indices(2);
1300 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1301 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1302 // Only store an entry for the field if the field is used!
1303 if (!PI.Node->getLink(l).empty()) {
1304 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1305 PointerVal PV = PI.Node->getLink(l)[0];
1306 assert(PV.Index == 0 && "Subindexing not supported yet!");
1307 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1308 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1309
1310 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1311 Indices));
1312 }
1313 }
1314
Chris Lattnere0618ca2002-03-29 05:50:20 +00001315 // Insert the entry node code into the entry block...
1316 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1317 EntryNodeInsts.begin(),
1318 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001319}
1320
1321
Chris Lattner441e16f2002-04-12 20:23:15 +00001322// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001323// module and update the Pool* instance variables to point to them.
1324//
1325void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001326 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001327 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001328 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001329 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001330 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001331
Chris Lattnere0618ca2002-03-29 05:50:20 +00001332 // Get pooldestroy function...
1333 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001334 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001335 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1336
Chris Lattnere0618ca2002-03-29 05:50:20 +00001337 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001338 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001339 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1340
1341 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001342 Args.push_back(POINTERTYPE); // Pointer to free
1343 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001344 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1345
1346 // Add the %PoolTy type to the symbol table of the module...
Chris Lattner441e16f2002-04-12 20:23:15 +00001347 //M->addTypeName("PoolTy", PoolTy->getElementType());
Chris Lattner175f37c2002-03-29 03:40:59 +00001348}
1349
1350
1351bool PoolAllocate::run(Module *M) {
1352 addPoolPrototypes(M);
1353 CurModule = M;
1354
1355 DS = &getAnalysis<DataStructure>();
1356 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001357
1358 // We cannot use an iterator here because it will get invalidated when we add
1359 // functions to the module later...
1360 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001361 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +00001362 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001363 if (Changed) {
1364 cerr << "Only processing one function\n";
1365 break;
1366 }
1367 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001368
1369 CurModule = 0;
1370 DS = 0;
1371 return false;
1372}
1373
1374
1375// createPoolAllocatePass - Global function to access the functionality of this
1376// pass...
1377//
Chris Lattner64fd9352002-03-28 18:08:31 +00001378Pass *createPoolAllocatePass() { return new PoolAllocate(); }