blob: 5182df4eb477b641b9adbe197a892d59ac4849cf [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>
Chris Lattner64fd9352002-03-28 18:08:31 +000027
Chris Lattner441e16f2002-04-12 20:23:15 +000028// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
29// creation phase in the top level function of a transformed data structure.
30//
Chris Lattneracf19022002-04-14 06:14:41 +000031//#define DEBUG_CREATE_POOLS 1
32
33// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
34// the transformation is doing.
35//
36//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000037
Chris Lattner457e1ac2002-04-15 22:42:23 +000038// DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
39// many static loads were eliminated from a function...
40//
41#define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
42
Chris Lattner50e3d322002-04-13 23:13:18 +000043#include "Support/CommandLine.h"
44enum PtrSize {
45 Ptr8bits, Ptr16bits, Ptr32bits
46};
47
48static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
Chris Lattneracf19022002-04-14 06:14:41 +000049 "Set pointer size for -poolalloc pass",
Chris Lattner50e3d322002-04-13 23:13:18 +000050 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
51 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
52 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"), 0);
53
Chris Lattner457e1ac2002-04-15 22:42:23 +000054static cl::Flag DisableRLE("no-pool-load-elim", "Disable pool load elimination after poolalloc pass", cl::Hidden);
55
Chris Lattner441e16f2002-04-12 20:23:15 +000056const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000057
Chris Lattnere0618ca2002-03-29 05:50:20 +000058// FIXME: This is dependant on the sparc backend layout conventions!!
59static TargetData TargetData("test");
60
Chris Lattner50e3d322002-04-13 23:13:18 +000061static const Type *getPointerTransformedType(const Type *Ty) {
Chris Lattner7076ff22002-06-25 16:13:21 +000062 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000063 return POINTERTYPE;
Chris Lattner7076ff22002-06-25 16:13:21 +000064 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000065 vector<const Type *> NewElTypes;
66 NewElTypes.reserve(STy->getElementTypes().size());
67 for (StructType::ElementTypes::const_iterator
68 I = STy->getElementTypes().begin(),
69 E = STy->getElementTypes().end(); I != E; ++I)
70 NewElTypes.push_back(getPointerTransformedType(*I));
71 return StructType::get(NewElTypes);
Chris Lattner7076ff22002-06-25 16:13:21 +000072 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000073 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
74 ATy->getNumElements());
75 } else {
76 assert(Ty->isPrimitiveType() && "Unknown derived type!");
77 return Ty;
78 }
79}
80
Chris Lattner64fd9352002-03-28 18:08:31 +000081namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000082 struct PoolInfo {
83 DSNode *Node; // The node this pool allocation represents
84 Value *Handle; // LLVM value of the pool in the current context
85 const Type *NewType; // The transformed type of the memory objects
86 const Type *PoolType; // The type of the pool
87
88 const Type *getOldType() const { return Node->getType(); }
89
90 PoolInfo() { // Define a default ctor for map::operator[]
91 cerr << "Map subscript used to get element that doesn't exist!\n";
92 abort(); // Invalid
93 }
94
95 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
96 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
97 // Handle can be null...
98 assert(N && NT && PT && "Pool info null!");
99 }
100
101 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
102 assert(N && "Invalid pool info!");
103
104 // The new type of the memory object is the same as the old type, except
105 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000106 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000107 }
108 };
109
Chris Lattner692ad5d2002-03-29 17:13:46 +0000110 // ScalarInfo - Information about an LLVM value that we know points to some
111 // datastructure we are processing.
112 //
113 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000114 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000115 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000116
Chris Lattner441e16f2002-04-12 20:23:15 +0000117 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
118 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000119 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000120 };
121
Chris Lattner396d5d72002-03-30 04:02:31 +0000122 // CallArgInfo - Information on one operand for a call that got expanded.
123 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000124 int ArgNo; // Call argument number this corresponds to
125 DSNode *Node; // The graph node for the pool
126 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000127
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000128 CallArgInfo(int Arg, DSNode *N, Value *PH)
129 : ArgNo(Arg), Node(N), PoolHandle(PH) {
130 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000131 }
132
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000133 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000134 bool operator<(const CallArgInfo &CAI) const {
135 return ArgNo < CAI.ArgNo;
136 }
137 };
138
Chris Lattner692ad5d2002-03-29 17:13:46 +0000139 // TransformFunctionInfo - Information about how a function eeds to be
140 // transformed.
141 //
142 struct TransformFunctionInfo {
143 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000144 // processed. Each CallArgInfo corresponds to an argument that needs to
145 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000146 //
147 // As a special case, "argument" number -1 corresponds to the return value.
148 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000149 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000150
151 // Func - The function to be transformed...
152 Function *Func;
153
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000154 // The call instruction that is used to map CallArgInfo PoolHandle values
155 // into the new function values.
156 CallInst *Call;
157
Chris Lattner692ad5d2002-03-29 17:13:46 +0000158 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000159 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000160
Chris Lattner396d5d72002-03-30 04:02:31 +0000161 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000162 if (Func < TFI.Func) return true;
163 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000164 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
165 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000166 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000167 }
168
169 void finalizeConstruction() {
170 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000171 // argument records, in order. Note that this must be a stable sort so
172 // that the entries with the same sorting criteria (ie they are multiple
173 // pool entries for the same argument) are kept in depth first order.
174 stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000175 }
Chris Lattner3e78dea2002-04-18 14:43:30 +0000176
177 // addCallInfo - For a specified function call CI, figure out which pool
178 // descriptors need to be passed in as arguments, and which arguments need
179 // to be transformed into indices. If Arg != -1, the specified call
180 // argument is passed in as a pointer to a data structure.
181 //
182 void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
183 DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
184
185 // Make sure that all dependant arguments are added to this transformation
186 // info. For example, if we call foo(null, P) and foo treats it's first and
187 // second arguments as belonging to the same data structure, the we MUST add
188 // entries to know that the null needs to be transformed into an index as
189 // well.
190 //
191 void ensureDependantArgumentsIncluded(DataStructure *DS,
192 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000193 };
194
195
196 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000197 struct PoolAllocate : public Pass {
Chris Lattner37104aa2002-04-29 14:57:45 +0000198 const char *getPassName() const { return "Pool Allocate"; }
199
Chris Lattner175f37c2002-03-29 03:40:59 +0000200 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000201 switch (ReqPointerSize) {
202 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
203 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
204 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
205 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000206
207 CurModule = 0; DS = 0;
208 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000209 }
210
Chris Lattner441e16f2002-04-12 20:23:15 +0000211 // getPoolType - Get the type used by the backend for a pool of a particular
212 // type. This pool record is used to allocate nodes of type NodeType.
213 //
214 // Here, PoolTy = { NodeType*, sbyte*, uint }*
215 //
216 const StructType *getPoolType(const Type *NodeType) {
217 vector<const Type*> PoolElements;
218 PoolElements.push_back(PointerType::get(NodeType));
219 PoolElements.push_back(PointerType::get(Type::SByteTy));
220 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000221 StructType *Result = StructType::get(PoolElements);
222
223 // Add a name to the symbol table to correspond to the backend
224 // representation of this pool...
225 assert(CurModule && "No current module!?");
226 string Name = CurModule->getTypeName(NodeType);
227 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
228 CurModule->addTypeName(Name+"oolbe", Result);
229
230 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000231 }
232
Chris Lattner7076ff22002-06-25 16:13:21 +0000233 bool run(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000234
Chris Lattnerc8e66542002-04-27 06:56:12 +0000235 // getAnalysisUsage - This function requires data structure information
Chris Lattner175f37c2002-03-29 03:40:59 +0000236 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000237 //
Chris Lattnerc8e66542002-04-27 06:56:12 +0000238 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
239 AU.addRequired(DataStructure::ID);
Chris Lattner64fd9352002-03-28 18:08:31 +0000240 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000241
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000242 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000243 // CurModule - The module being processed.
244 Module *CurModule;
245
246 // DS - The data structure graph for the module being processed.
247 DataStructure *DS;
248
249 // Prototypes that we add to support pool allocation...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000250 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolAllocArray, *PoolFree;
Chris Lattner175f37c2002-03-29 03:40:59 +0000251
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000252 // The map of already transformed functions... note that the keys of this
253 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
254 // of the ArgInfo elements.
255 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000256 map<TransformFunctionInfo, Function*> TransformedFunctions;
257
258 // getTransformedFunction - Get a transformed function, or return null if
259 // the function specified hasn't been transformed yet.
260 //
261 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
262 map<TransformFunctionInfo, Function*>::const_iterator I =
263 TransformedFunctions.find(TFI);
264 if (I != TransformedFunctions.end()) return I->second;
265 return 0;
266 }
267
268
Chris Lattner441e16f2002-04-12 20:23:15 +0000269 // addPoolPrototypes - Add prototypes for the pool functions to the
270 // specified module and update the Pool* instance variables to point to
271 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000272 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000273 void addPoolPrototypes(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000274
Chris Lattner66df97d2002-03-29 06:21:38 +0000275
276 // CreatePools - Insert instructions into the function we are processing to
277 // create all of the memory pool objects themselves. This also inserts
278 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000279 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000280 //
281 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000282 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000283
Chris Lattner175f37c2002-03-29 03:40:59 +0000284 // processFunction - Convert a function to use pool allocation where
285 // available.
286 //
287 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000288
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000289 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000290 // pools specified in PoolDescs when modifying data structure nodes
291 // specified in the PoolDescs map. IPFGraph is the closed data structure
292 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000293 //
294 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000295 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000296
297 // transformFunction - Transform the specified function the specified way.
298 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000299 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000300 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000301 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000302 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000303 FunctionDSGraph &CallerIPGraph,
304 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000305
Chris Lattner64fd9352002-03-28 18:08:31 +0000306 };
307}
308
Chris Lattner692ad5d2002-03-29 17:13:46 +0000309// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000310// allocation node in a data structure graph is eligable for pool allocation.
311//
312static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000313 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattnere0618ca2002-03-29 05:50:20 +0000314 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000315}
316
Chris Lattner175f37c2002-03-29 03:40:59 +0000317// processFunction - Convert a function to use pool allocation where
318// available.
319//
320bool PoolAllocate::processFunction(Function *F) {
321 // Get the closed datastructure graph for the current function... if there are
322 // any allocations in this graph that are not escaping, we need to pool
323 // allocate them here!
324 //
325 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
326
327 // Get all of the allocations that do not escape the current function. Since
328 // they are still live (they exist in the graph at all), this means we must
329 // have scalar references to these nodes, but the scalars are never returned.
330 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000331 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000332 IPGraph.getNonEscapingAllocations(Allocs);
333
334 // Filter out allocations that we cannot handle. Currently, this includes
335 // variable sized array allocations and alloca's (which we do not want to
336 // pool allocate)
337 //
338 Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
339 Allocs.end());
340
341
342 if (Allocs.empty()) return false; // Nothing to do.
343
Chris Lattner3e78dea2002-04-18 14:43:30 +0000344#ifdef DEBUG_TRANSFORM_PROGRESS
345 cerr << "Transforming Function: " << F->getName() << "\n";
346#endif
347
Chris Lattner692ad5d2002-03-29 17:13:46 +0000348 // Insert instructions into the function we are processing to create all of
349 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000350 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000351 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000352 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000353 map<DSNode*, PoolInfo> PoolDescs;
354 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000355
Chris Lattneracf19022002-04-14 06:14:41 +0000356#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000357 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000358#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000359
360 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000361 // how. To do this, we look at all of the scalars, seeing which functions are
362 // either used as a scalar value (so they return a data structure), or are
363 // passed one of our scalar values.
364 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000365 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000366
367 return true;
368}
369
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000370
Chris Lattner441e16f2002-04-12 20:23:15 +0000371//===----------------------------------------------------------------------===//
372//
373// NewInstructionCreator - This class is used to traverse the function being
374// modified, changing each instruction visit'ed to use and provide pointer
375// indexes instead of real pointers. This is what changes the body of a
376// function to use pool allocation.
377//
378class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000379 PoolAllocate &PoolAllocator;
380 vector<ScalarInfo> &Scalars;
381 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000382 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000383
Chris Lattner441e16f2002-04-12 20:23:15 +0000384 struct RefToUpdate {
385 Instruction *I; // Instruction to update
386 unsigned OpNum; // Operand number to update
387 Value *OldVal; // The old value it had
388
389 RefToUpdate(Instruction *i, unsigned o, Value *ov)
390 : I(i), OpNum(o), OldVal(ov) {}
391 };
392 vector<RefToUpdate> ReferencesToUpdate;
393
394 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000395 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
396 if (Scalars[i].Val == V) return Scalars[i];
Chris Lattner3e78dea2002-04-18 14:43:30 +0000397
398 cerr << "Could not find scalar " << V << " in scalar map!\n";
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000399 assert(0 && "Scalar not found in getScalar!");
400 abort();
401 return Scalars[0];
402 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000403
404 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000405 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000406 if (Scalars[i].Val == V) return &Scalars[i];
407 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000408 }
409
Chris Lattner7076ff22002-06-25 16:13:21 +0000410 BasicBlock::iterator ReplaceInstWith(Instruction &I, Instruction *New) {
411 BasicBlock *BB = I.getParent();
412 BasicBlock::iterator RI = &I;
413 BB->getInstList().remove(RI);
414 BB->getInstList().insert(RI, New);
415 XFormMap[&I] = New;
416 return New;
Chris Lattner441e16f2002-04-12 20:23:15 +0000417 }
418
Chris Lattner39db8712002-05-02 17:38:14 +0000419 Instruction *createPoolBaseInstruction(Value *PtrVal) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000420 const ScalarInfo &SC = getScalarRef(PtrVal);
421 vector<Value*> Args(3);
422 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
423 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
424 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
Chris Lattner39db8712002-05-02 17:38:14 +0000425 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
Chris Lattner441e16f2002-04-12 20:23:15 +0000426 }
427
428
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000429public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000430 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
431 map<CallInst*, TransformFunctionInfo> &C,
432 map<Value*, Value*> &X)
433 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000434
Chris Lattner441e16f2002-04-12 20:23:15 +0000435
436 // updateReferences - The NewInstructionCreator is responsible for creating
437 // new instructions to replace the old ones in the function, and then link up
438 // references to values to their new values. For it to do this, however, it
439 // keeps track of information about the value mapping of old values to new
440 // values that need to be patched up. Given this value map and a set of
441 // instruction operands to patch, updateReferences performs the updates.
442 //
443 void updateReferences() {
444 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
445 RefToUpdate &Ref = ReferencesToUpdate[i];
446 Value *NewVal = XFormMap[Ref.OldVal];
447
448 if (NewVal == 0) {
449 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
450 cast<Constant>(Ref.OldVal)->isNullValue()) {
451 // Transform the null pointer into a null index... caching in XFormMap
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000452 XFormMap[Ref.OldVal] = NewVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000453 //} else if (isa<Argument>(Ref.OldVal)) {
454 } else {
455 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
456 assert(XFormMap[Ref.OldVal] &&
457 "Reference to value that was not updated found!");
458 }
459 }
460
461 Ref.I->setOperand(Ref.OpNum, NewVal);
462 }
463 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000464 }
465
Chris Lattner441e16f2002-04-12 20:23:15 +0000466 //===--------------------------------------------------------------------===//
467 // Transformation methods:
468 // These methods specify how each type of instruction is transformed by the
469 // NewInstructionCreator instance...
470 //===--------------------------------------------------------------------===//
471
Chris Lattner7076ff22002-06-25 16:13:21 +0000472 void visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000473 assert(0 && "Cannot transform get element ptr instructions yet!");
474 }
475
476 // Replace the load instruction with a new one.
Chris Lattner7076ff22002-06-25 16:13:21 +0000477 void visitLoadInst(LoadInst &I) {
Chris Lattner39db8712002-05-02 17:38:14 +0000478 vector<Instruction *> BeforeInsts;
Chris Lattner441e16f2002-04-12 20:23:15 +0000479
480 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000481 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000482 Type::UIntTy, I.getOperand(0)->getName());
Chris Lattner39db8712002-05-02 17:38:14 +0000483 BeforeInsts.push_back(Index);
Chris Lattner7076ff22002-06-25 16:13:21 +0000484 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(0)));
Chris Lattner39db8712002-05-02 17:38:14 +0000485
486 // Include the pool base instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000487 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(0));
Chris Lattner39db8712002-05-02 17:38:14 +0000488 BeforeInsts.push_back(PoolBase);
489
490 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000491 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index,
492 I.getName()+".idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000493 BeforeInsts.push_back(IdxInst);
Chris Lattner441e16f2002-04-12 20:23:15 +0000494
Chris Lattner7076ff22002-06-25 16:13:21 +0000495 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000496 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000497 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000498 I.getName()+".addr");
Chris Lattner39db8712002-05-02 17:38:14 +0000499 BeforeInsts.push_back(Address);
500
Chris Lattner7076ff22002-06-25 16:13:21 +0000501 Instruction *NewLoad = new LoadInst(Address, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000502
503 // Replace the load instruction with the new load instruction...
504 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
505
Chris Lattner39db8712002-05-02 17:38:14 +0000506 // Add all of the instructions before the load...
507 NewLoad->getParent()->getInstList().insert(II, BeforeInsts.begin(),
508 BeforeInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000509
510 // If not yielding a pool allocated pointer, use the new load value as the
511 // value in the program instead of the old load value...
512 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000513 if (!getScalar(&I))
514 I.replaceAllUsesWith(NewLoad);
Chris Lattner441e16f2002-04-12 20:23:15 +0000515 }
516
517 // Replace the store instruction with a new one. In the store instruction,
518 // the value stored could be a pointer type, meaning that the new store may
519 // have to change one or both of it's operands.
520 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000521 void visitStoreInst(StoreInst &I) {
522 assert(getScalar(I.getOperand(1)) &&
Chris Lattner441e16f2002-04-12 20:23:15 +0000523 "Store inst found only storing pool allocated pointer. "
524 "Not imp yet!");
525
Chris Lattner7076ff22002-06-25 16:13:21 +0000526 Value *Val = I.getOperand(0); // The value to store...
Chris Lattner39db8712002-05-02 17:38:14 +0000527
Chris Lattner441e16f2002-04-12 20:23:15 +0000528 // Check to see if the value we are storing is a data structure pointer...
Chris Lattner7076ff22002-06-25 16:13:21 +0000529 //if (const ScalarInfo *ValScalar = getScalar(I.getOperand(0)))
530 if (isa<PointerType>(I.getOperand(0)->getType()))
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000531 Val = Constant::getNullValue(POINTERTYPE); // Yes, store a dummy
Chris Lattner441e16f2002-04-12 20:23:15 +0000532
Chris Lattner7076ff22002-06-25 16:13:21 +0000533 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(1));
Chris Lattner441e16f2002-04-12 20:23:15 +0000534
535 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000536 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000537 Type::UIntTy, I.getOperand(1)->getName());
538 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000539
Chris Lattner39db8712002-05-02 17:38:14 +0000540 // Instructions to add after the Index...
541 vector<Instruction*> AfterInsts;
542
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000543 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000544 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index, "idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000545 AfterInsts.push_back(IdxInst);
546
Chris Lattner7076ff22002-06-25 16:13:21 +0000547 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000548 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000549 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000550 I.getName()+"storeaddr");
Chris Lattner39db8712002-05-02 17:38:14 +0000551 AfterInsts.push_back(Address);
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000552
Chris Lattner39db8712002-05-02 17:38:14 +0000553 Instruction *NewStore = new StoreInst(Val, Address);
554 AfterInsts.push_back(NewStore);
Chris Lattner7076ff22002-06-25 16:13:21 +0000555 if (Val != I.getOperand(0)) // Value stored was a pointer?
556 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I.getOperand(0)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000557
558
559 // Replace the store instruction with the cast instruction...
560 BasicBlock::iterator II = ReplaceInstWith(I, Index);
561
562 // Add the pool base calculator instruction before the index...
Chris Lattner7076ff22002-06-25 16:13:21 +0000563 II = ++Index->getParent()->getInstList().insert(II, PoolBase);
564 ++II;
Chris Lattner441e16f2002-04-12 20:23:15 +0000565
Chris Lattner39db8712002-05-02 17:38:14 +0000566 // Add the instructions that go after the index...
567 Index->getParent()->getInstList().insert(II, AfterInsts.begin(),
568 AfterInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000569 }
570
571
572 // Create call to poolalloc for every malloc instruction
Chris Lattner7076ff22002-06-25 16:13:21 +0000573 void visitMallocInst(MallocInst &I) {
574 const ScalarInfo &SCI = getScalarRef(&I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000575 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000576
577 CallInst *Call;
Chris Lattner7076ff22002-06-25 16:13:21 +0000578 if (!I.isArrayAllocation()) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000579 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000580 Call = new CallInst(PoolAllocator.PoolAlloc, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000581 } else {
Chris Lattner7076ff22002-06-25 16:13:21 +0000582 Args.push_back(I.getArraySize());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000583 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000584 Call = new CallInst(PoolAllocator.PoolAllocArray, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000585 }
586
Chris Lattner441e16f2002-04-12 20:23:15 +0000587 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000588 }
589
Chris Lattner441e16f2002-04-12 20:23:15 +0000590 // Convert a call to poolfree for every free instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000591 void visitFreeInst(FreeInst &I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000592 // Create a new call to poolfree before the free instruction
593 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000594 Args.push_back(Constant::getNullValue(POINTERTYPE));
Chris Lattner7076ff22002-06-25 16:13:21 +0000595 Args.push_back(getScalarRef(I.getOperand(0)).Pool.Handle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000596 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
597 ReplaceInstWith(I, NewCall);
Chris Lattner7076ff22002-06-25 16:13:21 +0000598 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I.getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000599 }
600
601 // visitCallInst - Create a new call instruction with the extra arguments for
602 // all of the memory pools that the call needs.
603 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000604 void visitCallInst(CallInst &I) {
605 TransformFunctionInfo &TI = CallMap[&I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000606
607 // Start with all of the old arguments...
Chris Lattner7076ff22002-06-25 16:13:21 +0000608 vector<Value*> Args(I.op_begin()+1, I.op_end());
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000609
Chris Lattner441e16f2002-04-12 20:23:15 +0000610 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
611 // Replace all of the pointer arguments with our new pointer typed values.
612 if (TI.ArgInfo[i].ArgNo != -1)
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000613 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000614
615 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000616 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000617 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000618
619 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner7076ff22002-06-25 16:13:21 +0000620 Instruction *NewCall = new CallInst(NF, Args, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000621 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000622
Chris Lattner441e16f2002-04-12 20:23:15 +0000623 // Keep track of the mapping of operands so that we can resolve them to real
624 // values later.
625 Value *RetVal = NewCall;
626 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
627 if (TI.ArgInfo[i].ArgNo != -1)
628 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
Chris Lattner7076ff22002-06-25 16:13:21 +0000629 I.getOperand(TI.ArgInfo[i].ArgNo+1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000630 else
631 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000632
Chris Lattner441e16f2002-04-12 20:23:15 +0000633 // If not returning a pointer, use the new call as the value in the program
634 // instead of the old call...
635 //
636 if (RetVal)
Chris Lattner7076ff22002-06-25 16:13:21 +0000637 I.replaceAllUsesWith(RetVal);
Chris Lattner441e16f2002-04-12 20:23:15 +0000638 }
639
640 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
641 // nodes...
642 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000643 void visitPHINode(PHINode &PN) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000644 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000645 PHINode *NewPhi = new PHINode(POINTERTYPE, PN.getName());
646 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
647 NewPhi->addIncoming(DummyVal, PN.getIncomingBlock(i));
Chris Lattner441e16f2002-04-12 20:23:15 +0000648 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
Chris Lattner7076ff22002-06-25 16:13:21 +0000649 PN.getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000650 }
651
Chris Lattner441e16f2002-04-12 20:23:15 +0000652 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000653 }
654
Chris Lattner441e16f2002-04-12 20:23:15 +0000655 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner7076ff22002-06-25 16:13:21 +0000656 void visitReturnInst(ReturnInst &I) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000657 Instruction *Ret = new ReturnInst(Constant::getNullValue(POINTERTYPE));
Chris Lattner441e16f2002-04-12 20:23:15 +0000658 ReplaceInstWith(I, Ret);
Chris Lattner7076ff22002-06-25 16:13:21 +0000659 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I.getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000660 }
661
Chris Lattner441e16f2002-04-12 20:23:15 +0000662 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattner7076ff22002-06-25 16:13:21 +0000663 void visitSetCondInst(SetCondInst &SCI) {
664 BinaryOperator &I = (BinaryOperator&)SCI;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000665 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000666 BinaryOperator *New = BinaryOperator::create(I.getOpcode(), DummyVal,
667 DummyVal, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000668 ReplaceInstWith(I, New);
669
Chris Lattner7076ff22002-06-25 16:13:21 +0000670 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I.getOperand(0)));
671 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000672
673 // Make sure branches refer to the new condition...
Chris Lattner7076ff22002-06-25 16:13:21 +0000674 I.replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000675 }
676
Chris Lattner7076ff22002-06-25 16:13:21 +0000677 void visitInstruction(Instruction &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000678 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000679 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000680};
681
682
Chris Lattner457e1ac2002-04-15 22:42:23 +0000683// PoolBaseLoadEliminator - Every load and store through a pool allocated
684// pointer causes a load of the real pool base out of the pool descriptor.
685// Iterate through the function, doing a local elimination pass of duplicate
686// loads. This attempts to turn the all too common:
687//
688// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
689// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
690// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
691// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
692//
693// into:
694// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
695// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
696// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
697//
698//
699class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
700 // PoolDescValues - Keep track of the values in the current function that are
701 // pool descriptors (loads from which we want to eliminate).
702 //
703 vector<Value*> PoolDescValues;
704
705 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
706 // when referencing a pool descriptor.
707 //
708 map<Value*, LoadInst*> PoolDescMap;
709
710 // These two fields keep track of statistics of how effective we are, if
711 // debugging is enabled.
712 //
713 unsigned Eliminated, Remaining;
714public:
715 // Compact the pool descriptor map into a list of the pool descriptors in the
716 // current context that we should know about...
717 //
718 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
719 Eliminated = Remaining = 0;
720 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
721 E = PoolDescs.end(); I != E; ++I)
722 PoolDescValues.push_back(I->second.Handle);
723
724 // Remove duplicates from the list of pool values
725 sort(PoolDescValues.begin(), PoolDescValues.end());
726 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
727 PoolDescValues.end());
728 }
729
730#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
Chris Lattner7076ff22002-06-25 16:13:21 +0000731 void visitFunction(Function &F) {
732 cerr << "Pool Load Elim '" << F.getName() << "'\t";
Chris Lattner457e1ac2002-04-15 22:42:23 +0000733 }
734 ~PoolBaseLoadEliminator() {
735 unsigned Total = Eliminated+Remaining;
736 if (Total)
737 cerr << "removed " << Eliminated << "["
738 << Eliminated*100/Total << "%] loads, leaving "
739 << Remaining << ".\n";
740 }
741#endif
742
743 // Loop over the function, looking for loads to eliminate. Because we are a
744 // local transformation, we reset all of our state when we enter a new basic
745 // block.
746 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000747 void visitBasicBlock(BasicBlock &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000748 PoolDescMap.clear(); // Forget state.
749 }
750
751 // Starting with an empty basic block, we scan it looking for loads of the
752 // pool descriptor. When we find a load, we add it to the PoolDescMap,
753 // indicating that we have a value available to recycle next time we see the
754 // poolbase of this instruction being loaded.
755 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000756 void visitLoadInst(LoadInst &LI) {
757 Value *LoadAddr = LI.getPointerOperand();
Chris Lattner457e1ac2002-04-15 22:42:23 +0000758 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
759 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
Chris Lattner7076ff22002-06-25 16:13:21 +0000760 LI.replaceAllUsesWith(VIt->second); // Make the current load dead
Chris Lattner457e1ac2002-04-15 22:42:23 +0000761 ++Eliminated;
762 } else {
763 // This load might not be a load of a pool pointer, check to see if it is
Chris Lattner7076ff22002-06-25 16:13:21 +0000764 if (LI.getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
Chris Lattner457e1ac2002-04-15 22:42:23 +0000765 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
766 PoolDescValues.end()) {
767
768 assert("Make sure it's a load of the pool base, not a chaining field" &&
Chris Lattner7076ff22002-06-25 16:13:21 +0000769 LI.getOperand(1) == Constant::getNullValue(Type::UIntTy) &&
770 LI.getOperand(2) == Constant::getNullValue(Type::UByteTy) &&
771 LI.getOperand(3) == Constant::getNullValue(Type::UByteTy));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000772
773 // If it is a load of a pool base, keep track of it for future reference
Chris Lattner7076ff22002-06-25 16:13:21 +0000774 PoolDescMap.insert(make_pair(LoadAddr, &LI));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000775 ++Remaining;
776 }
777 }
778 }
779
780 // If we run across a function call, forget all state... Calls to
781 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
782 // reloaded the next time it is used. Furthermore, a call to a random
783 // function might call one of these functions, so be conservative. Through
784 // more analysis, this could be improved in the future.
785 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000786 void visitCallInst(CallInst &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000787 PoolDescMap.clear();
788 }
789};
790
Chris Lattner3e78dea2002-04-18 14:43:30 +0000791static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
792 map<DSNode*, PointerValSet> &NodeMapping) {
793 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
794 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
795 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
796 DSNode *DestNode = PVS[i].Node;
797
798 // Loop over all of the outgoing links in the mapped graph
799 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
800 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
801 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
802
803 // Add all of the node mappings now!
804 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
805 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
806 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
807 }
808 }
809 }
810}
811
812// CalculateNodeMapping - There is a partial isomorphism between the graph
813// passed in and the graph that is actually used by the function. We need to
814// figure out what this mapping is so that we can transformFunctionBody the
815// instructions in the function itself. Note that every node in the graph that
816// we are interested in must be both in the local graph of the called function,
817// and in the local graph of the calling function. Because of this, we only
818// define the mapping for these nodes [conveniently these are the only nodes we
819// CAN define a mapping for...]
820//
821// The roots of the graph that we are transforming is rooted in the arguments
822// passed into the function from the caller. This is where we start our
823// mapping calculation.
824//
825// The NodeMapping calculated maps from the callers graph to the called graph.
826//
827static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
828 FunctionDSGraph &CallerGraph,
829 FunctionDSGraph &CalledGraph,
830 map<DSNode*, PointerValSet> &NodeMapping) {
831 int LastArgNo = -2;
832 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
833 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
834 // corresponds to...
835 //
836 // Only consider first node of sequence. Extra nodes may may be added
837 // to the TFI if the data structure requires more nodes than just the
838 // one the argument points to. We are only interested in the one the
839 // argument points to though.
840 //
841 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
842 if (TFI.ArgInfo[i].ArgNo == -1) {
843 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
844 NodeMapping);
845 } else {
846 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner7076ff22002-06-25 16:13:21 +0000847 Function::aiterator AI = F->abegin();
848 std::advance(AI, TFI.ArgInfo[i].ArgNo);
849 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[AI],
Chris Lattner3e78dea2002-04-18 14:43:30 +0000850 NodeMapping);
851 }
852 LastArgNo = TFI.ArgInfo[i].ArgNo;
853 }
854 }
855}
Chris Lattner441e16f2002-04-12 20:23:15 +0000856
857
Chris Lattner3e78dea2002-04-18 14:43:30 +0000858
859
860// addCallInfo - For a specified function call CI, figure out which pool
861// descriptors need to be passed in as arguments, and which arguments need to be
862// transformed into indices. If Arg != -1, the specified call argument is
863// passed in as a pointer to a data structure.
864//
865void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
866 int Arg, DSNode *GraphNode,
867 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000868 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000869 assert(Func == 0 || Func == CI->getCalledFunction() &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000870 "Function call record should always call the same function!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000871 assert(Call == 0 || Call == CI &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000872 "Call element already filled in with different value!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000873 Func = CI->getCalledFunction();
874 Call = CI;
875 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000876
877 // For now, add the entire graph that is pointed to by the call argument.
878 // This graph can and should be pruned to only what the function itself will
879 // use, because often this will be a dramatically smaller subset of what we
880 // are providing.
881 //
Chris Lattner3e78dea2002-04-18 14:43:30 +0000882 // FIXME: This should use pool links instead of extra arguments!
883 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000884 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000885 I != E; ++I)
Chris Lattner3e78dea2002-04-18 14:43:30 +0000886 ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
887}
888
889static void markReachableNodes(const PointerValSet &Vals,
890 set<DSNode*> &ReachableNodes) {
891 for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
892 DSNode *N = Vals[n].Node;
893 if (ReachableNodes.count(N) == 0) // Haven't already processed node?
894 ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
895 }
896}
897
898// Make sure that all dependant arguments are added to this transformation info.
899// For example, if we call foo(null, P) and foo treats it's first and second
900// arguments as belonging to the same data structure, the we MUST add entries to
901// know that the null needs to be transformed into an index as well.
902//
903void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
904 map<DSNode*, PoolInfo> &PoolDescs) {
905 // FIXME: This does not work for indirect function calls!!!
906 if (Func == 0) return; // FIXME!
907
908 // Make sure argument entries are sorted.
909 finalizeConstruction();
910
911 // Loop over the function signature, checking to see if there are any pointer
912 // arguments that we do not convert... if there is something we haven't
913 // converted, set done to false.
914 //
915 unsigned PtrNo = 0;
916 bool Done = true;
917 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
918 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
919 // We DO transform the ret val... skip all possible entries for retval
920 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
921 PtrNo++;
922 } else {
923 Done = false;
924 }
925
Chris Lattner7076ff22002-06-25 16:13:21 +0000926 unsigned i = 0;
927 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I,++i){
928 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +0000929 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
930 // We DO transform this arg... skip all possible entries for argument
931 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
932 PtrNo++;
933 } else {
934 Done = false;
935 break;
936 }
937 }
938 }
939
940 // If we already have entries for all pointer arguments and retvals, there
941 // certainly is no work to do. Bail out early to avoid building relatively
942 // expensive data structures.
943 //
944 if (Done) return;
945
946#ifdef DEBUG_TRANSFORM_PROGRESS
947 cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
948#endif
949
950 // Otherwise, we MIGHT have to add the arguments/retval if they are part of
951 // the same datastructure graph as some other argument or retval that we ARE
952 // processing.
953 //
954 // Get the data structure graph for the called function.
955 //
956 FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
957
958 // Build a mapping between the nodes in our current graph and the nodes in the
959 // called function's graph. We build it based on our _incomplete_
960 // transformation information, because it contains all of the info that we
961 // should need.
962 //
963 map<DSNode*, PointerValSet> NodeMapping;
964 CalculateNodeMapping(Func, *this,
965 DS->getClosedDSGraph(Call->getParent()->getParent()),
966 CalledDS, NodeMapping);
967
968 // Build the inverted version of the node mapping, that maps from a node in
969 // the called functions graph to a single node in the caller graph.
970 //
971 map<DSNode*, DSNode*> InverseNodeMap;
972 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
973 E = NodeMapping.end(); I != E; ++I) {
974 PointerValSet &CalledNodes = I->second;
975 for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
976 InverseNodeMap[CalledNodes[i].Node] = I->first;
977 }
978 NodeMapping.clear(); // Done with information, free memory
979
980 // Build a set of reachable nodes from the arguments/retval that we ARE
981 // passing in...
982 set<DSNode*> ReachableNodes;
983
984 // Loop through all of the arguments, marking all of the reachable data
985 // structure nodes reachable if they are from this pointer...
986 //
987 for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
988 if (ArgInfo[i].ArgNo == -1) {
989 if (i == 0) // Only process retvals once (performance opt)
990 markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
991 } else { // If it's an argument value...
Chris Lattner7076ff22002-06-25 16:13:21 +0000992 Function::aiterator AI = Func->abegin();
993 std::advance(AI, ArgInfo[i].ArgNo);
994 if (isa<PointerType>(AI->getType()))
995 markReachableNodes(CalledDS.getValueMap()[AI], ReachableNodes);
Chris Lattner3e78dea2002-04-18 14:43:30 +0000996 }
997 }
998
999 // Now that we know which nodes are already reachable, see if any of the
1000 // arguments that we are not passing values in for can reach one of the
1001 // existing nodes...
1002 //
1003
1004 // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
1005 // nodes we know about. The problem is that if we do this, then I don't know
1006 // how to get pool pointers for this head list. Since we are completely
1007 // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
1008 //
1009
1010 PtrNo = 0;
1011 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
1012 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
1013 // We DO transform the ret val... skip all possible entries for retval
1014 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
1015 PtrNo++;
1016 } else {
1017 // See what the return value points to...
1018
1019 // FIXME: This should generalize to any number of nodes, just see if any
1020 // are reachable.
1021 assert(CalledDS.getRetNodes().size() == 1 &&
1022 "Assumes only one node is returned");
1023 DSNode *N = CalledDS.getRetNodes()[0].Node;
1024
1025 // If the return value is not marked as being passed in, but it NEEDS to
1026 // be transformed, then make it known now.
1027 //
1028 if (ReachableNodes.count(N)) {
1029#ifdef DEBUG_TRANSFORM_PROGRESS
1030 cerr << "ensure dependant arguments adds return value entry!\n";
1031#endif
1032 addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1033
1034 // Keep sorted!
1035 finalizeConstruction();
1036 }
1037 }
1038
Chris Lattner7076ff22002-06-25 16:13:21 +00001039 i = 0;
1040 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I, ++i)
1041 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +00001042 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1043 // We DO transform this arg... skip all possible entries for argument
1044 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1045 PtrNo++;
1046 } else {
1047 // This should generalize to any number of nodes, just see if any are
1048 // reachable.
Chris Lattner7076ff22002-06-25 16:13:21 +00001049 assert(CalledDS.getValueMap()[I].size() == 1 &&
Chris Lattner3e78dea2002-04-18 14:43:30 +00001050 "Only handle case where pointing to one node so far!");
1051
1052 // If the arg is not marked as being passed in, but it NEEDS to
1053 // be transformed, then make it known now.
1054 //
Chris Lattner7076ff22002-06-25 16:13:21 +00001055 DSNode *N = CalledDS.getValueMap()[I][0].Node;
Chris Lattner3e78dea2002-04-18 14:43:30 +00001056 if (ReachableNodes.count(N)) {
1057#ifdef DEBUG_TRANSFORM_PROGRESS
1058 cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1059#endif
1060 addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1061
1062 // Keep sorted!
1063 finalizeConstruction();
1064 }
1065 }
1066 }
Chris Lattner396d5d72002-03-30 04:02:31 +00001067}
1068
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001069
1070// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +00001071// pools specified in PoolDescs when modifying data structure nodes specified in
1072// the PoolDescs map. Specifically, scalar values specified in the Scalars
1073// vector must be remapped. IPFGraph is the closed data structure graph for F,
1074// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001075//
1076void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +00001077 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001078
1079 // Loop through the value map looking for scalars that refer to nonescaping
1080 // allocations. Add them to the Scalars vector. Note that we may have
1081 // multiple entries in the Scalars vector for each value if it points to more
1082 // than one object.
1083 //
1084 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1085 vector<ScalarInfo> Scalars;
1086
Chris Lattneracf19022002-04-14 06:14:41 +00001087#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001088 cerr << "Building scalar map for fn '" << F->getName() << "' body:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001089#endif
Chris Lattner847b6e22002-03-30 20:53:14 +00001090
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001091 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1092 E = ValMap.end(); I != E; ++I) {
1093 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
1094
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001095 // Check to see if the scalar points to a data structure node...
1096 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001097 if (PVS[i].Index) { cerr << "Problem in " << F->getName() << " for " << I->first << "\n"; }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001098 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1099
1100 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +00001101 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1102 if (AI != PoolDescs.end()) { // Add it to the list of scalars
1103 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +00001104#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001105 cerr << "\nScalar Mapping from:" << I->first
1106 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +00001107#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001108 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001109 }
1110 }
1111
Chris Lattneracf19022002-04-14 06:14:41 +00001112#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001113 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +00001114 << "': Found the following values that point to poolable nodes:\n";
1115
1116 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +00001117 cerr << Scalars[i].Val;
1118 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001119#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +00001120
Chris Lattner692ad5d2002-03-29 17:13:46 +00001121 // CallMap - Contain an entry for every call instruction that needs to be
1122 // transformed. Each entry in the map contains information about what we need
1123 // to do to each call site to change it to work.
1124 //
1125 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +00001126
Chris Lattner441e16f2002-04-12 20:23:15 +00001127 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +00001128 // how. To do this, we look at all of the scalars, seeing which functions are
1129 // either used as a scalar value (so they return a data structure), or are
1130 // passed one of our scalar values.
1131 //
1132 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1133 Value *ScalarVal = Scalars[i].Val;
1134
1135 // Check to see if the scalar _IS_ a call...
1136 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1137 // If so, add information about the pool it will be returning...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001138 CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001139
1140 // Check to see if the scalar is an operand to a call...
1141 for (Value::use_iterator UI = ScalarVal->use_begin(),
1142 UE = ScalarVal->use_end(); UI != UE; ++UI) {
1143 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1144 // Find out which operand this is to the call instruction...
1145 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1146 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1147 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1148
1149 // FIXME: This is broken if the same pointer is passed to a call more
1150 // than once! It will get multiple entries for the first pointer.
1151
1152 // Add the operand number and pool handle to the call table...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001153 CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1154 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001155 }
1156 }
1157 }
1158
Chris Lattner3e78dea2002-04-18 14:43:30 +00001159 // Make sure that all dependant arguments are added as well. For example, if
1160 // we call foo(null, P) and foo treats it's first and second arguments as
1161 // belonging to the same data structure, the we MUST set up the CallMap to
1162 // know that the null needs to be transformed into an index as well.
1163 //
1164 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1165 I != CallMap.end(); ++I)
1166 I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1167
Chris Lattneracf19022002-04-14 06:14:41 +00001168#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +00001169 // Print out call map...
1170 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1171 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001172 cerr << "For call: " << I->first;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001173 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001174 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001175 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +00001176 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001177 }
Chris Lattneracf19022002-04-14 06:14:41 +00001178#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +00001179
1180 // Loop through all of the call nodes, recursively creating the new functions
1181 // that we want to call... This uses a map to prevent infinite recursion and
1182 // to avoid duplicating functions unneccesarily.
1183 //
1184 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1185 E = CallMap.end(); I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001186 // Transform all of the functions we need, or at least ensure there is a
1187 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +00001188 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001189 }
1190
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001191 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +00001192 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001193 // functions that we just hacked up.
1194 //
1195
1196 // First step, find the instructions to be modified.
1197 vector<Instruction*> InstToFix;
1198 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1199 Value *ScalarVal = Scalars[i].Val;
1200
1201 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
1202 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1203 InstToFix.push_back(Inst);
1204
1205 // All all of the instructions that use the scalar as an operand...
1206 for (Value::use_iterator UI = ScalarVal->use_begin(),
1207 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +00001208 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001209 }
1210
Chris Lattner50e3d322002-04-13 23:13:18 +00001211 // Make sure that we get return instructions that return a null value from the
1212 // function...
1213 //
1214 if (!IPFGraph.getRetNodes().empty()) {
1215 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1216 PointerVal RetNode = IPFGraph.getRetNodes()[0];
1217 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1218
1219 // Only process return instructions if the return value of this function is
1220 // part of one of the data structures we are transforming...
1221 //
1222 if (PoolDescs.count(RetNode.Node)) {
1223 // Loop over all of the basic blocks, adding return instructions...
1224 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001225 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
Chris Lattner50e3d322002-04-13 23:13:18 +00001226 InstToFix.push_back(RI);
1227 }
1228 }
1229
1230
1231
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001232 // Eliminate duplicates by sorting, then removing equal neighbors.
1233 sort(InstToFix.begin(), InstToFix.end());
1234 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1235
Chris Lattner441e16f2002-04-12 20:23:15 +00001236 // Loop over all of the instructions to transform, creating the new
1237 // replacement instructions for them. This also unlinks them from the
1238 // function so they can be safely deleted later.
1239 //
1240 map<Value*, Value*> XFormMap;
1241 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001242
Chris Lattner441e16f2002-04-12 20:23:15 +00001243 // Visit all instructions... creating the new instructions that we need and
1244 // unlinking the old instructions from the function...
1245 //
Chris Lattneracf19022002-04-14 06:14:41 +00001246#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001247 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1248 cerr << "Fixing: " << InstToFix[i];
Chris Lattner7076ff22002-06-25 16:13:21 +00001249 NIC.visit(*InstToFix[i]);
Chris Lattner441e16f2002-04-12 20:23:15 +00001250 }
Chris Lattneracf19022002-04-14 06:14:41 +00001251#else
1252 NIC.visit(InstToFix.begin(), InstToFix.end());
1253#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001254
1255 // Make all instructions we will delete "let go" of their operands... so that
1256 // we can safely delete Arguments whose types have changed...
1257 //
1258 for_each(InstToFix.begin(), InstToFix.end(),
1259 mem_fun(&Instruction::dropAllReferences));
1260
1261 // Loop through all of the pointer arguments coming into the function,
1262 // replacing them with arguments of POINTERTYPE to match the function type of
1263 // the function.
1264 //
1265 FunctionType::ParamTypes::const_iterator TI =
1266 F->getFunctionType()->getParamTypes().begin();
Chris Lattner7076ff22002-06-25 16:13:21 +00001267 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++TI) {
1268 if (I->getType() != *TI) {
1269 assert(isa<PointerType>(I->getType()) && *TI == POINTERTYPE);
1270 Argument *NewArg = new Argument(*TI, I->getName());
1271 XFormMap[I] = NewArg; // Map old arg into new arg...
Chris Lattner441e16f2002-04-12 20:23:15 +00001272
Chris Lattner441e16f2002-04-12 20:23:15 +00001273 // Replace the old argument and then delete it...
Chris Lattner7076ff22002-06-25 16:13:21 +00001274 I = F->getArgumentList().erase(I);
1275 I = F->getArgumentList().insert(I, NewArg);
Chris Lattner441e16f2002-04-12 20:23:15 +00001276 }
1277 }
1278
1279 // Now that all of the new instructions have been created, we can update all
1280 // of the references to dummy values to be references to the actual values
1281 // that are computed.
1282 //
1283 NIC.updateReferences();
1284
Chris Lattneracf19022002-04-14 06:14:41 +00001285#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001286 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +00001287#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001288
1289 // Delete all of the "instructions to fix"
1290 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001291
Chris Lattner457e1ac2002-04-15 22:42:23 +00001292 // Eliminate pool base loads that we can easily prove are redundant
1293 if (!DisableRLE)
1294 PoolBaseLoadEliminator(PoolDescs).visit(F);
1295
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001296 // Since we have liberally hacked the function to pieces, we want to inform
1297 // the datastructure pass that its internal representation is out of date.
1298 //
1299 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001300}
1301
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001302
1303
1304// transformFunction - Transform the specified function the specified way. It
1305// we have already transformed that function that way, don't do anything. The
1306// nodes in the TransformFunctionInfo come out of callers data structure graph.
1307//
1308void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001309 FunctionDSGraph &CallerIPGraph,
1310 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001311 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1312
Chris Lattneracf19022002-04-14 06:14:41 +00001313#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001314 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001315 << TFI.Func->getName() << ":\n";
1316 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1317 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1318 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001319#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001320
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001321 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001322
Chris Lattner291a1b12002-03-29 19:05:48 +00001323 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001324
Chris Lattner291a1b12002-03-29 19:05:48 +00001325 // Build the type for the new function that we are transforming
1326 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001327 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001328 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1329 ArgTys.push_back(OldFuncType->getParamType(i));
1330
Chris Lattner441e16f2002-04-12 20:23:15 +00001331 const Type *RetType = OldFuncType->getReturnType();
1332
Chris Lattner291a1b12002-03-29 19:05:48 +00001333 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001334 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1335 if (TFI.ArgInfo[i].ArgNo == -1)
1336 RetType = POINTERTYPE; // Return a pointer
1337 else
1338 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1339 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1340 ->second.PoolType));
1341 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001342
1343 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001344 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1345 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001346
1347 // The new function is internal, because we know that only we can call it.
1348 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001349 // pointers (which look like the same value is always passed into a parameter,
1350 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001351 //
1352 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001353 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001354 CurModule->getFunctionList().push_back(NewFunc);
1355
Chris Lattner441e16f2002-04-12 20:23:15 +00001356
Chris Lattneracf19022002-04-14 06:14:41 +00001357#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001358 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001359#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001360
Chris Lattner291a1b12002-03-29 19:05:48 +00001361 // Add the newly formed function to the TransformedFunctions table so that
1362 // infinite recursion does not occur!
1363 //
1364 TransformedFunctions[TFI] = NewFunc;
1365
1366 // Add arguments to the function... starting with all of the old arguments
1367 vector<Value*> ArgMap;
Chris Lattner7076ff22002-06-25 16:13:21 +00001368 for (Function::const_aiterator I = TFI.Func->abegin(), E = TFI.Func->aend();
1369 I != E; ++I) {
1370 Argument *NFA = new Argument(I->getType(), I->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001371 NewFunc->getArgumentList().push_back(NFA);
1372 ArgMap.push_back(NFA); // Keep track of the arguments
1373 }
1374
1375 // Now add all of the arguments corresponding to pools passed in...
1376 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001377 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001378 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001379 if (AI.ArgNo == -1)
1380 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001381 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001382 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1383 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1384 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001385 NewFunc->getArgumentList().push_back(NFA);
1386 }
1387
1388 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001389 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001390
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001391 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001392 // it has extra arguments for the pools coming in. Now we have to get the
1393 // data structure graph for the function we are replacing, and figure out how
1394 // our graph nodes map to the graph nodes in the dest function.
1395 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001396 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001397
Chris Lattner441e16f2002-04-12 20:23:15 +00001398 // NodeMapping - Multimap from callers graph to called graph. We are
1399 // guaranteed that the called function graph has more nodes than the caller,
1400 // or exactly the same number of nodes. This is because the called function
1401 // might not know that two nodes are merged when considering the callers
1402 // context, but the caller obviously does. Because of this, a single node in
1403 // the calling function's data structure graph can map to multiple nodes in
1404 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001405 //
1406 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001407
Chris Lattner847b6e22002-03-30 20:53:14 +00001408 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001409 NodeMapping);
1410
1411 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001412#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001413 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001414 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1415 I != NodeMapping.end(); ++I) {
1416 cerr << "Map: "; I->first->print(cerr);
1417 cerr << "To: "; I->second.print(cerr);
1418 cerr << "\n";
1419 }
Chris Lattneracf19022002-04-14 06:14:41 +00001420#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001421
1422 // Fill in the PoolDescriptor information for the transformed function so that
1423 // it can determine which value holds the pool descriptor for each data
1424 // structure node that it accesses.
1425 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001426 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001427
Chris Lattneracf19022002-04-14 06:14:41 +00001428#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001429 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001430#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001431
Chris Lattner441e16f2002-04-12 20:23:15 +00001432 // Calculate as much of the pool descriptor map as possible. Since we have
1433 // the node mapping between the caller and callee functions, and we have the
1434 // pool descriptor information of the caller, we can calculate a partical pool
1435 // descriptor map for the called function.
1436 //
1437 // The nodes that we do not have complete information for are the ones that
1438 // are accessed by loading pointers derived from arguments passed in, but that
1439 // are not passed in directly. In this case, we have all of the information
1440 // except a pool value. If the called function refers to this pool, the pool
1441 // value will be loaded from the pool graph and added to the map as neccesary.
1442 //
1443 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1444 I != NodeMapping.end(); ++I) {
1445 DSNode *CallerNode = I->first;
1446 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001447
Chris Lattner441e16f2002-04-12 20:23:15 +00001448 // Check to see if we have a node pointer passed in for this value...
1449 Value *CalleeValue = 0;
1450 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1451 if (TFI.ArgInfo[a].Node == CallerNode) {
1452 // Calculate the argument number that the pool is to the function
1453 // call... The call instruction should not have the pool operands added
1454 // yet.
1455 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001456#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001457 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001458#endif
Chris Lattner7076ff22002-06-25 16:13:21 +00001459 assert(ArgNo < NewFunc->asize() &&
Chris Lattner441e16f2002-04-12 20:23:15 +00001460 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001461
Chris Lattner441e16f2002-04-12 20:23:15 +00001462 // Map the pool argument into the called function...
Chris Lattner7076ff22002-06-25 16:13:21 +00001463 Function::aiterator AI = NewFunc->abegin();
1464 std::advance(AI, ArgNo);
1465 CalleeValue = AI;
Chris Lattner441e16f2002-04-12 20:23:15 +00001466 break; // Found value, quit loop
1467 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001468
Chris Lattner441e16f2002-04-12 20:23:15 +00001469 // Loop over all of the data structure nodes that this incoming node maps to
1470 // Creating a PoolInfo structure for them.
1471 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1472 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1473 DSNode *CalleeNode = I->second[i].Node;
1474
1475 // Add the descriptor. We already know everything about it by now, much
1476 // of it is the same as the caller info.
1477 //
1478 PoolDescs.insert(make_pair(CalleeNode,
1479 PoolInfo(CalleeNode, CalleeValue,
1480 CallerPI.NewType,
1481 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001482 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001483 }
1484
1485 // We must destroy the node mapping so that we don't have latent references
1486 // into the data structure graph for the new function. Otherwise we get
1487 // assertion failures when transformFunctionBody tries to invalidate the
1488 // graph.
1489 //
1490 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001491
1492 // Now that we know everything we need about the function, transform the body
1493 // now!
1494 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001495 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1496
Chris Lattneracf19022002-04-14 06:14:41 +00001497#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001498 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001499#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001500}
1501
Chris Lattner8f796d62002-04-13 19:25:57 +00001502static unsigned countPointerTypes(const Type *Ty) {
1503 if (isa<PointerType>(Ty)) {
1504 return 1;
Chris Lattner7076ff22002-06-25 16:13:21 +00001505 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001506 unsigned Num = 0;
1507 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1508 Num += countPointerTypes(STy->getElementTypes()[i]);
1509 return Num;
Chris Lattner7076ff22002-06-25 16:13:21 +00001510 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001511 return countPointerTypes(ATy->getElementType());
1512 } else {
1513 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1514 return 0;
1515 }
1516}
Chris Lattner66df97d2002-03-29 06:21:38 +00001517
1518// CreatePools - Insert instructions into the function we are processing to
1519// create all of the memory pool objects themselves. This also inserts
1520// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001521// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001522//
1523void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001524 map<DSNode*, PoolInfo> &PoolDescs) {
1525 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001526 vector<BasicBlock*> ReturnNodes;
1527 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001528 if (isa<ReturnInst>(I->getTerminator()))
1529 ReturnNodes.push_back(I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001530
Chris Lattner3e78dea2002-04-18 14:43:30 +00001531#ifdef DEBUG_CREATE_POOLS
1532 cerr << "Allocs that we are pool allocating:\n";
1533 for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1534 Allocs[i]->dump();
1535#endif
1536
Chris Lattner441e16f2002-04-12 20:23:15 +00001537 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1538
1539 // First pass over the allocations to process...
1540 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1541 // Create the pooldescriptor mapping... with null entries for everything
1542 // except the node & NewType fields.
1543 //
1544 map<DSNode*, PoolInfo>::iterator PI =
1545 PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1546
Chris Lattner8f796d62002-04-13 19:25:57 +00001547 // Add a symbol table entry for the new type if there was one for the old
1548 // type...
1549 string OldName = CurModule->getTypeName(Allocs[i]->getType());
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001550 if (OldName.empty()) OldName = "node";
1551 CurModule->addTypeName(OldName+".p", PI->second.NewType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001552
Chris Lattner441e16f2002-04-12 20:23:15 +00001553 // Create the abstract pool types that will need to be resolved in a second
1554 // pass once an abstract type is created for each pool.
1555 //
1556 // Can only handle limited shapes for now...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001557 const Type *OldNodeTy = Allocs[i]->getType();
Chris Lattner441e16f2002-04-12 20:23:15 +00001558 vector<const Type*> PoolTypes;
1559
1560 // Pool type is the first element of the pool descriptor type...
1561 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001562
1563 unsigned NumPointers = countPointerTypes(OldNodeTy);
1564 while (NumPointers--) // Add a different opaque type for each pointer
1565 PoolTypes.push_back(OpaqueType::get());
1566
Chris Lattner441e16f2002-04-12 20:23:15 +00001567 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1568 "Node should have same number of pointers as pool!");
1569
Chris Lattner8f796d62002-04-13 19:25:57 +00001570 StructType *PoolType = StructType::get(PoolTypes);
1571
1572 // Add a symbol table entry for the pooltype if possible...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001573 CurModule->addTypeName(OldName+".pool", PoolType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001574
Chris Lattner441e16f2002-04-12 20:23:15 +00001575 // Create the pool type, with opaque values for pointers...
Chris Lattner8f796d62002-04-13 19:25:57 +00001576 AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001577#ifdef DEBUG_CREATE_POOLS
1578 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1579#endif
1580 }
1581
1582 // Now that we have types for all of the pool types, link them all together.
1583 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1584 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1585
1586 // Resolve all of the outgoing pointer types of this pool node...
1587 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1588 PointerValSet &PVS = Allocs[i]->getLink(p);
1589 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1590 " probably just leave the type opaque or something dumb.");
1591 unsigned Out;
1592 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1593 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1594
1595 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1596
1597 // The actual struct type could change each time through the loop, so it's
1598 // NOT loop invariant.
Chris Lattner7076ff22002-06-25 16:13:21 +00001599 const StructType *PoolTy = cast<StructType>(PoolTyH.get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001600
1601 // Get the opaque type...
Chris Lattner7076ff22002-06-25 16:13:21 +00001602 DerivedType *ElTy = (DerivedType*)(PoolTy->getElementTypes()[p+1].get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001603
1604#ifdef DEBUG_CREATE_POOLS
1605 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1606 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1607#endif
1608
1609 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1610 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1611
1612#ifdef DEBUG_CREATE_POOLS
1613 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1614#endif
1615 }
1616 }
1617
1618 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001619 vector<Instruction*> EntryNodeInsts;
1620 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001621 PoolInfo &PI = PoolDescs[Allocs[i]];
1622
1623 // Fill in the pool type for this pool...
1624 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1625 assert(!PI.PoolType->isAbstract() &&
1626 "Pool type should not be abstract anymore!");
1627
Chris Lattnere0618ca2002-03-29 05:50:20 +00001628 // Add an allocation and a free for each pool...
Chris Lattner5da145b2002-04-13 19:52:54 +00001629 AllocaInst *PoolAlloc
1630 = new AllocaInst(PointerType::get(PI.PoolType), 0,
1631 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001632 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001633 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001634 AllocationInst *AI = Allocs[i]->getAllocation();
1635
1636 // Initialize the pool. We need to know how big each allocation is. For
1637 // our purposes here, we assume we are allocating a scalar, or array of
1638 // constant size.
1639 //
Chris Lattneracf19022002-04-14 06:14:41 +00001640 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001641
1642 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001643 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001644 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001645 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1646
Chris Lattner441e16f2002-04-12 20:23:15 +00001647 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001648 Args.clear();
1649 Args.push_back(PoolAlloc); // Pool to initialize
1650
Chris Lattnere0618ca2002-03-29 05:50:20 +00001651 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1652 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1653
1654 // Insert it before the return instruction...
1655 BasicBlock *RetNode = ReturnNodes[EN];
Chris Lattner7076ff22002-06-25 16:13:21 +00001656 RetNode->getInstList().insert(RetNode->end()--, Destroy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001657 }
1658 }
1659
Chris Lattner5da145b2002-04-13 19:52:54 +00001660 // Now that all of the pool descriptors have been created, link them together
1661 // so that called functions can get links as neccesary...
1662 //
1663 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1664 PoolInfo &PI = PoolDescs[Allocs[i]];
1665
1666 // For every pointer in the data structure, initialize a link that
1667 // indicates which pool to access...
1668 //
1669 vector<Value*> Indices(2);
1670 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1671 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1672 // Only store an entry for the field if the field is used!
1673 if (!PI.Node->getLink(l).empty()) {
1674 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1675 PointerVal PV = PI.Node->getLink(l)[0];
1676 assert(PV.Index == 0 && "Subindexing not supported yet!");
1677 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1678 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1679
1680 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1681 Indices));
1682 }
1683 }
1684
Chris Lattnere0618ca2002-03-29 05:50:20 +00001685 // Insert the entry node code into the entry block...
Chris Lattner7076ff22002-06-25 16:13:21 +00001686 F->getEntryNode().getInstList().insert(++F->getEntryNode().begin(),
Chris Lattnere0618ca2002-03-29 05:50:20 +00001687 EntryNodeInsts.begin(),
1688 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001689}
1690
1691
Chris Lattner441e16f2002-04-12 20:23:15 +00001692// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001693// module and update the Pool* instance variables to point to them.
1694//
Chris Lattner7076ff22002-06-25 16:13:21 +00001695void PoolAllocate::addPoolPrototypes(Module &M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001696 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001697 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001698 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001699 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001700 PoolInit = M.getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001701
Chris Lattnere0618ca2002-03-29 05:50:20 +00001702 // Get pooldestroy function...
1703 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001704 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001705 PoolDestroy = M.getOrInsertFunction("pooldestroy", PoolDestroyTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001706
Chris Lattnere0618ca2002-03-29 05:50:20 +00001707 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001708 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001709 PoolAlloc = M.getOrInsertFunction("poolalloc", PoolAllocTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001710
1711 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001712 Args.push_back(POINTERTYPE); // Pointer to free
1713 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001714 PoolFree = M.getOrInsertFunction("poolfree", PoolFreeTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001715
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001716 Args[0] = Type::UIntTy; // Number of slots to allocate
1717 FunctionType *PoolAllocArrayTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001718 PoolAllocArray = M.getOrInsertFunction("poolallocarray", PoolAllocArrayTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001719}
1720
1721
Chris Lattner7076ff22002-06-25 16:13:21 +00001722bool PoolAllocate::run(Module &M) {
Chris Lattner175f37c2002-03-29 03:40:59 +00001723 addPoolPrototypes(M);
Chris Lattner7076ff22002-06-25 16:13:21 +00001724 CurModule = &M;
Chris Lattner175f37c2002-03-29 03:40:59 +00001725
1726 DS = &getAnalysis<DataStructure>();
1727 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001728
Chris Lattner7076ff22002-06-25 16:13:21 +00001729 for (Module::iterator I = M.begin(); I != M.end(); ++I)
1730 if (!I->isExternal()) {
1731 Changed |= processFunction(I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001732 if (Changed) {
1733 cerr << "Only processing one function\n";
1734 break;
1735 }
1736 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001737
1738 CurModule = 0;
1739 DS = 0;
1740 return false;
1741}
1742
1743
1744// createPoolAllocatePass - Global function to access the functionality of this
1745// pass...
1746//
Chris Lattner64fd9352002-03-28 18:08:31 +00001747Pass *createPoolAllocatePass() { return new PoolAllocate(); }