blob: 2b5ba858154d8aa752bba18aead5bca1dd69d56e [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//
Chris Lattner457e1ac2002-04-15 22:42:23 +00007// This pass requires a DCE & instcombine pass to be run after it for best
8// results.
9//
Chris Lattner64fd9352002-03-28 18:08:31 +000010//===----------------------------------------------------------------------===//
11
12#include "llvm/Transforms/IPO/PoolAllocate.h"
Chris Lattner291a1b12002-03-29 19:05:48 +000013#include "llvm/Transforms/CloneFunction.h"
Chris Lattner64fd9352002-03-28 18:08:31 +000014#include "llvm/Analysis/DataStructure.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000015#include "llvm/Analysis/DataStructureGraph.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000016#include "llvm/Module.h"
17#include "llvm/Function.h"
Chris Lattnerd92b01c2002-04-09 18:37:46 +000018#include "llvm/BasicBlock.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000019#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000020#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000021#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000023#include "llvm/DerivedTypes.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000024#include "llvm/ConstantVals.h"
25#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000026#include "llvm/Support/InstVisitor.h"
Chris Lattner2e9fa6d2002-04-09 19:48:49 +000027#include "llvm/Argument.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000028#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000029#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000030#include <algorithm>
Chris Lattner64fd9352002-03-28 18:08:31 +000031
Chris Lattner441e16f2002-04-12 20:23:15 +000032// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
33// creation phase in the top level function of a transformed data structure.
34//
Chris Lattneracf19022002-04-14 06:14:41 +000035//#define DEBUG_CREATE_POOLS 1
36
37// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
38// the transformation is doing.
39//
40//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000041
Chris Lattner457e1ac2002-04-15 22:42:23 +000042// DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
43// many static loads were eliminated from a function...
44//
45#define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
46
Chris Lattner50e3d322002-04-13 23:13:18 +000047#include "Support/CommandLine.h"
48enum PtrSize {
49 Ptr8bits, Ptr16bits, Ptr32bits
50};
51
52static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
Chris Lattneracf19022002-04-14 06:14:41 +000053 "Set pointer size for -poolalloc pass",
Chris Lattner50e3d322002-04-13 23:13:18 +000054 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
55 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
56 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"), 0);
57
Chris Lattner457e1ac2002-04-15 22:42:23 +000058static cl::Flag DisableRLE("no-pool-load-elim", "Disable pool load elimination after poolalloc pass", cl::Hidden);
59
Chris Lattner441e16f2002-04-12 20:23:15 +000060const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000061
Chris Lattnere0618ca2002-03-29 05:50:20 +000062// FIXME: This is dependant on the sparc backend layout conventions!!
63static TargetData TargetData("test");
64
Chris Lattner50e3d322002-04-13 23:13:18 +000065static const Type *getPointerTransformedType(const Type *Ty) {
66 if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
67 return POINTERTYPE;
68 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
69 vector<const Type *> NewElTypes;
70 NewElTypes.reserve(STy->getElementTypes().size());
71 for (StructType::ElementTypes::const_iterator
72 I = STy->getElementTypes().begin(),
73 E = STy->getElementTypes().end(); I != E; ++I)
74 NewElTypes.push_back(getPointerTransformedType(*I));
75 return StructType::get(NewElTypes);
76 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
77 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
78 ATy->getNumElements());
79 } else {
80 assert(Ty->isPrimitiveType() && "Unknown derived type!");
81 return Ty;
82 }
83}
84
Chris Lattner64fd9352002-03-28 18:08:31 +000085namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000086 struct PoolInfo {
87 DSNode *Node; // The node this pool allocation represents
88 Value *Handle; // LLVM value of the pool in the current context
89 const Type *NewType; // The transformed type of the memory objects
90 const Type *PoolType; // The type of the pool
91
92 const Type *getOldType() const { return Node->getType(); }
93
94 PoolInfo() { // Define a default ctor for map::operator[]
95 cerr << "Map subscript used to get element that doesn't exist!\n";
96 abort(); // Invalid
97 }
98
99 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
100 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
101 // Handle can be null...
102 assert(N && NT && PT && "Pool info null!");
103 }
104
105 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
106 assert(N && "Invalid pool info!");
107
108 // The new type of the memory object is the same as the old type, except
109 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000110 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000111 }
112 };
113
Chris Lattner692ad5d2002-03-29 17:13:46 +0000114 // ScalarInfo - Information about an LLVM value that we know points to some
115 // datastructure we are processing.
116 //
117 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000118 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000119 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000120
Chris Lattner441e16f2002-04-12 20:23:15 +0000121 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
122 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000123 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000124 };
125
Chris Lattner396d5d72002-03-30 04:02:31 +0000126 // CallArgInfo - Information on one operand for a call that got expanded.
127 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000128 int ArgNo; // Call argument number this corresponds to
129 DSNode *Node; // The graph node for the pool
130 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000131
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000132 CallArgInfo(int Arg, DSNode *N, Value *PH)
133 : ArgNo(Arg), Node(N), PoolHandle(PH) {
134 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000135 }
136
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000137 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000138 bool operator<(const CallArgInfo &CAI) const {
139 return ArgNo < CAI.ArgNo;
140 }
141 };
142
Chris Lattner692ad5d2002-03-29 17:13:46 +0000143 // TransformFunctionInfo - Information about how a function eeds to be
144 // transformed.
145 //
146 struct TransformFunctionInfo {
147 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000148 // processed. Each CallArgInfo corresponds to an argument that needs to
149 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000150 //
151 // As a special case, "argument" number -1 corresponds to the return value.
152 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000153 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000154
155 // Func - The function to be transformed...
156 Function *Func;
157
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000158 // The call instruction that is used to map CallArgInfo PoolHandle values
159 // into the new function values.
160 CallInst *Call;
161
Chris Lattner692ad5d2002-03-29 17:13:46 +0000162 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000163 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000164
Chris Lattner396d5d72002-03-30 04:02:31 +0000165 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000166 if (Func < TFI.Func) return true;
167 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000168 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
169 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000170 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000171 }
172
173 void finalizeConstruction() {
174 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000175 // argument records, in order. Note that this must be a stable sort so
176 // that the entries with the same sorting criteria (ie they are multiple
177 // pool entries for the same argument) are kept in depth first order.
178 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000179 }
180 };
181
182
183 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000184 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000185 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000186 switch (ReqPointerSize) {
187 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
188 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
189 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
190 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000191
192 CurModule = 0; DS = 0;
193 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000194 }
195
Chris Lattner441e16f2002-04-12 20:23:15 +0000196 // getPoolType - Get the type used by the backend for a pool of a particular
197 // type. This pool record is used to allocate nodes of type NodeType.
198 //
199 // Here, PoolTy = { NodeType*, sbyte*, uint }*
200 //
201 const StructType *getPoolType(const Type *NodeType) {
202 vector<const Type*> PoolElements;
203 PoolElements.push_back(PointerType::get(NodeType));
204 PoolElements.push_back(PointerType::get(Type::SByteTy));
205 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000206 StructType *Result = StructType::get(PoolElements);
207
208 // Add a name to the symbol table to correspond to the backend
209 // representation of this pool...
210 assert(CurModule && "No current module!?");
211 string Name = CurModule->getTypeName(NodeType);
212 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
213 CurModule->addTypeName(Name+"oolbe", Result);
214
215 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000216 }
217
Chris Lattner175f37c2002-03-29 03:40:59 +0000218 bool run(Module *M);
219
220 // getAnalysisUsageInfo - This function requires data structure information
221 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000222 //
223 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
Chris Lattner175f37c2002-03-29 03:40:59 +0000224 Pass::AnalysisSet &,Pass::AnalysisSet &) {
Chris Lattner64fd9352002-03-28 18:08:31 +0000225 Required.push_back(DataStructure::ID);
226 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000227
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000228 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000229 // CurModule - The module being processed.
230 Module *CurModule;
231
232 // DS - The data structure graph for the module being processed.
233 DataStructure *DS;
234
235 // Prototypes that we add to support pool allocation...
236 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
237
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000238 // The map of already transformed functions... note that the keys of this
239 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
240 // of the ArgInfo elements.
241 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000242 map<TransformFunctionInfo, Function*> TransformedFunctions;
243
244 // getTransformedFunction - Get a transformed function, or return null if
245 // the function specified hasn't been transformed yet.
246 //
247 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
248 map<TransformFunctionInfo, Function*>::const_iterator I =
249 TransformedFunctions.find(TFI);
250 if (I != TransformedFunctions.end()) return I->second;
251 return 0;
252 }
253
254
Chris Lattner441e16f2002-04-12 20:23:15 +0000255 // addPoolPrototypes - Add prototypes for the pool functions to the
256 // specified module and update the Pool* instance variables to point to
257 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000258 //
259 void addPoolPrototypes(Module *M);
260
Chris Lattner66df97d2002-03-29 06:21:38 +0000261
262 // CreatePools - Insert instructions into the function we are processing to
263 // create all of the memory pool objects themselves. This also inserts
264 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000265 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000266 //
267 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000268 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000269
Chris Lattner175f37c2002-03-29 03:40:59 +0000270 // processFunction - Convert a function to use pool allocation where
271 // available.
272 //
273 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000274
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000275 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000276 // pools specified in PoolDescs when modifying data structure nodes
277 // specified in the PoolDescs map. IPFGraph is the closed data structure
278 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000279 //
280 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000281 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000282
283 // transformFunction - Transform the specified function the specified way.
284 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000285 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000286 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000287 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000288 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000289 FunctionDSGraph &CallerIPGraph,
290 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000291
Chris Lattner64fd9352002-03-28 18:08:31 +0000292 };
293}
294
Chris Lattner692ad5d2002-03-29 17:13:46 +0000295// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000296// allocation node in a data structure graph is eligable for pool allocation.
297//
298static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000299 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattner175f37c2002-03-29 03:40:59 +0000300
301 MallocInst *MI = cast<MallocInst>(DS->getAllocation());
302 if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
Chris Lattnere0618ca2002-03-29 05:50:20 +0000303 return true; // Do not allow variable size allocations...
Chris Lattner175f37c2002-03-29 03:40:59 +0000304
Chris Lattnere0618ca2002-03-29 05:50:20 +0000305 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000306}
307
Chris Lattner175f37c2002-03-29 03:40:59 +0000308// processFunction - Convert a function to use pool allocation where
309// available.
310//
311bool PoolAllocate::processFunction(Function *F) {
312 // Get the closed datastructure graph for the current function... if there are
313 // any allocations in this graph that are not escaping, we need to pool
314 // allocate them here!
315 //
316 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
317
318 // Get all of the allocations that do not escape the current function. Since
319 // they are still live (they exist in the graph at all), this means we must
320 // have scalar references to these nodes, but the scalars are never returned.
321 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000322 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000323 IPGraph.getNonEscapingAllocations(Allocs);
324
325 // Filter out allocations that we cannot handle. Currently, this includes
326 // variable sized array allocations and alloca's (which we do not want to
327 // pool allocate)
328 //
329 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
330 Allocs.end());
331
332
333 if (Allocs.empty()) return false; // Nothing to do.
334
Chris Lattner692ad5d2002-03-29 17:13:46 +0000335 // Insert instructions into the function we are processing to create all of
336 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000337 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000338 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000339 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000340 map<DSNode*, PoolInfo> PoolDescs;
341 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000342
Chris Lattneracf19022002-04-14 06:14:41 +0000343#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000344 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000345#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000346
347 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000348 // how. To do this, we look at all of the scalars, seeing which functions are
349 // either used as a scalar value (so they return a data structure), or are
350 // passed one of our scalar values.
351 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000352 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000353
354 return true;
355}
356
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000357
Chris Lattner441e16f2002-04-12 20:23:15 +0000358//===----------------------------------------------------------------------===//
359//
360// NewInstructionCreator - This class is used to traverse the function being
361// modified, changing each instruction visit'ed to use and provide pointer
362// indexes instead of real pointers. This is what changes the body of a
363// function to use pool allocation.
364//
365class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000366 PoolAllocate &PoolAllocator;
367 vector<ScalarInfo> &Scalars;
368 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000369 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000370
Chris Lattner441e16f2002-04-12 20:23:15 +0000371 struct RefToUpdate {
372 Instruction *I; // Instruction to update
373 unsigned OpNum; // Operand number to update
374 Value *OldVal; // The old value it had
375
376 RefToUpdate(Instruction *i, unsigned o, Value *ov)
377 : I(i), OpNum(o), OldVal(ov) {}
378 };
379 vector<RefToUpdate> ReferencesToUpdate;
380
381 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000382 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
383 if (Scalars[i].Val == V) return Scalars[i];
384 assert(0 && "Scalar not found in getScalar!");
385 abort();
386 return Scalars[0];
387 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000388
389 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000390 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000391 if (Scalars[i].Val == V) return &Scalars[i];
392 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000393 }
394
Chris Lattner441e16f2002-04-12 20:23:15 +0000395 BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
396 BasicBlock *BB = I->getParent();
397 BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
398 BB->getInstList().replaceWith(RI, New);
399 XFormMap[I] = New;
400 return RI;
401 }
402
403 LoadInst *createPoolBaseInstruction(Value *PtrVal) {
404 const ScalarInfo &SC = getScalarRef(PtrVal);
405 vector<Value*> Args(3);
406 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
407 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
408 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
409 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
410 }
411
412
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000413public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000414 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
415 map<CallInst*, TransformFunctionInfo> &C,
416 map<Value*, Value*> &X)
417 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000418
Chris Lattner441e16f2002-04-12 20:23:15 +0000419
420 // updateReferences - The NewInstructionCreator is responsible for creating
421 // new instructions to replace the old ones in the function, and then link up
422 // references to values to their new values. For it to do this, however, it
423 // keeps track of information about the value mapping of old values to new
424 // values that need to be patched up. Given this value map and a set of
425 // instruction operands to patch, updateReferences performs the updates.
426 //
427 void updateReferences() {
428 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
429 RefToUpdate &Ref = ReferencesToUpdate[i];
430 Value *NewVal = XFormMap[Ref.OldVal];
431
432 if (NewVal == 0) {
433 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
434 cast<Constant>(Ref.OldVal)->isNullValue()) {
435 // Transform the null pointer into a null index... caching in XFormMap
436 XFormMap[Ref.OldVal] = NewVal =Constant::getNullConstant(POINTERTYPE);
437 //} else if (isa<Argument>(Ref.OldVal)) {
438 } else {
439 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
440 assert(XFormMap[Ref.OldVal] &&
441 "Reference to value that was not updated found!");
442 }
443 }
444
445 Ref.I->setOperand(Ref.OpNum, NewVal);
446 }
447 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000448 }
449
Chris Lattner441e16f2002-04-12 20:23:15 +0000450 //===--------------------------------------------------------------------===//
451 // Transformation methods:
452 // These methods specify how each type of instruction is transformed by the
453 // NewInstructionCreator instance...
454 //===--------------------------------------------------------------------===//
455
456 void visitGetElementPtrInst(GetElementPtrInst *I) {
457 assert(0 && "Cannot transform get element ptr instructions yet!");
458 }
459
460 // Replace the load instruction with a new one.
461 void visitLoadInst(LoadInst *I) {
462 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
463
464 // Cast our index to be a UIntTy so we can use it to index into the pool...
465 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
466 Type::UIntTy, I->getOperand(0)->getName());
467
468 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
469
470 vector<Value*> Indices(I->idx_begin(), I->idx_end());
471 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
472 "Cannot handle array indexing yet!");
473 Indices[0] = Index;
474 Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
475
476 // Replace the load instruction with the new load instruction...
477 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
478
479 // Add the pool base calculator instruction before the load...
480 II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
481
482 // Add the cast before the load instruction...
483 NewLoad->getParent()->getInstList().insert(II, Index);
484
485 // If not yielding a pool allocated pointer, use the new load value as the
486 // value in the program instead of the old load value...
487 //
488 if (!getScalar(I))
489 I->replaceAllUsesWith(NewLoad);
490 }
491
492 // Replace the store instruction with a new one. In the store instruction,
493 // the value stored could be a pointer type, meaning that the new store may
494 // have to change one or both of it's operands.
495 //
496 void visitStoreInst(StoreInst *I) {
497 assert(getScalar(I->getOperand(1)) &&
498 "Store inst found only storing pool allocated pointer. "
499 "Not imp yet!");
500
501 Value *Val = I->getOperand(0); // The value to store...
502 // Check to see if the value we are storing is a data structure pointer...
503 if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
504 Val = Constant::getNullConstant(POINTERTYPE); // Yes, store a dummy
505
506 Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
507
508 // Cast our index to be a UIntTy so we can use it to index into the pool...
509 CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
510 Type::UIntTy, I->getOperand(1)->getName());
511 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
512
513 vector<Value*> Indices(I->idx_begin(), I->idx_end());
514 assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
515 "Cannot handle array indexing yet!");
516 Indices[0] = Index;
517 Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
518
519 if (Val != I->getOperand(0)) // Value stored was a pointer?
520 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
521
522
523 // Replace the store instruction with the cast instruction...
524 BasicBlock::iterator II = ReplaceInstWith(I, Index);
525
526 // Add the pool base calculator instruction before the index...
527 II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
528
529 // Add the store after the cast instruction...
530 Index->getParent()->getInstList().insert(II, NewStore);
531 }
532
533
534 // Create call to poolalloc for every malloc instruction
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000535 void visitMallocInst(MallocInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000536 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000537 Args.push_back(getScalarRef(I).Pool.Handle);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000538 CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000539 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000540 }
541
Chris Lattner441e16f2002-04-12 20:23:15 +0000542 // Convert a call to poolfree for every free instruction...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000543 void visitFreeInst(FreeInst *I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000544 // Create a new call to poolfree before the free instruction
545 vector<Value*> Args;
Chris Lattner441e16f2002-04-12 20:23:15 +0000546 Args.push_back(Constant::getNullConstant(POINTERTYPE));
547 Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
548 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
549 ReplaceInstWith(I, NewCall);
550 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 0, I->getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000551 }
552
553 // visitCallInst - Create a new call instruction with the extra arguments for
554 // all of the memory pools that the call needs.
555 //
556 void visitCallInst(CallInst *I) {
557 TransformFunctionInfo &TI = CallMap[I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000558
559 // Start with all of the old arguments...
560 vector<Value*> Args(I->op_begin()+1, I->op_end());
561
Chris Lattner441e16f2002-04-12 20:23:15 +0000562 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
563 // Replace all of the pointer arguments with our new pointer typed values.
564 if (TI.ArgInfo[i].ArgNo != -1)
565 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullConstant(POINTERTYPE);
566
567 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000568 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000569 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000570
571 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner441e16f2002-04-12 20:23:15 +0000572 Instruction *NewCall = new CallInst(NF, Args, I->getName());
573 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000574
Chris Lattner441e16f2002-04-12 20:23:15 +0000575 // Keep track of the mapping of operands so that we can resolve them to real
576 // values later.
577 Value *RetVal = NewCall;
578 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
579 if (TI.ArgInfo[i].ArgNo != -1)
580 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
581 I->getOperand(TI.ArgInfo[i].ArgNo+1)));
582 else
583 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000584
Chris Lattner441e16f2002-04-12 20:23:15 +0000585 // If not returning a pointer, use the new call as the value in the program
586 // instead of the old call...
587 //
588 if (RetVal)
589 I->replaceAllUsesWith(RetVal);
590 }
591
592 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
593 // nodes...
594 //
595 void visitPHINode(PHINode *PN) {
596 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
597 PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
598 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
599 NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
600 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
601 PN->getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000602 }
603
Chris Lattner441e16f2002-04-12 20:23:15 +0000604 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000605 }
606
Chris Lattner441e16f2002-04-12 20:23:15 +0000607 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner847b6e22002-03-30 20:53:14 +0000608 void visitReturnInst(ReturnInst *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000609 Instruction *Ret = new ReturnInst(Constant::getNullConstant(POINTERTYPE));
610 ReplaceInstWith(I, Ret);
611 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000612 }
613
Chris Lattner441e16f2002-04-12 20:23:15 +0000614 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000615 void visitSetCondInst(SetCondInst *SCI) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000616 BinaryOperator *I = (BinaryOperator*)SCI;
617 Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
618 BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
619 DummyVal, I->getName());
620 ReplaceInstWith(I, New);
621
622 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
623 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
624
625 // Make sure branches refer to the new condition...
626 I->replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000627 }
628
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000629 void visitInstruction(Instruction *I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000630 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000631 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000632};
633
634
Chris Lattner457e1ac2002-04-15 22:42:23 +0000635// PoolBaseLoadEliminator - Every load and store through a pool allocated
636// pointer causes a load of the real pool base out of the pool descriptor.
637// Iterate through the function, doing a local elimination pass of duplicate
638// loads. This attempts to turn the all too common:
639//
640// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
641// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
642// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
643// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
644//
645// into:
646// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
647// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
648// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
649//
650//
651class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
652 // PoolDescValues - Keep track of the values in the current function that are
653 // pool descriptors (loads from which we want to eliminate).
654 //
655 vector<Value*> PoolDescValues;
656
657 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
658 // when referencing a pool descriptor.
659 //
660 map<Value*, LoadInst*> PoolDescMap;
661
662 // These two fields keep track of statistics of how effective we are, if
663 // debugging is enabled.
664 //
665 unsigned Eliminated, Remaining;
666public:
667 // Compact the pool descriptor map into a list of the pool descriptors in the
668 // current context that we should know about...
669 //
670 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
671 Eliminated = Remaining = 0;
672 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
673 E = PoolDescs.end(); I != E; ++I)
674 PoolDescValues.push_back(I->second.Handle);
675
676 // Remove duplicates from the list of pool values
677 sort(PoolDescValues.begin(), PoolDescValues.end());
678 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
679 PoolDescValues.end());
680 }
681
682#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
683 void visitFunction(Function *F) {
684 cerr << "Pool Load Elim '" << F->getName() << "'\t";
685 }
686 ~PoolBaseLoadEliminator() {
687 unsigned Total = Eliminated+Remaining;
688 if (Total)
689 cerr << "removed " << Eliminated << "["
690 << Eliminated*100/Total << "%] loads, leaving "
691 << Remaining << ".\n";
692 }
693#endif
694
695 // Loop over the function, looking for loads to eliminate. Because we are a
696 // local transformation, we reset all of our state when we enter a new basic
697 // block.
698 //
699 void visitBasicBlock(BasicBlock *) {
700 PoolDescMap.clear(); // Forget state.
701 }
702
703 // Starting with an empty basic block, we scan it looking for loads of the
704 // pool descriptor. When we find a load, we add it to the PoolDescMap,
705 // indicating that we have a value available to recycle next time we see the
706 // poolbase of this instruction being loaded.
707 //
708 void visitLoadInst(LoadInst *LI) {
709 Value *LoadAddr = LI->getPointerOperand();
710 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
711 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
712 LI->replaceAllUsesWith(VIt->second); // Make the current load dead
713 ++Eliminated;
714 } else {
715 // This load might not be a load of a pool pointer, check to see if it is
716 if (LI->getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
717 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
718 PoolDescValues.end()) {
719
720 assert("Make sure it's a load of the pool base, not a chaining field" &&
721 LI->getOperand(1) == Constant::getNullConstant(Type::UIntTy) &&
722 LI->getOperand(2) == Constant::getNullConstant(Type::UByteTy) &&
723 LI->getOperand(3) == Constant::getNullConstant(Type::UByteTy));
724
725 // If it is a load of a pool base, keep track of it for future reference
726 PoolDescMap.insert(make_pair(LoadAddr, LI));
727 ++Remaining;
728 }
729 }
730 }
731
732 // If we run across a function call, forget all state... Calls to
733 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
734 // reloaded the next time it is used. Furthermore, a call to a random
735 // function might call one of these functions, so be conservative. Through
736 // more analysis, this could be improved in the future.
737 //
738 void visitCallInst(CallInst *) {
739 PoolDescMap.clear();
740 }
741};
742
Chris Lattner441e16f2002-04-12 20:23:15 +0000743
744
Chris Lattner0dc225c2002-03-31 07:17:46 +0000745static void addCallInfo(DataStructure *DS,
746 TransformFunctionInfo &TFI, CallInst *CI, int Arg,
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000747 DSNode *GraphNode,
Chris Lattner441e16f2002-04-12 20:23:15 +0000748 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000749 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
750 assert(TFI.Func == 0 || TFI.Func == CI->getCalledFunction() &&
751 "Function call record should always call the same function!");
752 assert(TFI.Call == 0 || TFI.Call == CI &&
753 "Call element already filled in with different value!");
754 TFI.Func = CI->getCalledFunction();
755 TFI.Call = CI;
756 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(TFI.Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000757
758 // For now, add the entire graph that is pointed to by the call argument.
759 // This graph can and should be pruned to only what the function itself will
760 // use, because often this will be a dramatically smaller subset of what we
761 // are providing.
762 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000763 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000764 I != E; ++I)
765 TFI.ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
Chris Lattner396d5d72002-03-30 04:02:31 +0000766}
767
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000768
769// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000770// pools specified in PoolDescs when modifying data structure nodes specified in
771// the PoolDescs map. Specifically, scalar values specified in the Scalars
772// vector must be remapped. IPFGraph is the closed data structure graph for F,
773// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000774//
775void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000776 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000777
778 // Loop through the value map looking for scalars that refer to nonescaping
779 // allocations. Add them to the Scalars vector. Note that we may have
780 // multiple entries in the Scalars vector for each value if it points to more
781 // than one object.
782 //
783 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
784 vector<ScalarInfo> Scalars;
785
Chris Lattneracf19022002-04-14 06:14:41 +0000786#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +0000787 cerr << "Building scalar map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +0000788#endif
Chris Lattner847b6e22002-03-30 20:53:14 +0000789
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000790 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
791 E = ValMap.end(); I != E; ++I) {
792 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
793
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000794 // Check to see if the scalar points to a data structure node...
795 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
796 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
797
798 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +0000799 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
800 if (AI != PoolDescs.end()) { // Add it to the list of scalars
801 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +0000802#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000803 cerr << "\nScalar Mapping from:" << I->first
804 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +0000805#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000806 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000807 }
808 }
809
Chris Lattneracf19022002-04-14 06:14:41 +0000810#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +0000811 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +0000812 << "': Found the following values that point to poolable nodes:\n";
813
814 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000815 cerr << Scalars[i].Val;
816 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +0000817#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +0000818
Chris Lattner692ad5d2002-03-29 17:13:46 +0000819 // CallMap - Contain an entry for every call instruction that needs to be
820 // transformed. Each entry in the map contains information about what we need
821 // to do to each call site to change it to work.
822 //
823 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +0000824
Chris Lattner441e16f2002-04-12 20:23:15 +0000825 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000826 // how. To do this, we look at all of the scalars, seeing which functions are
827 // either used as a scalar value (so they return a data structure), or are
828 // passed one of our scalar values.
829 //
830 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
831 Value *ScalarVal = Scalars[i].Val;
832
833 // Check to see if the scalar _IS_ a call...
834 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
835 // If so, add information about the pool it will be returning...
Chris Lattner441e16f2002-04-12 20:23:15 +0000836 addCallInfo(DS, CallMap[CI], CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000837
838 // Check to see if the scalar is an operand to a call...
839 for (Value::use_iterator UI = ScalarVal->use_begin(),
840 UE = ScalarVal->use_end(); UI != UE; ++UI) {
841 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
842 // Find out which operand this is to the call instruction...
843 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
844 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
845 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
846
847 // FIXME: This is broken if the same pointer is passed to a call more
848 // than once! It will get multiple entries for the first pointer.
849
850 // Add the operand number and pool handle to the call table...
Chris Lattner441e16f2002-04-12 20:23:15 +0000851 addCallInfo(DS, CallMap[CI], CI, OI-CI->op_begin()-1,
852 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000853 }
854 }
855 }
856
Chris Lattneracf19022002-04-14 06:14:41 +0000857#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +0000858 // Print out call map...
859 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
860 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000861 cerr << "For call: " << I->first;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000862 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000863 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000864 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000865 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +0000866 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +0000867 }
Chris Lattneracf19022002-04-14 06:14:41 +0000868#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +0000869
870 // Loop through all of the call nodes, recursively creating the new functions
871 // that we want to call... This uses a map to prevent infinite recursion and
872 // to avoid duplicating functions unneccesarily.
873 //
874 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
875 E = CallMap.end(); I != E; ++I) {
876 // Make sure the entries are sorted.
877 I->second.finalizeConstruction();
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000878
879 // Transform all of the functions we need, or at least ensure there is a
880 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +0000881 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000882 }
883
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000884 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +0000885 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000886 // functions that we just hacked up.
887 //
888
889 // First step, find the instructions to be modified.
890 vector<Instruction*> InstToFix;
891 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
892 Value *ScalarVal = Scalars[i].Val;
893
894 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
895 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
896 InstToFix.push_back(Inst);
897
898 // All all of the instructions that use the scalar as an operand...
899 for (Value::use_iterator UI = ScalarVal->use_begin(),
900 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +0000901 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000902 }
903
Chris Lattner50e3d322002-04-13 23:13:18 +0000904 // Make sure that we get return instructions that return a null value from the
905 // function...
906 //
907 if (!IPFGraph.getRetNodes().empty()) {
908 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
909 PointerVal RetNode = IPFGraph.getRetNodes()[0];
910 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
911
912 // Only process return instructions if the return value of this function is
913 // part of one of the data structures we are transforming...
914 //
915 if (PoolDescs.count(RetNode.Node)) {
916 // Loop over all of the basic blocks, adding return instructions...
917 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
918 if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
919 InstToFix.push_back(RI);
920 }
921 }
922
923
924
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000925 // Eliminate duplicates by sorting, then removing equal neighbors.
926 sort(InstToFix.begin(), InstToFix.end());
927 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
928
Chris Lattner441e16f2002-04-12 20:23:15 +0000929 // Loop over all of the instructions to transform, creating the new
930 // replacement instructions for them. This also unlinks them from the
931 // function so they can be safely deleted later.
932 //
933 map<Value*, Value*> XFormMap;
934 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000935
Chris Lattner441e16f2002-04-12 20:23:15 +0000936 // Visit all instructions... creating the new instructions that we need and
937 // unlinking the old instructions from the function...
938 //
Chris Lattneracf19022002-04-14 06:14:41 +0000939#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000940 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
941 cerr << "Fixing: " << InstToFix[i];
942 NIC.visit(InstToFix[i]);
943 }
Chris Lattneracf19022002-04-14 06:14:41 +0000944#else
945 NIC.visit(InstToFix.begin(), InstToFix.end());
946#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000947
948 // Make all instructions we will delete "let go" of their operands... so that
949 // we can safely delete Arguments whose types have changed...
950 //
951 for_each(InstToFix.begin(), InstToFix.end(),
952 mem_fun(&Instruction::dropAllReferences));
953
954 // Loop through all of the pointer arguments coming into the function,
955 // replacing them with arguments of POINTERTYPE to match the function type of
956 // the function.
957 //
958 FunctionType::ParamTypes::const_iterator TI =
959 F->getFunctionType()->getParamTypes().begin();
960 for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
961 E = F->getArgumentList().end(); I != E; ++I, ++TI) {
962 Argument *Arg = *I;
963 if (Arg->getType() != *TI) {
964 assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
965 Argument *NewArg = new Argument(*TI, Arg->getName());
966 XFormMap[Arg] = NewArg; // Map old arg into new arg...
967
968
969 // Replace the old argument and then delete it...
970 delete F->getArgumentList().replaceWith(I, NewArg);
971 }
972 }
973
974 // Now that all of the new instructions have been created, we can update all
975 // of the references to dummy values to be references to the actual values
976 // that are computed.
977 //
978 NIC.updateReferences();
979
Chris Lattneracf19022002-04-14 06:14:41 +0000980#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000981 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000982#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000983
984 // Delete all of the "instructions to fix"
985 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000986
Chris Lattner457e1ac2002-04-15 22:42:23 +0000987 // Eliminate pool base loads that we can easily prove are redundant
988 if (!DisableRLE)
989 PoolBaseLoadEliminator(PoolDescs).visit(F);
990
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000991 // Since we have liberally hacked the function to pieces, we want to inform
992 // the datastructure pass that its internal representation is out of date.
993 //
994 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000995}
996
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000997static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
998 map<DSNode*, PointerValSet> &NodeMapping) {
999 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
1000 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
1001 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
1002 DSNode *DestNode = PVS[i].Node;
Chris Lattner692ad5d2002-03-29 17:13:46 +00001003
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001004 // Loop over all of the outgoing links in the mapped graph
1005 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
1006 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
1007 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001008
1009 // Add all of the node mappings now!
1010 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
1011 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
1012 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
1013 }
1014 }
1015 }
1016}
1017
1018// CalculateNodeMapping - There is a partial isomorphism between the graph
1019// passed in and the graph that is actually used by the function. We need to
1020// figure out what this mapping is so that we can transformFunctionBody the
1021// instructions in the function itself. Note that every node in the graph that
1022// we are interested in must be both in the local graph of the called function,
1023// and in the local graph of the calling function. Because of this, we only
1024// define the mapping for these nodes [conveniently these are the only nodes we
1025// CAN define a mapping for...]
Chris Lattner692ad5d2002-03-29 17:13:46 +00001026//
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001027// The roots of the graph that we are transforming is rooted in the arguments
1028// passed into the function from the caller. This is where we start our
1029// mapping calculation.
1030//
1031// The NodeMapping calculated maps from the callers graph to the called graph.
1032//
Chris Lattner847b6e22002-03-30 20:53:14 +00001033static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001034 FunctionDSGraph &CallerGraph,
1035 FunctionDSGraph &CalledGraph,
1036 map<DSNode*, PointerValSet> &NodeMapping) {
1037 int LastArgNo = -2;
1038 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1039 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
1040 // corresponds to...
1041 //
1042 // Only consider first node of sequence. Extra nodes may may be added
1043 // to the TFI if the data structure requires more nodes than just the
1044 // one the argument points to. We are only interested in the one the
1045 // argument points to though.
1046 //
1047 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
1048 if (TFI.ArgInfo[i].ArgNo == -1) {
1049 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
1050 NodeMapping);
1051 } else {
1052 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner847b6e22002-03-30 20:53:14 +00001053 Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001054 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
1055 NodeMapping);
1056 }
1057 LastArgNo = TFI.ArgInfo[i].ArgNo;
1058 }
1059 }
1060}
1061
1062
1063// transformFunction - Transform the specified function the specified way. It
1064// we have already transformed that function that way, don't do anything. The
1065// nodes in the TransformFunctionInfo come out of callers data structure graph.
1066//
1067void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001068 FunctionDSGraph &CallerIPGraph,
1069 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001070 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1071
Chris Lattneracf19022002-04-14 06:14:41 +00001072#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001073 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001074 << TFI.Func->getName() << ":\n";
1075 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1076 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1077 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001078#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001079
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001080 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001081
Chris Lattner291a1b12002-03-29 19:05:48 +00001082 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001083
Chris Lattner291a1b12002-03-29 19:05:48 +00001084 // Build the type for the new function that we are transforming
1085 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001086 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001087 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1088 ArgTys.push_back(OldFuncType->getParamType(i));
1089
Chris Lattner441e16f2002-04-12 20:23:15 +00001090 const Type *RetType = OldFuncType->getReturnType();
1091
Chris Lattner291a1b12002-03-29 19:05:48 +00001092 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001093 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1094 if (TFI.ArgInfo[i].ArgNo == -1)
1095 RetType = POINTERTYPE; // Return a pointer
1096 else
1097 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1098 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1099 ->second.PoolType));
1100 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001101
1102 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001103 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1104 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001105
1106 // The new function is internal, because we know that only we can call it.
1107 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001108 // pointers (which look like the same value is always passed into a parameter,
1109 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001110 //
1111 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001112 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001113 CurModule->getFunctionList().push_back(NewFunc);
1114
Chris Lattner441e16f2002-04-12 20:23:15 +00001115
Chris Lattneracf19022002-04-14 06:14:41 +00001116#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001117 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001118#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001119
Chris Lattner291a1b12002-03-29 19:05:48 +00001120 // Add the newly formed function to the TransformedFunctions table so that
1121 // infinite recursion does not occur!
1122 //
1123 TransformedFunctions[TFI] = NewFunc;
1124
1125 // Add arguments to the function... starting with all of the old arguments
1126 vector<Value*> ArgMap;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001127 for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
Chris Lattner2e9fa6d2002-04-09 19:48:49 +00001128 const Argument *OFA = TFI.Func->getArgumentList()[i];
1129 Argument *NFA = new Argument(OFA->getType(), OFA->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001130 NewFunc->getArgumentList().push_back(NFA);
1131 ArgMap.push_back(NFA); // Keep track of the arguments
1132 }
1133
1134 // Now add all of the arguments corresponding to pools passed in...
1135 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001136 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001137 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001138 if (AI.ArgNo == -1)
1139 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001140 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001141 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1142 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1143 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001144 NewFunc->getArgumentList().push_back(NFA);
1145 }
1146
1147 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001148 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001149
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001150 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001151 // it has extra arguments for the pools coming in. Now we have to get the
1152 // data structure graph for the function we are replacing, and figure out how
1153 // our graph nodes map to the graph nodes in the dest function.
1154 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001155 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001156
Chris Lattner441e16f2002-04-12 20:23:15 +00001157 // NodeMapping - Multimap from callers graph to called graph. We are
1158 // guaranteed that the called function graph has more nodes than the caller,
1159 // or exactly the same number of nodes. This is because the called function
1160 // might not know that two nodes are merged when considering the callers
1161 // context, but the caller obviously does. Because of this, a single node in
1162 // the calling function's data structure graph can map to multiple nodes in
1163 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001164 //
1165 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001166
Chris Lattner847b6e22002-03-30 20:53:14 +00001167 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001168 NodeMapping);
1169
1170 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001171#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001172 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001173 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1174 I != NodeMapping.end(); ++I) {
1175 cerr << "Map: "; I->first->print(cerr);
1176 cerr << "To: "; I->second.print(cerr);
1177 cerr << "\n";
1178 }
Chris Lattneracf19022002-04-14 06:14:41 +00001179#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001180
1181 // Fill in the PoolDescriptor information for the transformed function so that
1182 // it can determine which value holds the pool descriptor for each data
1183 // structure node that it accesses.
1184 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001185 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001186
Chris Lattneracf19022002-04-14 06:14:41 +00001187#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001188 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001189#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001190
Chris Lattner441e16f2002-04-12 20:23:15 +00001191 // Calculate as much of the pool descriptor map as possible. Since we have
1192 // the node mapping between the caller and callee functions, and we have the
1193 // pool descriptor information of the caller, we can calculate a partical pool
1194 // descriptor map for the called function.
1195 //
1196 // The nodes that we do not have complete information for are the ones that
1197 // are accessed by loading pointers derived from arguments passed in, but that
1198 // are not passed in directly. In this case, we have all of the information
1199 // except a pool value. If the called function refers to this pool, the pool
1200 // value will be loaded from the pool graph and added to the map as neccesary.
1201 //
1202 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1203 I != NodeMapping.end(); ++I) {
1204 DSNode *CallerNode = I->first;
1205 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001206
Chris Lattner441e16f2002-04-12 20:23:15 +00001207 // Check to see if we have a node pointer passed in for this value...
1208 Value *CalleeValue = 0;
1209 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1210 if (TFI.ArgInfo[a].Node == CallerNode) {
1211 // Calculate the argument number that the pool is to the function
1212 // call... The call instruction should not have the pool operands added
1213 // yet.
1214 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001215#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001216 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001217#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001218 assert(ArgNo < NewFunc->getArgumentList().size() &&
1219 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001220
Chris Lattner441e16f2002-04-12 20:23:15 +00001221 // Map the pool argument into the called function...
1222 CalleeValue = NewFunc->getArgumentList()[ArgNo];
1223 break; // Found value, quit loop
1224 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001225
Chris Lattner441e16f2002-04-12 20:23:15 +00001226 // Loop over all of the data structure nodes that this incoming node maps to
1227 // Creating a PoolInfo structure for them.
1228 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1229 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1230 DSNode *CalleeNode = I->second[i].Node;
1231
1232 // Add the descriptor. We already know everything about it by now, much
1233 // of it is the same as the caller info.
1234 //
1235 PoolDescs.insert(make_pair(CalleeNode,
1236 PoolInfo(CalleeNode, CalleeValue,
1237 CallerPI.NewType,
1238 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001239 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001240 }
1241
1242 // We must destroy the node mapping so that we don't have latent references
1243 // into the data structure graph for the new function. Otherwise we get
1244 // assertion failures when transformFunctionBody tries to invalidate the
1245 // graph.
1246 //
1247 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001248
1249 // Now that we know everything we need about the function, transform the body
1250 // now!
1251 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001252 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1253
Chris Lattneracf19022002-04-14 06:14:41 +00001254#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001255 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001256#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001257}
1258
Chris Lattner8f796d62002-04-13 19:25:57 +00001259static unsigned countPointerTypes(const Type *Ty) {
1260 if (isa<PointerType>(Ty)) {
1261 return 1;
1262 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1263 unsigned Num = 0;
1264 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1265 Num += countPointerTypes(STy->getElementTypes()[i]);
1266 return Num;
1267 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1268 return countPointerTypes(ATy->getElementType());
1269 } else {
1270 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1271 return 0;
1272 }
1273}
Chris Lattner66df97d2002-03-29 06:21:38 +00001274
1275// CreatePools - Insert instructions into the function we are processing to
1276// create all of the memory pool objects themselves. This also inserts
1277// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001278// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001279//
1280void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001281 map<DSNode*, PoolInfo> &PoolDescs) {
1282 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001283 vector<BasicBlock*> ReturnNodes;
1284 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1285 if (isa<ReturnInst>((*I)->getTerminator()))
1286 ReturnNodes.push_back(*I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001287
Chris Lattner441e16f2002-04-12 20:23:15 +00001288 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1289
1290 // First pass over the allocations to process...
1291 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1292 // Create the pooldescriptor mapping... with null entries for everything
1293 // except the node & NewType fields.
1294 //
1295 map<DSNode*, PoolInfo>::iterator PI =
1296 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1297
Chris Lattner8f796d62002-04-13 19:25:57 +00001298 // Add a symbol table entry for the new type if there was one for the old
1299 // type...
1300 string OldName = CurModule->getTypeName(Allocs[i]->getType());
1301 if (!OldName.empty())
1302 CurModule->addTypeName(OldName+".p", PI->second.NewType);
1303
Chris Lattner441e16f2002-04-12 20:23:15 +00001304 // Create the abstract pool types that will need to be resolved in a second
1305 // pass once an abstract type is created for each pool.
1306 //
1307 // Can only handle limited shapes for now...
1308 StructType *OldNodeTy = cast<StructType>(Allocs[i]->getType());
1309 vector<const Type*> PoolTypes;
1310
1311 // Pool type is the first element of the pool descriptor type...
1312 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001313
1314 unsigned NumPointers = countPointerTypes(OldNodeTy);
1315 while (NumPointers--) // Add a different opaque type for each pointer
1316 PoolTypes.push_back(OpaqueType::get());
1317
Chris Lattner441e16f2002-04-12 20:23:15 +00001318 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1319 "Node should have same number of pointers as pool!");
1320
Chris Lattner8f796d62002-04-13 19:25:57 +00001321 StructType *PoolType = StructType::get(PoolTypes);
1322
1323 // Add a symbol table entry for the pooltype if possible...
1324 if (!OldName.empty()) CurModule->addTypeName(OldName+".pool", PoolType);
1325
Chris Lattner441e16f2002-04-12 20:23:15 +00001326 // Create the pool type, with opaque values for pointers...
Chris Lattner8f796d62002-04-13 19:25:57 +00001327 AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001328#ifdef DEBUG_CREATE_POOLS
1329 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1330#endif
1331 }
1332
1333 // Now that we have types for all of the pool types, link them all together.
1334 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1335 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1336
1337 // Resolve all of the outgoing pointer types of this pool node...
1338 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1339 PointerValSet &PVS = Allocs[i]->getLink(p);
1340 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1341 " probably just leave the type opaque or something dumb.");
1342 unsigned Out;
1343 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1344 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1345
1346 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1347
1348 // The actual struct type could change each time through the loop, so it's
1349 // NOT loop invariant.
1350 StructType *PoolTy = cast<StructType>(PoolTyH.get());
1351
1352 // Get the opaque type...
1353 DerivedType *ElTy =
1354 cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1355
1356#ifdef DEBUG_CREATE_POOLS
1357 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1358 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1359#endif
1360
1361 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1362 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1363
1364#ifdef DEBUG_CREATE_POOLS
1365 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1366#endif
1367 }
1368 }
1369
1370 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001371 vector<Instruction*> EntryNodeInsts;
1372 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001373 PoolInfo &PI = PoolDescs[Allocs[i]];
1374
1375 // Fill in the pool type for this pool...
1376 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1377 assert(!PI.PoolType->isAbstract() &&
1378 "Pool type should not be abstract anymore!");
1379
Chris Lattnere0618ca2002-03-29 05:50:20 +00001380 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001381 AllocaInst *PoolAlloc
1382 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1383 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001384 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001385 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001386 AllocationInst *AI = Allocs[i]->getAllocation();
1387
1388 // Initialize the pool. We need to know how big each allocation is. For
1389 // our purposes here, we assume we are allocating a scalar, or array of
1390 // constant size.
1391 //
Chris Lattneracf19022002-04-14 06:14:41 +00001392 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001393
1394 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001395 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001396 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001397 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1398
Chris Lattner441e16f2002-04-12 20:23:15 +00001399 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001400 Args.clear();
1401 Args.push_back(PoolAlloc); // Pool to initialize
1402
Chris Lattnere0618ca2002-03-29 05:50:20 +00001403 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1404 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1405
1406 // Insert it before the return instruction...
1407 BasicBlock *RetNode = ReturnNodes[EN];
1408 RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1409 }
1410 }
1411
Chris Lattner5da145b2002-04-13 19:52:54 +00001412 // Now that all of the pool descriptors have been created, link them together
1413 // so that called functions can get links as neccesary...
1414 //
1415 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1416 PoolInfo &PI = PoolDescs[Allocs[i]];
1417
1418 // For every pointer in the data structure, initialize a link that
1419 // indicates which pool to access...
1420 //
1421 vector<Value*> Indices(2);
1422 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1423 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1424 // Only store an entry for the field if the field is used!
1425 if (!PI.Node->getLink(l).empty()) {
1426 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1427 PointerVal PV = PI.Node->getLink(l)[0];
1428 assert(PV.Index == 0 && "Subindexing not supported yet!");
1429 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1430 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1431
1432 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1433 Indices));
1434 }
1435 }
1436
Chris Lattnere0618ca2002-03-29 05:50:20 +00001437 // Insert the entry node code into the entry block...
1438 F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1439 EntryNodeInsts.begin(),
1440 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001441}
1442
1443
Chris Lattner441e16f2002-04-12 20:23:15 +00001444// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001445// module and update the Pool* instance variables to point to them.
1446//
1447void PoolAllocate::addPoolPrototypes(Module *M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001448 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001449 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001450 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001451 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001452 PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001453
Chris Lattnere0618ca2002-03-29 05:50:20 +00001454 // Get pooldestroy function...
1455 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001456 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001457 PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1458
Chris Lattnere0618ca2002-03-29 05:50:20 +00001459 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001460 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001461 PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1462
1463 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001464 Args.push_back(POINTERTYPE); // Pointer to free
1465 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001466 PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1467
1468 // Add the %PoolTy type to the symbol table of the module...
Chris Lattner441e16f2002-04-12 20:23:15 +00001469 //M->addTypeName("PoolTy", PoolTy->getElementType());
Chris Lattner175f37c2002-03-29 03:40:59 +00001470}
1471
1472
1473bool PoolAllocate::run(Module *M) {
1474 addPoolPrototypes(M);
1475 CurModule = M;
1476
1477 DS = &getAnalysis<DataStructure>();
1478 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001479
1480 // We cannot use an iterator here because it will get invalidated when we add
1481 // functions to the module later...
1482 for (unsigned i = 0; i != M->size(); ++i)
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001483 if (!M->getFunctionList()[i]->isExternal()) {
Chris Lattner291a1b12002-03-29 19:05:48 +00001484 Changed |= processFunction(M->getFunctionList()[i]);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001485 if (Changed) {
1486 cerr << "Only processing one function\n";
1487 break;
1488 }
1489 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001490
1491 CurModule = 0;
1492 DS = 0;
1493 return false;
1494}
1495
1496
1497// createPoolAllocatePass - Global function to access the functionality of this
1498// pass...
1499//
Chris Lattner64fd9352002-03-28 18:08:31 +00001500Pass *createPoolAllocatePass() { return new PoolAllocate(); }