blob: bbd9d1b9f0466d6606ef8e37cfee155e9badf604 [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 Lattner7608a462002-05-07 18:36:35 +000013#include "llvm/Transforms/Utils/CloneFunction.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000014#include "llvm/Analysis/DataStructureGraph.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000015#include "llvm/Module.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 Lattnerca142372002-04-28 19:55:58 +000021#include "llvm/Constants.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000022#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000023#include "llvm/Support/InstVisitor.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000024#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000025#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000026#include <algorithm>
Anand Shukla2bc64192002-06-25 21:07:58 +000027using std::vector;
28using std::cerr;
29using std::map;
30using std::string;
31using std::set;
Chris Lattner64fd9352002-03-28 18:08:31 +000032
Chris Lattner441e16f2002-04-12 20:23:15 +000033// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
34// creation phase in the top level function of a transformed data structure.
35//
Chris Lattneracf19022002-04-14 06:14:41 +000036//#define DEBUG_CREATE_POOLS 1
37
38// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
39// the transformation is doing.
40//
41//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000042
Chris Lattner457e1ac2002-04-15 22:42:23 +000043// DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
44// many static loads were eliminated from a function...
45//
46#define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
47
Chris Lattner50e3d322002-04-13 23:13:18 +000048#include "Support/CommandLine.h"
49enum PtrSize {
50 Ptr8bits, Ptr16bits, Ptr32bits
51};
52
53static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
Chris Lattneracf19022002-04-14 06:14:41 +000054 "Set pointer size for -poolalloc pass",
Chris Lattner50e3d322002-04-13 23:13:18 +000055 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
56 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
57 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"), 0);
58
Chris Lattner457e1ac2002-04-15 22:42:23 +000059static cl::Flag DisableRLE("no-pool-load-elim", "Disable pool load elimination after poolalloc pass", cl::Hidden);
60
Chris Lattner441e16f2002-04-12 20:23:15 +000061const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000062
Chris Lattnere0618ca2002-03-29 05:50:20 +000063// FIXME: This is dependant on the sparc backend layout conventions!!
64static TargetData TargetData("test");
65
Chris Lattner50e3d322002-04-13 23:13:18 +000066static const Type *getPointerTransformedType(const Type *Ty) {
Chris Lattner7076ff22002-06-25 16:13:21 +000067 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000068 return POINTERTYPE;
Chris Lattner7076ff22002-06-25 16:13:21 +000069 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000070 vector<const Type *> NewElTypes;
71 NewElTypes.reserve(STy->getElementTypes().size());
72 for (StructType::ElementTypes::const_iterator
73 I = STy->getElementTypes().begin(),
74 E = STy->getElementTypes().end(); I != E; ++I)
75 NewElTypes.push_back(getPointerTransformedType(*I));
76 return StructType::get(NewElTypes);
Chris Lattner7076ff22002-06-25 16:13:21 +000077 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000078 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
79 ATy->getNumElements());
80 } else {
81 assert(Ty->isPrimitiveType() && "Unknown derived type!");
82 return Ty;
83 }
84}
85
Chris Lattner64fd9352002-03-28 18:08:31 +000086namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000087 struct PoolInfo {
88 DSNode *Node; // The node this pool allocation represents
89 Value *Handle; // LLVM value of the pool in the current context
90 const Type *NewType; // The transformed type of the memory objects
91 const Type *PoolType; // The type of the pool
92
93 const Type *getOldType() const { return Node->getType(); }
94
95 PoolInfo() { // Define a default ctor for map::operator[]
96 cerr << "Map subscript used to get element that doesn't exist!\n";
97 abort(); // Invalid
98 }
99
100 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
101 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
102 // Handle can be null...
103 assert(N && NT && PT && "Pool info null!");
104 }
105
106 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
107 assert(N && "Invalid pool info!");
108
109 // The new type of the memory object is the same as the old type, except
110 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000111 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000112 }
113 };
114
Chris Lattner692ad5d2002-03-29 17:13:46 +0000115 // ScalarInfo - Information about an LLVM value that we know points to some
116 // datastructure we are processing.
117 //
118 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000119 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000120 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000121
Chris Lattner441e16f2002-04-12 20:23:15 +0000122 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
123 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000124 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000125 };
126
Chris Lattner396d5d72002-03-30 04:02:31 +0000127 // CallArgInfo - Information on one operand for a call that got expanded.
128 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000129 int ArgNo; // Call argument number this corresponds to
130 DSNode *Node; // The graph node for the pool
131 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000132
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000133 CallArgInfo(int Arg, DSNode *N, Value *PH)
134 : ArgNo(Arg), Node(N), PoolHandle(PH) {
135 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000136 }
137
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000138 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000139 bool operator<(const CallArgInfo &CAI) const {
140 return ArgNo < CAI.ArgNo;
141 }
142 };
143
Chris Lattner692ad5d2002-03-29 17:13:46 +0000144 // TransformFunctionInfo - Information about how a function eeds to be
145 // transformed.
146 //
147 struct TransformFunctionInfo {
148 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000149 // processed. Each CallArgInfo corresponds to an argument that needs to
150 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000151 //
152 // As a special case, "argument" number -1 corresponds to the return value.
153 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000154 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000155
156 // Func - The function to be transformed...
157 Function *Func;
158
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000159 // The call instruction that is used to map CallArgInfo PoolHandle values
160 // into the new function values.
161 CallInst *Call;
162
Chris Lattner692ad5d2002-03-29 17:13:46 +0000163 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000164 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000165
Chris Lattner396d5d72002-03-30 04:02:31 +0000166 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000167 if (Func < TFI.Func) return true;
168 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000169 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
170 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000171 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000172 }
173
174 void finalizeConstruction() {
175 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000176 // argument records, in order. Note that this must be a stable sort so
177 // that the entries with the same sorting criteria (ie they are multiple
178 // pool entries for the same argument) are kept in depth first order.
Anand Shukla2bc64192002-06-25 21:07:58 +0000179 std::stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000180 }
Chris Lattner3e78dea2002-04-18 14:43:30 +0000181
182 // addCallInfo - For a specified function call CI, figure out which pool
183 // descriptors need to be passed in as arguments, and which arguments need
184 // to be transformed into indices. If Arg != -1, the specified call
185 // argument is passed in as a pointer to a data structure.
186 //
187 void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
188 DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
189
190 // Make sure that all dependant arguments are added to this transformation
191 // info. For example, if we call foo(null, P) and foo treats it's first and
192 // second arguments as belonging to the same data structure, the we MUST add
193 // entries to know that the null needs to be transformed into an index as
194 // well.
195 //
196 void ensureDependantArgumentsIncluded(DataStructure *DS,
197 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000198 };
199
200
201 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000202 struct PoolAllocate : public Pass {
Chris Lattner37104aa2002-04-29 14:57:45 +0000203 const char *getPassName() const { return "Pool Allocate"; }
204
Chris Lattner175f37c2002-03-29 03:40:59 +0000205 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000206 switch (ReqPointerSize) {
207 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
208 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
209 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
210 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000211
212 CurModule = 0; DS = 0;
213 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000214 }
215
Chris Lattner441e16f2002-04-12 20:23:15 +0000216 // getPoolType - Get the type used by the backend for a pool of a particular
217 // type. This pool record is used to allocate nodes of type NodeType.
218 //
219 // Here, PoolTy = { NodeType*, sbyte*, uint }*
220 //
221 const StructType *getPoolType(const Type *NodeType) {
222 vector<const Type*> PoolElements;
223 PoolElements.push_back(PointerType::get(NodeType));
224 PoolElements.push_back(PointerType::get(Type::SByteTy));
225 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000226 StructType *Result = StructType::get(PoolElements);
227
228 // Add a name to the symbol table to correspond to the backend
229 // representation of this pool...
230 assert(CurModule && "No current module!?");
231 string Name = CurModule->getTypeName(NodeType);
232 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
233 CurModule->addTypeName(Name+"oolbe", Result);
234
235 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000236 }
237
Chris Lattner7076ff22002-06-25 16:13:21 +0000238 bool run(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000239
Chris Lattnerc8e66542002-04-27 06:56:12 +0000240 // getAnalysisUsage - This function requires data structure information
Chris Lattner175f37c2002-03-29 03:40:59 +0000241 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000242 //
Chris Lattnerc8e66542002-04-27 06:56:12 +0000243 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
244 AU.addRequired(DataStructure::ID);
Chris Lattner64fd9352002-03-28 18:08:31 +0000245 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000246
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000247 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000248 // CurModule - The module being processed.
249 Module *CurModule;
250
251 // DS - The data structure graph for the module being processed.
252 DataStructure *DS;
253
254 // Prototypes that we add to support pool allocation...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000255 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolAllocArray, *PoolFree;
Chris Lattner175f37c2002-03-29 03:40:59 +0000256
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000257 // The map of already transformed functions... note that the keys of this
258 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
259 // of the ArgInfo elements.
260 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000261 map<TransformFunctionInfo, Function*> TransformedFunctions;
262
263 // getTransformedFunction - Get a transformed function, or return null if
264 // the function specified hasn't been transformed yet.
265 //
266 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
267 map<TransformFunctionInfo, Function*>::const_iterator I =
268 TransformedFunctions.find(TFI);
269 if (I != TransformedFunctions.end()) return I->second;
270 return 0;
271 }
272
273
Chris Lattner441e16f2002-04-12 20:23:15 +0000274 // addPoolPrototypes - Add prototypes for the pool functions to the
275 // specified module and update the Pool* instance variables to point to
276 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000277 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000278 void addPoolPrototypes(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000279
Chris Lattner66df97d2002-03-29 06:21:38 +0000280
281 // CreatePools - Insert instructions into the function we are processing to
282 // create all of the memory pool objects themselves. This also inserts
283 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000284 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000285 //
286 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000287 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000288
Chris Lattner175f37c2002-03-29 03:40:59 +0000289 // processFunction - Convert a function to use pool allocation where
290 // available.
291 //
292 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000293
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000294 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000295 // pools specified in PoolDescs when modifying data structure nodes
296 // specified in the PoolDescs map. IPFGraph is the closed data structure
297 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000298 //
299 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000300 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000301
302 // transformFunction - Transform the specified function the specified way.
303 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000304 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000305 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000306 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000307 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000308 FunctionDSGraph &CallerIPGraph,
309 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000310
Chris Lattner64fd9352002-03-28 18:08:31 +0000311 };
312}
313
Chris Lattner692ad5d2002-03-29 17:13:46 +0000314// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000315// allocation node in a data structure graph is eligable for pool allocation.
316//
317static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000318 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattnere0618ca2002-03-29 05:50:20 +0000319 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000320}
321
Chris Lattner175f37c2002-03-29 03:40:59 +0000322// processFunction - Convert a function to use pool allocation where
323// available.
324//
325bool PoolAllocate::processFunction(Function *F) {
326 // Get the closed datastructure graph for the current function... if there are
327 // any allocations in this graph that are not escaping, we need to pool
328 // allocate them here!
329 //
330 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
331
332 // Get all of the allocations that do not escape the current function. Since
333 // they are still live (they exist in the graph at all), this means we must
334 // have scalar references to these nodes, but the scalars are never returned.
335 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000336 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000337 IPGraph.getNonEscapingAllocations(Allocs);
338
339 // Filter out allocations that we cannot handle. Currently, this includes
340 // variable sized array allocations and alloca's (which we do not want to
341 // pool allocate)
342 //
Anand Shukla2bc64192002-06-25 21:07:58 +0000343 Allocs.erase(std::remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
Chris Lattner175f37c2002-03-29 03:40:59 +0000344 Allocs.end());
345
346
347 if (Allocs.empty()) return false; // Nothing to do.
348
Chris Lattner3e78dea2002-04-18 14:43:30 +0000349#ifdef DEBUG_TRANSFORM_PROGRESS
350 cerr << "Transforming Function: " << F->getName() << "\n";
351#endif
352
Chris Lattner692ad5d2002-03-29 17:13:46 +0000353 // Insert instructions into the function we are processing to create all of
354 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000355 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000356 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000357 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000358 map<DSNode*, PoolInfo> PoolDescs;
359 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000360
Chris Lattneracf19022002-04-14 06:14:41 +0000361#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000362 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000363#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000364
365 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000366 // how. To do this, we look at all of the scalars, seeing which functions are
367 // either used as a scalar value (so they return a data structure), or are
368 // passed one of our scalar values.
369 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000370 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000371
372 return true;
373}
374
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000375
Chris Lattner441e16f2002-04-12 20:23:15 +0000376//===----------------------------------------------------------------------===//
377//
378// NewInstructionCreator - This class is used to traverse the function being
379// modified, changing each instruction visit'ed to use and provide pointer
380// indexes instead of real pointers. This is what changes the body of a
381// function to use pool allocation.
382//
383class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000384 PoolAllocate &PoolAllocator;
385 vector<ScalarInfo> &Scalars;
386 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000387 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000388
Chris Lattner441e16f2002-04-12 20:23:15 +0000389 struct RefToUpdate {
390 Instruction *I; // Instruction to update
391 unsigned OpNum; // Operand number to update
392 Value *OldVal; // The old value it had
393
394 RefToUpdate(Instruction *i, unsigned o, Value *ov)
395 : I(i), OpNum(o), OldVal(ov) {}
396 };
397 vector<RefToUpdate> ReferencesToUpdate;
398
399 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000400 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
401 if (Scalars[i].Val == V) return Scalars[i];
Chris Lattner3e78dea2002-04-18 14:43:30 +0000402
403 cerr << "Could not find scalar " << V << " in scalar map!\n";
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000404 assert(0 && "Scalar not found in getScalar!");
405 abort();
406 return Scalars[0];
407 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000408
409 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000410 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000411 if (Scalars[i].Val == V) return &Scalars[i];
412 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000413 }
414
Chris Lattner7076ff22002-06-25 16:13:21 +0000415 BasicBlock::iterator ReplaceInstWith(Instruction &I, Instruction *New) {
416 BasicBlock *BB = I.getParent();
417 BasicBlock::iterator RI = &I;
418 BB->getInstList().remove(RI);
419 BB->getInstList().insert(RI, New);
420 XFormMap[&I] = New;
421 return New;
Chris Lattner441e16f2002-04-12 20:23:15 +0000422 }
423
Chris Lattner39db8712002-05-02 17:38:14 +0000424 Instruction *createPoolBaseInstruction(Value *PtrVal) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000425 const ScalarInfo &SC = getScalarRef(PtrVal);
426 vector<Value*> Args(3);
427 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
428 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
429 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
Chris Lattner39db8712002-05-02 17:38:14 +0000430 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
Chris Lattner441e16f2002-04-12 20:23:15 +0000431 }
432
433
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000434public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000435 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
436 map<CallInst*, TransformFunctionInfo> &C,
437 map<Value*, Value*> &X)
438 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000439
Chris Lattner441e16f2002-04-12 20:23:15 +0000440
441 // updateReferences - The NewInstructionCreator is responsible for creating
442 // new instructions to replace the old ones in the function, and then link up
443 // references to values to their new values. For it to do this, however, it
444 // keeps track of information about the value mapping of old values to new
445 // values that need to be patched up. Given this value map and a set of
446 // instruction operands to patch, updateReferences performs the updates.
447 //
448 void updateReferences() {
449 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
450 RefToUpdate &Ref = ReferencesToUpdate[i];
451 Value *NewVal = XFormMap[Ref.OldVal];
452
453 if (NewVal == 0) {
454 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
455 cast<Constant>(Ref.OldVal)->isNullValue()) {
456 // Transform the null pointer into a null index... caching in XFormMap
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000457 XFormMap[Ref.OldVal] = NewVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000458 //} else if (isa<Argument>(Ref.OldVal)) {
459 } else {
460 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
461 assert(XFormMap[Ref.OldVal] &&
462 "Reference to value that was not updated found!");
463 }
464 }
465
466 Ref.I->setOperand(Ref.OpNum, NewVal);
467 }
468 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000469 }
470
Chris Lattner441e16f2002-04-12 20:23:15 +0000471 //===--------------------------------------------------------------------===//
472 // Transformation methods:
473 // These methods specify how each type of instruction is transformed by the
474 // NewInstructionCreator instance...
475 //===--------------------------------------------------------------------===//
476
Chris Lattner7076ff22002-06-25 16:13:21 +0000477 void visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000478 assert(0 && "Cannot transform get element ptr instructions yet!");
479 }
480
481 // Replace the load instruction with a new one.
Chris Lattner7076ff22002-06-25 16:13:21 +0000482 void visitLoadInst(LoadInst &I) {
Chris Lattner39db8712002-05-02 17:38:14 +0000483 vector<Instruction *> BeforeInsts;
Chris Lattner441e16f2002-04-12 20:23:15 +0000484
485 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000486 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000487 Type::UIntTy, I.getOperand(0)->getName());
Chris Lattner39db8712002-05-02 17:38:14 +0000488 BeforeInsts.push_back(Index);
Chris Lattner7076ff22002-06-25 16:13:21 +0000489 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(0)));
Chris Lattner39db8712002-05-02 17:38:14 +0000490
491 // Include the pool base instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000492 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(0));
Chris Lattner39db8712002-05-02 17:38:14 +0000493 BeforeInsts.push_back(PoolBase);
494
495 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000496 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index,
497 I.getName()+".idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000498 BeforeInsts.push_back(IdxInst);
Chris Lattner441e16f2002-04-12 20:23:15 +0000499
Chris Lattner7076ff22002-06-25 16:13:21 +0000500 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000501 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000502 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000503 I.getName()+".addr");
Chris Lattner39db8712002-05-02 17:38:14 +0000504 BeforeInsts.push_back(Address);
505
Chris Lattner7076ff22002-06-25 16:13:21 +0000506 Instruction *NewLoad = new LoadInst(Address, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000507
508 // Replace the load instruction with the new load instruction...
509 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
510
Chris Lattner39db8712002-05-02 17:38:14 +0000511 // Add all of the instructions before the load...
512 NewLoad->getParent()->getInstList().insert(II, BeforeInsts.begin(),
513 BeforeInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000514
515 // If not yielding a pool allocated pointer, use the new load value as the
516 // value in the program instead of the old load value...
517 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000518 if (!getScalar(&I))
519 I.replaceAllUsesWith(NewLoad);
Chris Lattner441e16f2002-04-12 20:23:15 +0000520 }
521
522 // Replace the store instruction with a new one. In the store instruction,
523 // the value stored could be a pointer type, meaning that the new store may
524 // have to change one or both of it's operands.
525 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000526 void visitStoreInst(StoreInst &I) {
527 assert(getScalar(I.getOperand(1)) &&
Chris Lattner441e16f2002-04-12 20:23:15 +0000528 "Store inst found only storing pool allocated pointer. "
529 "Not imp yet!");
530
Chris Lattner7076ff22002-06-25 16:13:21 +0000531 Value *Val = I.getOperand(0); // The value to store...
Chris Lattner39db8712002-05-02 17:38:14 +0000532
Chris Lattner441e16f2002-04-12 20:23:15 +0000533 // Check to see if the value we are storing is a data structure pointer...
Chris Lattner7076ff22002-06-25 16:13:21 +0000534 //if (const ScalarInfo *ValScalar = getScalar(I.getOperand(0)))
535 if (isa<PointerType>(I.getOperand(0)->getType()))
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000536 Val = Constant::getNullValue(POINTERTYPE); // Yes, store a dummy
Chris Lattner441e16f2002-04-12 20:23:15 +0000537
Chris Lattner7076ff22002-06-25 16:13:21 +0000538 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(1));
Chris Lattner441e16f2002-04-12 20:23:15 +0000539
540 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000541 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000542 Type::UIntTy, I.getOperand(1)->getName());
543 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000544
Chris Lattner39db8712002-05-02 17:38:14 +0000545 // Instructions to add after the Index...
546 vector<Instruction*> AfterInsts;
547
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000548 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000549 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index, "idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000550 AfterInsts.push_back(IdxInst);
551
Chris Lattner7076ff22002-06-25 16:13:21 +0000552 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000553 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000554 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000555 I.getName()+"storeaddr");
Chris Lattner39db8712002-05-02 17:38:14 +0000556 AfterInsts.push_back(Address);
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000557
Chris Lattner39db8712002-05-02 17:38:14 +0000558 Instruction *NewStore = new StoreInst(Val, Address);
559 AfterInsts.push_back(NewStore);
Chris Lattner7076ff22002-06-25 16:13:21 +0000560 if (Val != I.getOperand(0)) // Value stored was a pointer?
561 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I.getOperand(0)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000562
563
564 // Replace the store instruction with the cast instruction...
565 BasicBlock::iterator II = ReplaceInstWith(I, Index);
566
567 // Add the pool base calculator instruction before the index...
Chris Lattner7076ff22002-06-25 16:13:21 +0000568 II = ++Index->getParent()->getInstList().insert(II, PoolBase);
569 ++II;
Chris Lattner441e16f2002-04-12 20:23:15 +0000570
Chris Lattner39db8712002-05-02 17:38:14 +0000571 // Add the instructions that go after the index...
572 Index->getParent()->getInstList().insert(II, AfterInsts.begin(),
573 AfterInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000574 }
575
576
577 // Create call to poolalloc for every malloc instruction
Chris Lattner7076ff22002-06-25 16:13:21 +0000578 void visitMallocInst(MallocInst &I) {
579 const ScalarInfo &SCI = getScalarRef(&I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000580 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000581
582 CallInst *Call;
Chris Lattner7076ff22002-06-25 16:13:21 +0000583 if (!I.isArrayAllocation()) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000584 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000585 Call = new CallInst(PoolAllocator.PoolAlloc, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000586 } else {
Chris Lattner7076ff22002-06-25 16:13:21 +0000587 Args.push_back(I.getArraySize());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000588 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000589 Call = new CallInst(PoolAllocator.PoolAllocArray, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000590 }
591
Chris Lattner441e16f2002-04-12 20:23:15 +0000592 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000593 }
594
Chris Lattner441e16f2002-04-12 20:23:15 +0000595 // Convert a call to poolfree for every free instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000596 void visitFreeInst(FreeInst &I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000597 // Create a new call to poolfree before the free instruction
598 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000599 Args.push_back(Constant::getNullValue(POINTERTYPE));
Chris Lattner7076ff22002-06-25 16:13:21 +0000600 Args.push_back(getScalarRef(I.getOperand(0)).Pool.Handle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000601 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
602 ReplaceInstWith(I, NewCall);
Chris Lattner7076ff22002-06-25 16:13:21 +0000603 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I.getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000604 }
605
606 // visitCallInst - Create a new call instruction with the extra arguments for
607 // all of the memory pools that the call needs.
608 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000609 void visitCallInst(CallInst &I) {
610 TransformFunctionInfo &TI = CallMap[&I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000611
612 // Start with all of the old arguments...
Chris Lattner7076ff22002-06-25 16:13:21 +0000613 vector<Value*> Args(I.op_begin()+1, I.op_end());
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000614
Chris Lattner441e16f2002-04-12 20:23:15 +0000615 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
616 // Replace all of the pointer arguments with our new pointer typed values.
617 if (TI.ArgInfo[i].ArgNo != -1)
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000618 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000619
620 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000621 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000622 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000623
624 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner7076ff22002-06-25 16:13:21 +0000625 Instruction *NewCall = new CallInst(NF, Args, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000626 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000627
Chris Lattner441e16f2002-04-12 20:23:15 +0000628 // Keep track of the mapping of operands so that we can resolve them to real
629 // values later.
630 Value *RetVal = NewCall;
631 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
632 if (TI.ArgInfo[i].ArgNo != -1)
633 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
Chris Lattner7076ff22002-06-25 16:13:21 +0000634 I.getOperand(TI.ArgInfo[i].ArgNo+1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000635 else
636 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000637
Chris Lattner441e16f2002-04-12 20:23:15 +0000638 // If not returning a pointer, use the new call as the value in the program
639 // instead of the old call...
640 //
641 if (RetVal)
Chris Lattner7076ff22002-06-25 16:13:21 +0000642 I.replaceAllUsesWith(RetVal);
Chris Lattner441e16f2002-04-12 20:23:15 +0000643 }
644
645 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
646 // nodes...
647 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000648 void visitPHINode(PHINode &PN) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000649 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000650 PHINode *NewPhi = new PHINode(POINTERTYPE, PN.getName());
651 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
652 NewPhi->addIncoming(DummyVal, PN.getIncomingBlock(i));
Chris Lattner441e16f2002-04-12 20:23:15 +0000653 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
Chris Lattner7076ff22002-06-25 16:13:21 +0000654 PN.getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000655 }
656
Chris Lattner441e16f2002-04-12 20:23:15 +0000657 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000658 }
659
Chris Lattner441e16f2002-04-12 20:23:15 +0000660 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner7076ff22002-06-25 16:13:21 +0000661 void visitReturnInst(ReturnInst &I) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000662 Instruction *Ret = new ReturnInst(Constant::getNullValue(POINTERTYPE));
Chris Lattner441e16f2002-04-12 20:23:15 +0000663 ReplaceInstWith(I, Ret);
Chris Lattner7076ff22002-06-25 16:13:21 +0000664 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I.getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000665 }
666
Chris Lattner441e16f2002-04-12 20:23:15 +0000667 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattner7076ff22002-06-25 16:13:21 +0000668 void visitSetCondInst(SetCondInst &SCI) {
669 BinaryOperator &I = (BinaryOperator&)SCI;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000670 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000671 BinaryOperator *New = BinaryOperator::create(I.getOpcode(), DummyVal,
672 DummyVal, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000673 ReplaceInstWith(I, New);
674
Chris Lattner7076ff22002-06-25 16:13:21 +0000675 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I.getOperand(0)));
676 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000677
678 // Make sure branches refer to the new condition...
Chris Lattner7076ff22002-06-25 16:13:21 +0000679 I.replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000680 }
681
Chris Lattner7076ff22002-06-25 16:13:21 +0000682 void visitInstruction(Instruction &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000683 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000684 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000685};
686
687
Chris Lattner457e1ac2002-04-15 22:42:23 +0000688// PoolBaseLoadEliminator - Every load and store through a pool allocated
689// pointer causes a load of the real pool base out of the pool descriptor.
690// Iterate through the function, doing a local elimination pass of duplicate
691// loads. This attempts to turn the all too common:
692//
693// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
694// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
695// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
696// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
697//
698// into:
699// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
700// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
701// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
702//
703//
704class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
705 // PoolDescValues - Keep track of the values in the current function that are
706 // pool descriptors (loads from which we want to eliminate).
707 //
708 vector<Value*> PoolDescValues;
709
710 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
711 // when referencing a pool descriptor.
712 //
713 map<Value*, LoadInst*> PoolDescMap;
714
715 // These two fields keep track of statistics of how effective we are, if
716 // debugging is enabled.
717 //
718 unsigned Eliminated, Remaining;
719public:
720 // Compact the pool descriptor map into a list of the pool descriptors in the
721 // current context that we should know about...
722 //
723 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
724 Eliminated = Remaining = 0;
725 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
726 E = PoolDescs.end(); I != E; ++I)
727 PoolDescValues.push_back(I->second.Handle);
728
729 // Remove duplicates from the list of pool values
730 sort(PoolDescValues.begin(), PoolDescValues.end());
731 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
732 PoolDescValues.end());
733 }
734
735#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
Chris Lattner7076ff22002-06-25 16:13:21 +0000736 void visitFunction(Function &F) {
737 cerr << "Pool Load Elim '" << F.getName() << "'\t";
Chris Lattner457e1ac2002-04-15 22:42:23 +0000738 }
739 ~PoolBaseLoadEliminator() {
740 unsigned Total = Eliminated+Remaining;
741 if (Total)
742 cerr << "removed " << Eliminated << "["
743 << Eliminated*100/Total << "%] loads, leaving "
744 << Remaining << ".\n";
745 }
746#endif
747
748 // Loop over the function, looking for loads to eliminate. Because we are a
749 // local transformation, we reset all of our state when we enter a new basic
750 // block.
751 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000752 void visitBasicBlock(BasicBlock &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000753 PoolDescMap.clear(); // Forget state.
754 }
755
756 // Starting with an empty basic block, we scan it looking for loads of the
757 // pool descriptor. When we find a load, we add it to the PoolDescMap,
758 // indicating that we have a value available to recycle next time we see the
759 // poolbase of this instruction being loaded.
760 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000761 void visitLoadInst(LoadInst &LI) {
762 Value *LoadAddr = LI.getPointerOperand();
Chris Lattner457e1ac2002-04-15 22:42:23 +0000763 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
764 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
Chris Lattner7076ff22002-06-25 16:13:21 +0000765 LI.replaceAllUsesWith(VIt->second); // Make the current load dead
Chris Lattner457e1ac2002-04-15 22:42:23 +0000766 ++Eliminated;
767 } else {
768 // This load might not be a load of a pool pointer, check to see if it is
Chris Lattner7076ff22002-06-25 16:13:21 +0000769 if (LI.getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
Chris Lattner457e1ac2002-04-15 22:42:23 +0000770 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
771 PoolDescValues.end()) {
772
773 assert("Make sure it's a load of the pool base, not a chaining field" &&
Chris Lattner7076ff22002-06-25 16:13:21 +0000774 LI.getOperand(1) == Constant::getNullValue(Type::UIntTy) &&
775 LI.getOperand(2) == Constant::getNullValue(Type::UByteTy) &&
776 LI.getOperand(3) == Constant::getNullValue(Type::UByteTy));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000777
778 // If it is a load of a pool base, keep track of it for future reference
Anand Shukla2bc64192002-06-25 21:07:58 +0000779 PoolDescMap.insert(std::make_pair(LoadAddr, &LI));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000780 ++Remaining;
781 }
782 }
783 }
784
785 // If we run across a function call, forget all state... Calls to
786 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
787 // reloaded the next time it is used. Furthermore, a call to a random
788 // function might call one of these functions, so be conservative. Through
789 // more analysis, this could be improved in the future.
790 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000791 void visitCallInst(CallInst &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000792 PoolDescMap.clear();
793 }
794};
795
Chris Lattner3e78dea2002-04-18 14:43:30 +0000796static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
797 map<DSNode*, PointerValSet> &NodeMapping) {
798 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
799 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
800 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
801 DSNode *DestNode = PVS[i].Node;
802
803 // Loop over all of the outgoing links in the mapped graph
804 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
805 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
806 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
807
808 // Add all of the node mappings now!
809 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
810 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
811 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
812 }
813 }
814 }
815}
816
817// CalculateNodeMapping - There is a partial isomorphism between the graph
818// passed in and the graph that is actually used by the function. We need to
819// figure out what this mapping is so that we can transformFunctionBody the
820// instructions in the function itself. Note that every node in the graph that
821// we are interested in must be both in the local graph of the called function,
822// and in the local graph of the calling function. Because of this, we only
823// define the mapping for these nodes [conveniently these are the only nodes we
824// CAN define a mapping for...]
825//
826// The roots of the graph that we are transforming is rooted in the arguments
827// passed into the function from the caller. This is where we start our
828// mapping calculation.
829//
830// The NodeMapping calculated maps from the callers graph to the called graph.
831//
832static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
833 FunctionDSGraph &CallerGraph,
834 FunctionDSGraph &CalledGraph,
835 map<DSNode*, PointerValSet> &NodeMapping) {
836 int LastArgNo = -2;
837 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
838 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
839 // corresponds to...
840 //
841 // Only consider first node of sequence. Extra nodes may may be added
842 // to the TFI if the data structure requires more nodes than just the
843 // one the argument points to. We are only interested in the one the
844 // argument points to though.
845 //
846 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
847 if (TFI.ArgInfo[i].ArgNo == -1) {
848 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
849 NodeMapping);
850 } else {
851 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner7076ff22002-06-25 16:13:21 +0000852 Function::aiterator AI = F->abegin();
853 std::advance(AI, TFI.ArgInfo[i].ArgNo);
854 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[AI],
Chris Lattner3e78dea2002-04-18 14:43:30 +0000855 NodeMapping);
856 }
857 LastArgNo = TFI.ArgInfo[i].ArgNo;
858 }
859 }
860}
Chris Lattner441e16f2002-04-12 20:23:15 +0000861
862
Chris Lattner3e78dea2002-04-18 14:43:30 +0000863
864
865// addCallInfo - For a specified function call CI, figure out which pool
866// descriptors need to be passed in as arguments, and which arguments need to be
867// transformed into indices. If Arg != -1, the specified call argument is
868// passed in as a pointer to a data structure.
869//
870void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
871 int Arg, DSNode *GraphNode,
872 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000873 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000874 assert(Func == 0 || Func == CI->getCalledFunction() &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000875 "Function call record should always call the same function!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000876 assert(Call == 0 || Call == CI &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000877 "Call element already filled in with different value!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000878 Func = CI->getCalledFunction();
879 Call = CI;
880 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000881
882 // For now, add the entire graph that is pointed to by the call argument.
883 // This graph can and should be pruned to only what the function itself will
884 // use, because often this will be a dramatically smaller subset of what we
885 // are providing.
886 //
Chris Lattner3e78dea2002-04-18 14:43:30 +0000887 // FIXME: This should use pool links instead of extra arguments!
888 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000889 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000890 I != E; ++I)
Chris Lattner3e78dea2002-04-18 14:43:30 +0000891 ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
892}
893
894static void markReachableNodes(const PointerValSet &Vals,
895 set<DSNode*> &ReachableNodes) {
896 for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
897 DSNode *N = Vals[n].Node;
898 if (ReachableNodes.count(N) == 0) // Haven't already processed node?
899 ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
900 }
901}
902
903// Make sure that all dependant arguments are added to this transformation info.
904// For example, if we call foo(null, P) and foo treats it's first and second
905// arguments as belonging to the same data structure, the we MUST add entries to
906// know that the null needs to be transformed into an index as well.
907//
908void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
909 map<DSNode*, PoolInfo> &PoolDescs) {
910 // FIXME: This does not work for indirect function calls!!!
911 if (Func == 0) return; // FIXME!
912
913 // Make sure argument entries are sorted.
914 finalizeConstruction();
915
916 // Loop over the function signature, checking to see if there are any pointer
917 // arguments that we do not convert... if there is something we haven't
918 // converted, set done to false.
919 //
920 unsigned PtrNo = 0;
921 bool Done = true;
922 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
923 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
924 // We DO transform the ret val... skip all possible entries for retval
925 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
926 PtrNo++;
927 } else {
928 Done = false;
929 }
930
Chris Lattner7076ff22002-06-25 16:13:21 +0000931 unsigned i = 0;
932 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I,++i){
933 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +0000934 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
935 // We DO transform this arg... skip all possible entries for argument
936 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
937 PtrNo++;
938 } else {
939 Done = false;
940 break;
941 }
942 }
943 }
944
945 // If we already have entries for all pointer arguments and retvals, there
946 // certainly is no work to do. Bail out early to avoid building relatively
947 // expensive data structures.
948 //
949 if (Done) return;
950
951#ifdef DEBUG_TRANSFORM_PROGRESS
952 cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
953#endif
954
955 // Otherwise, we MIGHT have to add the arguments/retval if they are part of
956 // the same datastructure graph as some other argument or retval that we ARE
957 // processing.
958 //
959 // Get the data structure graph for the called function.
960 //
961 FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
962
963 // Build a mapping between the nodes in our current graph and the nodes in the
964 // called function's graph. We build it based on our _incomplete_
965 // transformation information, because it contains all of the info that we
966 // should need.
967 //
968 map<DSNode*, PointerValSet> NodeMapping;
969 CalculateNodeMapping(Func, *this,
970 DS->getClosedDSGraph(Call->getParent()->getParent()),
971 CalledDS, NodeMapping);
972
973 // Build the inverted version of the node mapping, that maps from a node in
974 // the called functions graph to a single node in the caller graph.
975 //
976 map<DSNode*, DSNode*> InverseNodeMap;
977 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
978 E = NodeMapping.end(); I != E; ++I) {
979 PointerValSet &CalledNodes = I->second;
980 for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
981 InverseNodeMap[CalledNodes[i].Node] = I->first;
982 }
983 NodeMapping.clear(); // Done with information, free memory
984
985 // Build a set of reachable nodes from the arguments/retval that we ARE
986 // passing in...
987 set<DSNode*> ReachableNodes;
988
989 // Loop through all of the arguments, marking all of the reachable data
990 // structure nodes reachable if they are from this pointer...
991 //
992 for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
993 if (ArgInfo[i].ArgNo == -1) {
994 if (i == 0) // Only process retvals once (performance opt)
995 markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
996 } else { // If it's an argument value...
Chris Lattner7076ff22002-06-25 16:13:21 +0000997 Function::aiterator AI = Func->abegin();
998 std::advance(AI, ArgInfo[i].ArgNo);
999 if (isa<PointerType>(AI->getType()))
1000 markReachableNodes(CalledDS.getValueMap()[AI], ReachableNodes);
Chris Lattner3e78dea2002-04-18 14:43:30 +00001001 }
1002 }
1003
1004 // Now that we know which nodes are already reachable, see if any of the
1005 // arguments that we are not passing values in for can reach one of the
1006 // existing nodes...
1007 //
1008
1009 // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
1010 // nodes we know about. The problem is that if we do this, then I don't know
1011 // how to get pool pointers for this head list. Since we are completely
1012 // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
1013 //
1014
1015 PtrNo = 0;
1016 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
1017 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
1018 // We DO transform the ret val... skip all possible entries for retval
1019 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
1020 PtrNo++;
1021 } else {
1022 // See what the return value points to...
1023
1024 // FIXME: This should generalize to any number of nodes, just see if any
1025 // are reachable.
1026 assert(CalledDS.getRetNodes().size() == 1 &&
1027 "Assumes only one node is returned");
1028 DSNode *N = CalledDS.getRetNodes()[0].Node;
1029
1030 // If the return value is not marked as being passed in, but it NEEDS to
1031 // be transformed, then make it known now.
1032 //
1033 if (ReachableNodes.count(N)) {
1034#ifdef DEBUG_TRANSFORM_PROGRESS
1035 cerr << "ensure dependant arguments adds return value entry!\n";
1036#endif
1037 addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1038
1039 // Keep sorted!
1040 finalizeConstruction();
1041 }
1042 }
1043
Chris Lattner7076ff22002-06-25 16:13:21 +00001044 i = 0;
1045 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I, ++i)
1046 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +00001047 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1048 // We DO transform this arg... skip all possible entries for argument
1049 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1050 PtrNo++;
1051 } else {
1052 // This should generalize to any number of nodes, just see if any are
1053 // reachable.
Chris Lattner7076ff22002-06-25 16:13:21 +00001054 assert(CalledDS.getValueMap()[I].size() == 1 &&
Chris Lattner3e78dea2002-04-18 14:43:30 +00001055 "Only handle case where pointing to one node so far!");
1056
1057 // If the arg is not marked as being passed in, but it NEEDS to
1058 // be transformed, then make it known now.
1059 //
Chris Lattner7076ff22002-06-25 16:13:21 +00001060 DSNode *N = CalledDS.getValueMap()[I][0].Node;
Chris Lattner3e78dea2002-04-18 14:43:30 +00001061 if (ReachableNodes.count(N)) {
1062#ifdef DEBUG_TRANSFORM_PROGRESS
1063 cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1064#endif
1065 addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1066
1067 // Keep sorted!
1068 finalizeConstruction();
1069 }
1070 }
1071 }
Chris Lattner396d5d72002-03-30 04:02:31 +00001072}
1073
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001074
1075// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +00001076// pools specified in PoolDescs when modifying data structure nodes specified in
1077// the PoolDescs map. Specifically, scalar values specified in the Scalars
1078// vector must be remapped. IPFGraph is the closed data structure graph for F,
1079// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001080//
1081void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +00001082 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001083
1084 // Loop through the value map looking for scalars that refer to nonescaping
1085 // allocations. Add them to the Scalars vector. Note that we may have
1086 // multiple entries in the Scalars vector for each value if it points to more
1087 // than one object.
1088 //
1089 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1090 vector<ScalarInfo> Scalars;
1091
Chris Lattneracf19022002-04-14 06:14:41 +00001092#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001093 cerr << "Building scalar map for fn '" << F->getName() << "' body:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001094#endif
Chris Lattner847b6e22002-03-30 20:53:14 +00001095
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001096 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1097 E = ValMap.end(); I != E; ++I) {
1098 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
1099
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001100 // Check to see if the scalar points to a data structure node...
1101 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001102 if (PVS[i].Index) { cerr << "Problem in " << F->getName() << " for " << I->first << "\n"; }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001103 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1104
1105 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +00001106 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1107 if (AI != PoolDescs.end()) { // Add it to the list of scalars
1108 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +00001109#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001110 cerr << "\nScalar Mapping from:" << I->first
1111 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +00001112#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001113 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001114 }
1115 }
1116
Chris Lattneracf19022002-04-14 06:14:41 +00001117#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001118 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +00001119 << "': Found the following values that point to poolable nodes:\n";
1120
1121 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +00001122 cerr << Scalars[i].Val;
1123 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001124#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +00001125
Chris Lattner692ad5d2002-03-29 17:13:46 +00001126 // CallMap - Contain an entry for every call instruction that needs to be
1127 // transformed. Each entry in the map contains information about what we need
1128 // to do to each call site to change it to work.
1129 //
1130 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +00001131
Chris Lattner441e16f2002-04-12 20:23:15 +00001132 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +00001133 // how. To do this, we look at all of the scalars, seeing which functions are
1134 // either used as a scalar value (so they return a data structure), or are
1135 // passed one of our scalar values.
1136 //
1137 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1138 Value *ScalarVal = Scalars[i].Val;
1139
1140 // Check to see if the scalar _IS_ a call...
1141 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1142 // If so, add information about the pool it will be returning...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001143 CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001144
1145 // Check to see if the scalar is an operand to a call...
1146 for (Value::use_iterator UI = ScalarVal->use_begin(),
1147 UE = ScalarVal->use_end(); UI != UE; ++UI) {
1148 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1149 // Find out which operand this is to the call instruction...
1150 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1151 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1152 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1153
1154 // FIXME: This is broken if the same pointer is passed to a call more
1155 // than once! It will get multiple entries for the first pointer.
1156
1157 // Add the operand number and pool handle to the call table...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001158 CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1159 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001160 }
1161 }
1162 }
1163
Chris Lattner3e78dea2002-04-18 14:43:30 +00001164 // Make sure that all dependant arguments are added as well. For example, if
1165 // we call foo(null, P) and foo treats it's first and second arguments as
1166 // belonging to the same data structure, the we MUST set up the CallMap to
1167 // know that the null needs to be transformed into an index as well.
1168 //
1169 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1170 I != CallMap.end(); ++I)
1171 I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1172
Chris Lattneracf19022002-04-14 06:14:41 +00001173#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +00001174 // Print out call map...
1175 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1176 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001177 cerr << "For call: " << I->first;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001178 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001179 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001180 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +00001181 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001182 }
Chris Lattneracf19022002-04-14 06:14:41 +00001183#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +00001184
1185 // Loop through all of the call nodes, recursively creating the new functions
1186 // that we want to call... This uses a map to prevent infinite recursion and
1187 // to avoid duplicating functions unneccesarily.
1188 //
1189 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1190 E = CallMap.end(); I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001191 // Transform all of the functions we need, or at least ensure there is a
1192 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +00001193 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001194 }
1195
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001196 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +00001197 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001198 // functions that we just hacked up.
1199 //
1200
1201 // First step, find the instructions to be modified.
1202 vector<Instruction*> InstToFix;
1203 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1204 Value *ScalarVal = Scalars[i].Val;
1205
1206 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
1207 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1208 InstToFix.push_back(Inst);
1209
1210 // All all of the instructions that use the scalar as an operand...
1211 for (Value::use_iterator UI = ScalarVal->use_begin(),
1212 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +00001213 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001214 }
1215
Chris Lattner50e3d322002-04-13 23:13:18 +00001216 // Make sure that we get return instructions that return a null value from the
1217 // function...
1218 //
1219 if (!IPFGraph.getRetNodes().empty()) {
1220 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1221 PointerVal RetNode = IPFGraph.getRetNodes()[0];
1222 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1223
1224 // Only process return instructions if the return value of this function is
1225 // part of one of the data structures we are transforming...
1226 //
1227 if (PoolDescs.count(RetNode.Node)) {
1228 // Loop over all of the basic blocks, adding return instructions...
1229 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001230 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
Chris Lattner50e3d322002-04-13 23:13:18 +00001231 InstToFix.push_back(RI);
1232 }
1233 }
1234
1235
1236
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001237 // Eliminate duplicates by sorting, then removing equal neighbors.
1238 sort(InstToFix.begin(), InstToFix.end());
1239 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1240
Chris Lattner441e16f2002-04-12 20:23:15 +00001241 // Loop over all of the instructions to transform, creating the new
1242 // replacement instructions for them. This also unlinks them from the
1243 // function so they can be safely deleted later.
1244 //
1245 map<Value*, Value*> XFormMap;
1246 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001247
Chris Lattner441e16f2002-04-12 20:23:15 +00001248 // Visit all instructions... creating the new instructions that we need and
1249 // unlinking the old instructions from the function...
1250 //
Chris Lattneracf19022002-04-14 06:14:41 +00001251#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001252 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1253 cerr << "Fixing: " << InstToFix[i];
Chris Lattner7076ff22002-06-25 16:13:21 +00001254 NIC.visit(*InstToFix[i]);
Chris Lattner441e16f2002-04-12 20:23:15 +00001255 }
Chris Lattneracf19022002-04-14 06:14:41 +00001256#else
1257 NIC.visit(InstToFix.begin(), InstToFix.end());
1258#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001259
1260 // Make all instructions we will delete "let go" of their operands... so that
1261 // we can safely delete Arguments whose types have changed...
1262 //
1263 for_each(InstToFix.begin(), InstToFix.end(),
Anand Shukla2bc64192002-06-25 21:07:58 +00001264 std::mem_fun(&Instruction::dropAllReferences));
Chris Lattner441e16f2002-04-12 20:23:15 +00001265
1266 // Loop through all of the pointer arguments coming into the function,
1267 // replacing them with arguments of POINTERTYPE to match the function type of
1268 // the function.
1269 //
1270 FunctionType::ParamTypes::const_iterator TI =
1271 F->getFunctionType()->getParamTypes().begin();
Chris Lattner7076ff22002-06-25 16:13:21 +00001272 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++TI) {
1273 if (I->getType() != *TI) {
1274 assert(isa<PointerType>(I->getType()) && *TI == POINTERTYPE);
1275 Argument *NewArg = new Argument(*TI, I->getName());
1276 XFormMap[I] = NewArg; // Map old arg into new arg...
Chris Lattner441e16f2002-04-12 20:23:15 +00001277
Chris Lattner441e16f2002-04-12 20:23:15 +00001278 // Replace the old argument and then delete it...
Chris Lattner7076ff22002-06-25 16:13:21 +00001279 I = F->getArgumentList().erase(I);
1280 I = F->getArgumentList().insert(I, NewArg);
Chris Lattner441e16f2002-04-12 20:23:15 +00001281 }
1282 }
1283
1284 // Now that all of the new instructions have been created, we can update all
1285 // of the references to dummy values to be references to the actual values
1286 // that are computed.
1287 //
1288 NIC.updateReferences();
1289
Chris Lattneracf19022002-04-14 06:14:41 +00001290#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001291 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +00001292#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001293
1294 // Delete all of the "instructions to fix"
1295 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001296
Chris Lattner457e1ac2002-04-15 22:42:23 +00001297 // Eliminate pool base loads that we can easily prove are redundant
1298 if (!DisableRLE)
1299 PoolBaseLoadEliminator(PoolDescs).visit(F);
1300
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001301 // Since we have liberally hacked the function to pieces, we want to inform
1302 // the datastructure pass that its internal representation is out of date.
1303 //
1304 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001305}
1306
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001307
1308
1309// transformFunction - Transform the specified function the specified way. It
1310// we have already transformed that function that way, don't do anything. The
1311// nodes in the TransformFunctionInfo come out of callers data structure graph.
1312//
1313void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001314 FunctionDSGraph &CallerIPGraph,
1315 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001316 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1317
Chris Lattneracf19022002-04-14 06:14:41 +00001318#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001319 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001320 << TFI.Func->getName() << ":\n";
1321 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1322 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1323 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001324#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001325
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001326 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001327
Chris Lattner291a1b12002-03-29 19:05:48 +00001328 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001329
Chris Lattner291a1b12002-03-29 19:05:48 +00001330 // Build the type for the new function that we are transforming
1331 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001332 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001333 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1334 ArgTys.push_back(OldFuncType->getParamType(i));
1335
Chris Lattner441e16f2002-04-12 20:23:15 +00001336 const Type *RetType = OldFuncType->getReturnType();
1337
Chris Lattner291a1b12002-03-29 19:05:48 +00001338 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001339 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1340 if (TFI.ArgInfo[i].ArgNo == -1)
1341 RetType = POINTERTYPE; // Return a pointer
1342 else
1343 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1344 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1345 ->second.PoolType));
1346 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001347
1348 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001349 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1350 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001351
1352 // The new function is internal, because we know that only we can call it.
1353 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001354 // pointers (which look like the same value is always passed into a parameter,
1355 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001356 //
1357 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001358 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001359 CurModule->getFunctionList().push_back(NewFunc);
1360
Chris Lattner441e16f2002-04-12 20:23:15 +00001361
Chris Lattneracf19022002-04-14 06:14:41 +00001362#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001363 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001364#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001365
Chris Lattner291a1b12002-03-29 19:05:48 +00001366 // Add the newly formed function to the TransformedFunctions table so that
1367 // infinite recursion does not occur!
1368 //
1369 TransformedFunctions[TFI] = NewFunc;
1370
1371 // Add arguments to the function... starting with all of the old arguments
1372 vector<Value*> ArgMap;
Chris Lattner7076ff22002-06-25 16:13:21 +00001373 for (Function::const_aiterator I = TFI.Func->abegin(), E = TFI.Func->aend();
1374 I != E; ++I) {
1375 Argument *NFA = new Argument(I->getType(), I->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001376 NewFunc->getArgumentList().push_back(NFA);
1377 ArgMap.push_back(NFA); // Keep track of the arguments
1378 }
1379
1380 // Now add all of the arguments corresponding to pools passed in...
1381 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001382 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001383 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001384 if (AI.ArgNo == -1)
1385 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001386 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001387 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1388 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1389 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001390 NewFunc->getArgumentList().push_back(NFA);
1391 }
1392
1393 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001394 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001395
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001396 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001397 // it has extra arguments for the pools coming in. Now we have to get the
1398 // data structure graph for the function we are replacing, and figure out how
1399 // our graph nodes map to the graph nodes in the dest function.
1400 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001401 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001402
Chris Lattner441e16f2002-04-12 20:23:15 +00001403 // NodeMapping - Multimap from callers graph to called graph. We are
1404 // guaranteed that the called function graph has more nodes than the caller,
1405 // or exactly the same number of nodes. This is because the called function
1406 // might not know that two nodes are merged when considering the callers
1407 // context, but the caller obviously does. Because of this, a single node in
1408 // the calling function's data structure graph can map to multiple nodes in
1409 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001410 //
1411 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001412
Chris Lattner847b6e22002-03-30 20:53:14 +00001413 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001414 NodeMapping);
1415
1416 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001417#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001418 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001419 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1420 I != NodeMapping.end(); ++I) {
1421 cerr << "Map: "; I->first->print(cerr);
1422 cerr << "To: "; I->second.print(cerr);
1423 cerr << "\n";
1424 }
Chris Lattneracf19022002-04-14 06:14:41 +00001425#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001426
1427 // Fill in the PoolDescriptor information for the transformed function so that
1428 // it can determine which value holds the pool descriptor for each data
1429 // structure node that it accesses.
1430 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001431 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001432
Chris Lattneracf19022002-04-14 06:14:41 +00001433#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001434 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001435#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001436
Chris Lattner441e16f2002-04-12 20:23:15 +00001437 // Calculate as much of the pool descriptor map as possible. Since we have
1438 // the node mapping between the caller and callee functions, and we have the
1439 // pool descriptor information of the caller, we can calculate a partical pool
1440 // descriptor map for the called function.
1441 //
1442 // The nodes that we do not have complete information for are the ones that
1443 // are accessed by loading pointers derived from arguments passed in, but that
1444 // are not passed in directly. In this case, we have all of the information
1445 // except a pool value. If the called function refers to this pool, the pool
1446 // value will be loaded from the pool graph and added to the map as neccesary.
1447 //
1448 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1449 I != NodeMapping.end(); ++I) {
1450 DSNode *CallerNode = I->first;
1451 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001452
Chris Lattner441e16f2002-04-12 20:23:15 +00001453 // Check to see if we have a node pointer passed in for this value...
1454 Value *CalleeValue = 0;
1455 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1456 if (TFI.ArgInfo[a].Node == CallerNode) {
1457 // Calculate the argument number that the pool is to the function
1458 // call... The call instruction should not have the pool operands added
1459 // yet.
1460 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001461#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001462 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001463#endif
Chris Lattner7076ff22002-06-25 16:13:21 +00001464 assert(ArgNo < NewFunc->asize() &&
Chris Lattner441e16f2002-04-12 20:23:15 +00001465 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001466
Chris Lattner441e16f2002-04-12 20:23:15 +00001467 // Map the pool argument into the called function...
Chris Lattner7076ff22002-06-25 16:13:21 +00001468 Function::aiterator AI = NewFunc->abegin();
1469 std::advance(AI, ArgNo);
1470 CalleeValue = AI;
Chris Lattner441e16f2002-04-12 20:23:15 +00001471 break; // Found value, quit loop
1472 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001473
Chris Lattner441e16f2002-04-12 20:23:15 +00001474 // Loop over all of the data structure nodes that this incoming node maps to
1475 // Creating a PoolInfo structure for them.
1476 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1477 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1478 DSNode *CalleeNode = I->second[i].Node;
1479
1480 // Add the descriptor. We already know everything about it by now, much
1481 // of it is the same as the caller info.
1482 //
Anand Shukla2bc64192002-06-25 21:07:58 +00001483 PoolDescs.insert(std::make_pair(CalleeNode,
Chris Lattner441e16f2002-04-12 20:23:15 +00001484 PoolInfo(CalleeNode, CalleeValue,
1485 CallerPI.NewType,
1486 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001487 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001488 }
1489
1490 // We must destroy the node mapping so that we don't have latent references
1491 // into the data structure graph for the new function. Otherwise we get
1492 // assertion failures when transformFunctionBody tries to invalidate the
1493 // graph.
1494 //
1495 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001496
1497 // Now that we know everything we need about the function, transform the body
1498 // now!
1499 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001500 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1501
Chris Lattneracf19022002-04-14 06:14:41 +00001502#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001503 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001504#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001505}
1506
Chris Lattner8f796d62002-04-13 19:25:57 +00001507static unsigned countPointerTypes(const Type *Ty) {
1508 if (isa<PointerType>(Ty)) {
1509 return 1;
Chris Lattner7076ff22002-06-25 16:13:21 +00001510 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001511 unsigned Num = 0;
1512 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1513 Num += countPointerTypes(STy->getElementTypes()[i]);
1514 return Num;
Chris Lattner7076ff22002-06-25 16:13:21 +00001515 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001516 return countPointerTypes(ATy->getElementType());
1517 } else {
1518 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1519 return 0;
1520 }
1521}
Chris Lattner66df97d2002-03-29 06:21:38 +00001522
1523// CreatePools - Insert instructions into the function we are processing to
1524// create all of the memory pool objects themselves. This also inserts
1525// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001526// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001527//
1528void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001529 map<DSNode*, PoolInfo> &PoolDescs) {
1530 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001531 vector<BasicBlock*> ReturnNodes;
1532 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001533 if (isa<ReturnInst>(I->getTerminator()))
1534 ReturnNodes.push_back(I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001535
Chris Lattner3e78dea2002-04-18 14:43:30 +00001536#ifdef DEBUG_CREATE_POOLS
1537 cerr << "Allocs that we are pool allocating:\n";
1538 for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1539 Allocs[i]->dump();
1540#endif
1541
Chris Lattner441e16f2002-04-12 20:23:15 +00001542 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1543
1544 // First pass over the allocations to process...
1545 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1546 // Create the pooldescriptor mapping... with null entries for everything
1547 // except the node & NewType fields.
1548 //
1549 map<DSNode*, PoolInfo>::iterator PI =
Anand Shukla2bc64192002-06-25 21:07:58 +00001550 PoolDescs.insert(std::make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
Chris Lattner441e16f2002-04-12 20:23:15 +00001551
Chris Lattner8f796d62002-04-13 19:25:57 +00001552 // Add a symbol table entry for the new type if there was one for the old
1553 // type...
1554 string OldName = CurModule->getTypeName(Allocs[i]->getType());
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001555 if (OldName.empty()) OldName = "node";
1556 CurModule->addTypeName(OldName+".p", PI->second.NewType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001557
Chris Lattner441e16f2002-04-12 20:23:15 +00001558 // Create the abstract pool types that will need to be resolved in a second
1559 // pass once an abstract type is created for each pool.
1560 //
1561 // Can only handle limited shapes for now...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001562 const Type *OldNodeTy = Allocs[i]->getType();
Chris Lattner441e16f2002-04-12 20:23:15 +00001563 vector<const Type*> PoolTypes;
1564
1565 // Pool type is the first element of the pool descriptor type...
1566 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001567
1568 unsigned NumPointers = countPointerTypes(OldNodeTy);
1569 while (NumPointers--) // Add a different opaque type for each pointer
1570 PoolTypes.push_back(OpaqueType::get());
1571
Chris Lattner441e16f2002-04-12 20:23:15 +00001572 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1573 "Node should have same number of pointers as pool!");
1574
Chris Lattner8f796d62002-04-13 19:25:57 +00001575 StructType *PoolType = StructType::get(PoolTypes);
1576
1577 // Add a symbol table entry for the pooltype if possible...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001578 CurModule->addTypeName(OldName+".pool", PoolType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001579
Chris Lattner441e16f2002-04-12 20:23:15 +00001580 // Create the pool type, with opaque values for pointers...
Anand Shukla2bc64192002-06-25 21:07:58 +00001581 AbsPoolTyMap.insert(std::make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001582#ifdef DEBUG_CREATE_POOLS
1583 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1584#endif
1585 }
1586
1587 // Now that we have types for all of the pool types, link them all together.
1588 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1589 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1590
1591 // Resolve all of the outgoing pointer types of this pool node...
1592 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1593 PointerValSet &PVS = Allocs[i]->getLink(p);
1594 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1595 " probably just leave the type opaque or something dumb.");
1596 unsigned Out;
1597 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1598 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1599
1600 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1601
1602 // The actual struct type could change each time through the loop, so it's
1603 // NOT loop invariant.
Chris Lattner7076ff22002-06-25 16:13:21 +00001604 const StructType *PoolTy = cast<StructType>(PoolTyH.get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001605
1606 // Get the opaque type...
Chris Lattner7076ff22002-06-25 16:13:21 +00001607 DerivedType *ElTy = (DerivedType*)(PoolTy->getElementTypes()[p+1].get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001608
1609#ifdef DEBUG_CREATE_POOLS
1610 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1611 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1612#endif
1613
1614 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1615 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1616
1617#ifdef DEBUG_CREATE_POOLS
1618 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1619#endif
1620 }
1621 }
1622
1623 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001624 vector<Instruction*> EntryNodeInsts;
1625 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001626 PoolInfo &PI = PoolDescs[Allocs[i]];
1627
1628 // Fill in the pool type for this pool...
1629 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1630 assert(!PI.PoolType->isAbstract() &&
1631 "Pool type should not be abstract anymore!");
1632
Chris Lattnere0618ca2002-03-29 05:50:20 +00001633 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001634 AllocaInst *PoolAlloc
1635 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1636 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001637 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001638 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001639 AllocationInst *AI = Allocs[i]->getAllocation();
1640
1641 // Initialize the pool. We need to know how big each allocation is. For
1642 // our purposes here, we assume we are allocating a scalar, or array of
1643 // constant size.
1644 //
Chris Lattneracf19022002-04-14 06:14:41 +00001645 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001646
1647 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001648 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001649 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001650 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1651
Chris Lattner441e16f2002-04-12 20:23:15 +00001652 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001653 Args.clear();
1654 Args.push_back(PoolAlloc); // Pool to initialize
1655
Chris Lattnere0618ca2002-03-29 05:50:20 +00001656 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1657 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1658
1659 // Insert it before the return instruction...
1660 BasicBlock *RetNode = ReturnNodes[EN];
Chris Lattner7076ff22002-06-25 16:13:21 +00001661 RetNode->getInstList().insert(RetNode->end()--, Destroy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001662 }
1663 }
1664
Chris Lattner5da145b2002-04-13 19:52:54 +00001665 // Now that all of the pool descriptors have been created, link them together
1666 // so that called functions can get links as neccesary...
1667 //
1668 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1669 PoolInfo &PI = PoolDescs[Allocs[i]];
1670
1671 // For every pointer in the data structure, initialize a link that
1672 // indicates which pool to access...
1673 //
1674 vector<Value*> Indices(2);
1675 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1676 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1677 // Only store an entry for the field if the field is used!
1678 if (!PI.Node->getLink(l).empty()) {
1679 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1680 PointerVal PV = PI.Node->getLink(l)[0];
1681 assert(PV.Index == 0 && "Subindexing not supported yet!");
1682 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1683 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1684
1685 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1686 Indices));
1687 }
1688 }
1689
Chris Lattnere0618ca2002-03-29 05:50:20 +00001690 // Insert the entry node code into the entry block...
Chris Lattner7076ff22002-06-25 16:13:21 +00001691 F->getEntryNode().getInstList().insert(++F->getEntryNode().begin(),
Chris Lattnere0618ca2002-03-29 05:50:20 +00001692 EntryNodeInsts.begin(),
1693 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001694}
1695
1696
Chris Lattner441e16f2002-04-12 20:23:15 +00001697// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001698// module and update the Pool* instance variables to point to them.
1699//
Chris Lattner7076ff22002-06-25 16:13:21 +00001700void PoolAllocate::addPoolPrototypes(Module &M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001701 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001702 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001703 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001704 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001705 PoolInit = M.getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001706
Chris Lattnere0618ca2002-03-29 05:50:20 +00001707 // Get pooldestroy function...
1708 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001709 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001710 PoolDestroy = M.getOrInsertFunction("pooldestroy", PoolDestroyTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001711
Chris Lattnere0618ca2002-03-29 05:50:20 +00001712 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001713 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001714 PoolAlloc = M.getOrInsertFunction("poolalloc", PoolAllocTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001715
1716 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001717 Args.push_back(POINTERTYPE); // Pointer to free
1718 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001719 PoolFree = M.getOrInsertFunction("poolfree", PoolFreeTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001720
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001721 Args[0] = Type::UIntTy; // Number of slots to allocate
1722 FunctionType *PoolAllocArrayTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001723 PoolAllocArray = M.getOrInsertFunction("poolallocarray", PoolAllocArrayTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001724}
1725
1726
Chris Lattner7076ff22002-06-25 16:13:21 +00001727bool PoolAllocate::run(Module &M) {
Chris Lattner175f37c2002-03-29 03:40:59 +00001728 addPoolPrototypes(M);
Chris Lattner7076ff22002-06-25 16:13:21 +00001729 CurModule = &M;
Chris Lattner175f37c2002-03-29 03:40:59 +00001730
1731 DS = &getAnalysis<DataStructure>();
1732 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001733
Chris Lattner7076ff22002-06-25 16:13:21 +00001734 for (Module::iterator I = M.begin(); I != M.end(); ++I)
1735 if (!I->isExternal()) {
1736 Changed |= processFunction(I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001737 if (Changed) {
1738 cerr << "Only processing one function\n";
1739 break;
1740 }
1741 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001742
1743 CurModule = 0;
1744 DS = 0;
1745 return false;
1746}
1747
1748
1749// createPoolAllocatePass - Global function to access the functionality of this
1750// pass...
1751//
Chris Lattner64fd9352002-03-28 18:08:31 +00001752Pass *createPoolAllocatePass() { return new PoolAllocate(); }