blob: bf86403d86b7256b00deba0f6808aa62cb542265 [file] [log] [blame]
Chris Lattner64fd9352002-03-28 18:08:31 +00001//===-- PoolAllocate.cpp - Pool Allocation Pass ---------------------------===//
2//
3// This transform changes programs so that disjoint data structures are
4// allocated out of different pools of memory, increasing locality and shrinking
5// pointer size.
6//
7//===----------------------------------------------------------------------===//
8
Chris Lattnerd1fd7e92003-01-24 20:13:20 +00009#if 0
Chris Lattner99a53f62002-07-24 17:12:05 +000010#include "llvm/Transforms/IPO.h"
Chris Lattnerfb8ca4a2002-11-19 20:08:24 +000011#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner1a535e12002-10-10 20:33:46 +000012#include "llvm/Analysis/DataStructure.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000013#include "llvm/Module.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000014#include "llvm/iMemory.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000015#include "llvm/iTerminators.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000016#include "llvm/iPHINode.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000017#include "llvm/iOther.h"
Chris Lattner441e16f2002-04-12 20:23:15 +000018#include "llvm/DerivedTypes.h"
Chris Lattnerca142372002-04-28 19:55:58 +000019#include "llvm/Constants.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000020#include "llvm/Target/TargetData.h"
Chris Lattnerf32d65d2002-03-29 21:25:19 +000021#include "llvm/Support/InstVisitor.h"
Chris Lattner396d5d72002-03-30 04:02:31 +000022#include "Support/DepthFirstIterator.h"
Chris Lattnere0618ca2002-03-29 05:50:20 +000023#include "Support/STLExtras.h"
Chris Lattner175f37c2002-03-29 03:40:59 +000024#include <algorithm>
Anand Shukla2bc64192002-06-25 21:07:58 +000025using std::vector;
26using std::cerr;
27using std::map;
28using std::string;
29using std::set;
Chris Lattner64fd9352002-03-28 18:08:31 +000030
Chris Lattner441e16f2002-04-12 20:23:15 +000031// DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
32// creation phase in the top level function of a transformed data structure.
33//
Chris Lattneracf19022002-04-14 06:14:41 +000034//#define DEBUG_CREATE_POOLS 1
35
36// DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
37// the transformation is doing.
38//
39//#define DEBUG_TRANSFORM_PROGRESS 1
Chris Lattner441e16f2002-04-12 20:23:15 +000040
Chris Lattner457e1ac2002-04-15 22:42:23 +000041// DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
42// many static loads were eliminated from a function...
43//
44#define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
45
Chris Lattner50e3d322002-04-13 23:13:18 +000046#include "Support/CommandLine.h"
47enum PtrSize {
48 Ptr8bits, Ptr16bits, Ptr32bits
49};
50
Chris Lattnerf5cad152002-07-22 02:10:13 +000051static cl::opt<PtrSize>
52ReqPointerSize("poolalloc-ptr-size",
53 cl::desc("Set pointer size for -poolalloc pass"),
54 cl::values(
Chris Lattner50e3d322002-04-13 23:13:18 +000055 clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
56 clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
Chris Lattnerf5cad152002-07-22 02:10:13 +000057 clEnumValN(Ptr8bits , "8", "Use 8 bit indices for pointers"),
58 0));
Chris Lattner50e3d322002-04-13 23:13:18 +000059
Chris Lattnerf5cad152002-07-22 02:10:13 +000060static cl::opt<bool>
61DisableRLE("no-pool-load-elim", cl::Hidden,
62 cl::desc("Disable pool load elimination after poolalloc pass"));
Chris Lattner457e1ac2002-04-15 22:42:23 +000063
Chris Lattner441e16f2002-04-12 20:23:15 +000064const Type *POINTERTYPE;
Chris Lattner692ad5d2002-03-29 17:13:46 +000065
Chris Lattnere0618ca2002-03-29 05:50:20 +000066// FIXME: This is dependant on the sparc backend layout conventions!!
67static TargetData TargetData("test");
68
Chris Lattner50e3d322002-04-13 23:13:18 +000069static const Type *getPointerTransformedType(const Type *Ty) {
Chris Lattner7076ff22002-06-25 16:13:21 +000070 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000071 return POINTERTYPE;
Chris Lattner7076ff22002-06-25 16:13:21 +000072 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000073 vector<const Type *> NewElTypes;
74 NewElTypes.reserve(STy->getElementTypes().size());
75 for (StructType::ElementTypes::const_iterator
76 I = STy->getElementTypes().begin(),
77 E = STy->getElementTypes().end(); I != E; ++I)
78 NewElTypes.push_back(getPointerTransformedType(*I));
79 return StructType::get(NewElTypes);
Chris Lattner7076ff22002-06-25 16:13:21 +000080 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner50e3d322002-04-13 23:13:18 +000081 return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
82 ATy->getNumElements());
83 } else {
84 assert(Ty->isPrimitiveType() && "Unknown derived type!");
85 return Ty;
86 }
87}
88
Chris Lattner64fd9352002-03-28 18:08:31 +000089namespace {
Chris Lattner441e16f2002-04-12 20:23:15 +000090 struct PoolInfo {
91 DSNode *Node; // The node this pool allocation represents
92 Value *Handle; // LLVM value of the pool in the current context
93 const Type *NewType; // The transformed type of the memory objects
94 const Type *PoolType; // The type of the pool
95
96 const Type *getOldType() const { return Node->getType(); }
97
98 PoolInfo() { // Define a default ctor for map::operator[]
99 cerr << "Map subscript used to get element that doesn't exist!\n";
100 abort(); // Invalid
101 }
102
103 PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
104 : Node(N), Handle(H), NewType(NT), PoolType(PT) {
105 // Handle can be null...
106 assert(N && NT && PT && "Pool info null!");
107 }
108
109 PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
110 assert(N && "Invalid pool info!");
111
112 // The new type of the memory object is the same as the old type, except
113 // that all of the pointer values are replaced with POINTERTYPE values.
Chris Lattner50e3d322002-04-13 23:13:18 +0000114 NewType = getPointerTransformedType(getOldType());
Chris Lattner441e16f2002-04-12 20:23:15 +0000115 }
116 };
117
Chris Lattner692ad5d2002-03-29 17:13:46 +0000118 // ScalarInfo - Information about an LLVM value that we know points to some
119 // datastructure we are processing.
120 //
121 struct ScalarInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000122 Value *Val; // Scalar value in Current Function
Chris Lattner441e16f2002-04-12 20:23:15 +0000123 PoolInfo Pool; // The pool the scalar points into
Chris Lattner692ad5d2002-03-29 17:13:46 +0000124
Chris Lattner441e16f2002-04-12 20:23:15 +0000125 ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
126 assert(V && "Null value passed to ScalarInfo ctor!");
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000127 }
Chris Lattner692ad5d2002-03-29 17:13:46 +0000128 };
129
Chris Lattner396d5d72002-03-30 04:02:31 +0000130 // CallArgInfo - Information on one operand for a call that got expanded.
131 struct CallArgInfo {
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000132 int ArgNo; // Call argument number this corresponds to
133 DSNode *Node; // The graph node for the pool
134 Value *PoolHandle; // The LLVM value that is the pool pointer
Chris Lattner396d5d72002-03-30 04:02:31 +0000135
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000136 CallArgInfo(int Arg, DSNode *N, Value *PH)
137 : ArgNo(Arg), Node(N), PoolHandle(PH) {
138 assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
Chris Lattner396d5d72002-03-30 04:02:31 +0000139 }
140
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000141 // operator< when sorting, sort by argument number.
Chris Lattner396d5d72002-03-30 04:02:31 +0000142 bool operator<(const CallArgInfo &CAI) const {
143 return ArgNo < CAI.ArgNo;
144 }
145 };
146
Chris Lattner692ad5d2002-03-29 17:13:46 +0000147 // TransformFunctionInfo - Information about how a function eeds to be
148 // transformed.
149 //
150 struct TransformFunctionInfo {
151 // ArgInfo - Maintain information about the arguments that need to be
Chris Lattner441e16f2002-04-12 20:23:15 +0000152 // processed. Each CallArgInfo corresponds to an argument that needs to
153 // have a pool pointer passed into the transformed function with it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000154 //
155 // As a special case, "argument" number -1 corresponds to the return value.
156 //
Chris Lattner396d5d72002-03-30 04:02:31 +0000157 vector<CallArgInfo> ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000158
159 // Func - The function to be transformed...
160 Function *Func;
161
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000162 // The call instruction that is used to map CallArgInfo PoolHandle values
163 // into the new function values.
164 CallInst *Call;
165
Chris Lattner692ad5d2002-03-29 17:13:46 +0000166 // default ctor...
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000167 TransformFunctionInfo() : Func(0), Call(0) {}
Chris Lattner692ad5d2002-03-29 17:13:46 +0000168
Chris Lattner396d5d72002-03-30 04:02:31 +0000169 bool operator<(const TransformFunctionInfo &TFI) const {
Chris Lattner291a1b12002-03-29 19:05:48 +0000170 if (Func < TFI.Func) return true;
171 if (Func > TFI.Func) return false;
Chris Lattner291a1b12002-03-29 19:05:48 +0000172 if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
173 if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
Chris Lattner396d5d72002-03-30 04:02:31 +0000174 return ArgInfo < TFI.ArgInfo;
Chris Lattner692ad5d2002-03-29 17:13:46 +0000175 }
176
177 void finalizeConstruction() {
178 // Sort the vector so that the return value is first, followed by the
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000179 // argument records, in order. Note that this must be a stable sort so
180 // that the entries with the same sorting criteria (ie they are multiple
181 // pool entries for the same argument) are kept in depth first order.
Anand Shukla2bc64192002-06-25 21:07:58 +0000182 std::stable_sort(ArgInfo.begin(), ArgInfo.end());
Chris Lattner692ad5d2002-03-29 17:13:46 +0000183 }
Chris Lattner3e78dea2002-04-18 14:43:30 +0000184
185 // addCallInfo - For a specified function call CI, figure out which pool
186 // descriptors need to be passed in as arguments, and which arguments need
187 // to be transformed into indices. If Arg != -1, the specified call
188 // argument is passed in as a pointer to a data structure.
189 //
190 void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
191 DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
192
193 // Make sure that all dependant arguments are added to this transformation
194 // info. For example, if we call foo(null, P) and foo treats it's first and
195 // second arguments as belonging to the same data structure, the we MUST add
196 // entries to know that the null needs to be transformed into an index as
197 // well.
198 //
199 void ensureDependantArgumentsIncluded(DataStructure *DS,
200 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000201 };
202
203
204 // Define the pass class that we implement...
Chris Lattner441e16f2002-04-12 20:23:15 +0000205 struct PoolAllocate : public Pass {
Chris Lattner175f37c2002-03-29 03:40:59 +0000206 PoolAllocate() {
Chris Lattner50e3d322002-04-13 23:13:18 +0000207 switch (ReqPointerSize) {
208 case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
209 case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
210 case Ptr8bits: POINTERTYPE = Type::UByteTy; break;
211 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000212
213 CurModule = 0; DS = 0;
214 PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
Chris Lattner64fd9352002-03-28 18:08:31 +0000215 }
216
Chris Lattner441e16f2002-04-12 20:23:15 +0000217 // getPoolType - Get the type used by the backend for a pool of a particular
218 // type. This pool record is used to allocate nodes of type NodeType.
219 //
220 // Here, PoolTy = { NodeType*, sbyte*, uint }*
221 //
222 const StructType *getPoolType(const Type *NodeType) {
223 vector<const Type*> PoolElements;
224 PoolElements.push_back(PointerType::get(NodeType));
225 PoolElements.push_back(PointerType::get(Type::SByteTy));
226 PoolElements.push_back(Type::UIntTy);
Chris Lattner8f796d62002-04-13 19:25:57 +0000227 StructType *Result = StructType::get(PoolElements);
228
229 // Add a name to the symbol table to correspond to the backend
230 // representation of this pool...
231 assert(CurModule && "No current module!?");
232 string Name = CurModule->getTypeName(NodeType);
233 if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
234 CurModule->addTypeName(Name+"oolbe", Result);
235
236 return Result;
Chris Lattner441e16f2002-04-12 20:23:15 +0000237 }
238
Chris Lattner7076ff22002-06-25 16:13:21 +0000239 bool run(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000240
Chris Lattnerc8e66542002-04-27 06:56:12 +0000241 // getAnalysisUsage - This function requires data structure information
Chris Lattner175f37c2002-03-29 03:40:59 +0000242 // to be able to see what is pool allocatable.
Chris Lattner64fd9352002-03-28 18:08:31 +0000243 //
Chris Lattnerc8e66542002-04-27 06:56:12 +0000244 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf0ed55d2002-08-08 19:01:30 +0000245 AU.addRequired<DataStructure>();
Chris Lattner64fd9352002-03-28 18:08:31 +0000246 }
Chris Lattner175f37c2002-03-29 03:40:59 +0000247
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000248 public:
Chris Lattner175f37c2002-03-29 03:40:59 +0000249 // CurModule - The module being processed.
250 Module *CurModule;
251
252 // DS - The data structure graph for the module being processed.
253 DataStructure *DS;
254
255 // Prototypes that we add to support pool allocation...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000256 Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolAllocArray, *PoolFree;
Chris Lattner175f37c2002-03-29 03:40:59 +0000257
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000258 // The map of already transformed functions... note that the keys of this
259 // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
260 // of the ArgInfo elements.
261 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000262 map<TransformFunctionInfo, Function*> TransformedFunctions;
263
264 // getTransformedFunction - Get a transformed function, or return null if
265 // the function specified hasn't been transformed yet.
266 //
267 Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
268 map<TransformFunctionInfo, Function*>::const_iterator I =
269 TransformedFunctions.find(TFI);
270 if (I != TransformedFunctions.end()) return I->second;
271 return 0;
272 }
273
274
Chris Lattner441e16f2002-04-12 20:23:15 +0000275 // addPoolPrototypes - Add prototypes for the pool functions to the
276 // specified module and update the Pool* instance variables to point to
277 // them.
Chris Lattner175f37c2002-03-29 03:40:59 +0000278 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000279 void addPoolPrototypes(Module &M);
Chris Lattner175f37c2002-03-29 03:40:59 +0000280
Chris Lattner66df97d2002-03-29 06:21:38 +0000281
282 // CreatePools - Insert instructions into the function we are processing to
283 // create all of the memory pool objects themselves. This also inserts
284 // destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +0000285 // PoolDescs map.
Chris Lattner66df97d2002-03-29 06:21:38 +0000286 //
287 void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +0000288 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner66df97d2002-03-29 06:21:38 +0000289
Chris Lattner175f37c2002-03-29 03:40:59 +0000290 // processFunction - Convert a function to use pool allocation where
291 // available.
292 //
293 bool processFunction(Function *F);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000294
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000295 // transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +0000296 // pools specified in PoolDescs when modifying data structure nodes
297 // specified in the PoolDescs map. IPFGraph is the closed data structure
298 // graph for F, of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000299 //
300 void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +0000301 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000302
303 // transformFunction - Transform the specified function the specified way.
304 // It we have already transformed that function that way, don't do anything.
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000305 // The nodes in the TransformFunctionInfo come out of callers data structure
Chris Lattner441e16f2002-04-12 20:23:15 +0000306 // graph, and the PoolDescs passed in are the caller's.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000307 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000308 void transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +0000309 FunctionDSGraph &CallerIPGraph,
310 map<DSNode*, PoolInfo> &PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000311
Chris Lattner64fd9352002-03-28 18:08:31 +0000312 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000313
Chris Lattnera2c09852002-07-26 21:12:44 +0000314 RegisterOpt<PoolAllocate> X("poolalloc",
315 "Pool allocate disjoint datastructures");
Chris Lattner64fd9352002-03-28 18:08:31 +0000316}
317
Chris Lattner692ad5d2002-03-29 17:13:46 +0000318// isNotPoolableAlloc - This is a predicate that returns true if the specified
Chris Lattner175f37c2002-03-29 03:40:59 +0000319// allocation node in a data structure graph is eligable for pool allocation.
320//
321static bool isNotPoolableAlloc(const AllocDSNode *DS) {
Chris Lattnere0618ca2002-03-29 05:50:20 +0000322 if (DS->isAllocaNode()) return true; // Do not pool allocate alloca's.
Chris Lattnere0618ca2002-03-29 05:50:20 +0000323 return false;
Chris Lattner175f37c2002-03-29 03:40:59 +0000324}
325
Chris Lattner175f37c2002-03-29 03:40:59 +0000326// processFunction - Convert a function to use pool allocation where
327// available.
328//
329bool PoolAllocate::processFunction(Function *F) {
330 // Get the closed datastructure graph for the current function... if there are
331 // any allocations in this graph that are not escaping, we need to pool
332 // allocate them here!
333 //
334 FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
335
336 // Get all of the allocations that do not escape the current function. Since
337 // they are still live (they exist in the graph at all), this means we must
338 // have scalar references to these nodes, but the scalars are never returned.
339 //
Chris Lattner692ad5d2002-03-29 17:13:46 +0000340 vector<AllocDSNode*> Allocs;
Chris Lattner175f37c2002-03-29 03:40:59 +0000341 IPGraph.getNonEscapingAllocations(Allocs);
342
343 // Filter out allocations that we cannot handle. Currently, this includes
344 // variable sized array allocations and alloca's (which we do not want to
345 // pool allocate)
346 //
Anand Shukla2bc64192002-06-25 21:07:58 +0000347 Allocs.erase(std::remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
Chris Lattner175f37c2002-03-29 03:40:59 +0000348 Allocs.end());
349
350
351 if (Allocs.empty()) return false; // Nothing to do.
352
Chris Lattner3e78dea2002-04-18 14:43:30 +0000353#ifdef DEBUG_TRANSFORM_PROGRESS
354 cerr << "Transforming Function: " << F->getName() << "\n";
355#endif
356
Chris Lattner692ad5d2002-03-29 17:13:46 +0000357 // Insert instructions into the function we are processing to create all of
358 // the memory pool objects themselves. This also inserts destruction code.
Chris Lattner441e16f2002-04-12 20:23:15 +0000359 // This fills in the PoolDescs map to associate the alloc node with the
Chris Lattner396d5d72002-03-30 04:02:31 +0000360 // allocation of the memory pool corresponding to it.
Chris Lattner692ad5d2002-03-29 17:13:46 +0000361 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000362 map<DSNode*, PoolInfo> PoolDescs;
363 CreatePools(F, Allocs, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000364
Chris Lattneracf19022002-04-14 06:14:41 +0000365#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +0000366 cerr << "Transformed Entry Function: \n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +0000367#endif
Chris Lattner441e16f2002-04-12 20:23:15 +0000368
369 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +0000370 // how. To do this, we look at all of the scalars, seeing which functions are
371 // either used as a scalar value (so they return a data structure), or are
372 // passed one of our scalar values.
373 //
Chris Lattner441e16f2002-04-12 20:23:15 +0000374 transformFunctionBody(F, IPGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +0000375
376 return true;
377}
378
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000379
Chris Lattner441e16f2002-04-12 20:23:15 +0000380//===----------------------------------------------------------------------===//
381//
382// NewInstructionCreator - This class is used to traverse the function being
383// modified, changing each instruction visit'ed to use and provide pointer
384// indexes instead of real pointers. This is what changes the body of a
385// function to use pool allocation.
386//
387class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000388 PoolAllocate &PoolAllocator;
389 vector<ScalarInfo> &Scalars;
390 map<CallInst*, TransformFunctionInfo> &CallMap;
Chris Lattner441e16f2002-04-12 20:23:15 +0000391 map<Value*, Value*> &XFormMap; // Map old pointers to new indexes
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000392
Chris Lattner441e16f2002-04-12 20:23:15 +0000393 struct RefToUpdate {
394 Instruction *I; // Instruction to update
395 unsigned OpNum; // Operand number to update
396 Value *OldVal; // The old value it had
397
398 RefToUpdate(Instruction *i, unsigned o, Value *ov)
399 : I(i), OpNum(o), OldVal(ov) {}
400 };
401 vector<RefToUpdate> ReferencesToUpdate;
402
403 const ScalarInfo &getScalarRef(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000404 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
405 if (Scalars[i].Val == V) return Scalars[i];
Chris Lattner3e78dea2002-04-18 14:43:30 +0000406
407 cerr << "Could not find scalar " << V << " in scalar map!\n";
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000408 assert(0 && "Scalar not found in getScalar!");
409 abort();
410 return Scalars[0];
411 }
Chris Lattner441e16f2002-04-12 20:23:15 +0000412
413 const ScalarInfo *getScalar(const Value *V) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000414 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +0000415 if (Scalars[i].Val == V) return &Scalars[i];
416 return 0;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000417 }
418
Chris Lattner7076ff22002-06-25 16:13:21 +0000419 BasicBlock::iterator ReplaceInstWith(Instruction &I, Instruction *New) {
420 BasicBlock *BB = I.getParent();
421 BasicBlock::iterator RI = &I;
422 BB->getInstList().remove(RI);
423 BB->getInstList().insert(RI, New);
424 XFormMap[&I] = New;
425 return New;
Chris Lattner441e16f2002-04-12 20:23:15 +0000426 }
427
Chris Lattner39db8712002-05-02 17:38:14 +0000428 Instruction *createPoolBaseInstruction(Value *PtrVal) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000429 const ScalarInfo &SC = getScalarRef(PtrVal);
430 vector<Value*> Args(3);
431 Args[0] = ConstantUInt::get(Type::UIntTy, 0); // No pointer offset
432 Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
433 Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
Chris Lattner39db8712002-05-02 17:38:14 +0000434 return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
Chris Lattner441e16f2002-04-12 20:23:15 +0000435 }
436
437
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000438public:
Chris Lattner441e16f2002-04-12 20:23:15 +0000439 NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
440 map<CallInst*, TransformFunctionInfo> &C,
441 map<Value*, Value*> &X)
442 : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000443
Chris Lattner441e16f2002-04-12 20:23:15 +0000444
445 // updateReferences - The NewInstructionCreator is responsible for creating
446 // new instructions to replace the old ones in the function, and then link up
447 // references to values to their new values. For it to do this, however, it
448 // keeps track of information about the value mapping of old values to new
449 // values that need to be patched up. Given this value map and a set of
450 // instruction operands to patch, updateReferences performs the updates.
451 //
452 void updateReferences() {
453 for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
454 RefToUpdate &Ref = ReferencesToUpdate[i];
455 Value *NewVal = XFormMap[Ref.OldVal];
456
457 if (NewVal == 0) {
458 if (isa<Constant>(Ref.OldVal) && // Refering to a null ptr?
459 cast<Constant>(Ref.OldVal)->isNullValue()) {
460 // Transform the null pointer into a null index... caching in XFormMap
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000461 XFormMap[Ref.OldVal] = NewVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000462 //} else if (isa<Argument>(Ref.OldVal)) {
463 } else {
464 cerr << "Unknown reference to: " << Ref.OldVal << "\n";
465 assert(XFormMap[Ref.OldVal] &&
466 "Reference to value that was not updated found!");
467 }
468 }
469
470 Ref.I->setOperand(Ref.OpNum, NewVal);
471 }
472 ReferencesToUpdate.clear();
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000473 }
474
Chris Lattner441e16f2002-04-12 20:23:15 +0000475 //===--------------------------------------------------------------------===//
476 // Transformation methods:
477 // These methods specify how each type of instruction is transformed by the
478 // NewInstructionCreator instance...
479 //===--------------------------------------------------------------------===//
480
Chris Lattner7076ff22002-06-25 16:13:21 +0000481 void visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000482 assert(0 && "Cannot transform get element ptr instructions yet!");
483 }
484
485 // Replace the load instruction with a new one.
Chris Lattner7076ff22002-06-25 16:13:21 +0000486 void visitLoadInst(LoadInst &I) {
Chris Lattner39db8712002-05-02 17:38:14 +0000487 vector<Instruction *> BeforeInsts;
Chris Lattner441e16f2002-04-12 20:23:15 +0000488
489 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000490 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000491 Type::UIntTy, I.getOperand(0)->getName());
Chris Lattner39db8712002-05-02 17:38:14 +0000492 BeforeInsts.push_back(Index);
Chris Lattner7076ff22002-06-25 16:13:21 +0000493 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(0)));
Chris Lattner39db8712002-05-02 17:38:14 +0000494
495 // Include the pool base instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000496 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(0));
Chris Lattner39db8712002-05-02 17:38:14 +0000497 BeforeInsts.push_back(PoolBase);
498
499 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000500 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index,
501 I.getName()+".idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000502 BeforeInsts.push_back(IdxInst);
Chris Lattner441e16f2002-04-12 20:23:15 +0000503
Chris Lattner7076ff22002-06-25 16:13:21 +0000504 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000505 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000506 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000507 I.getName()+".addr");
Chris Lattner39db8712002-05-02 17:38:14 +0000508 BeforeInsts.push_back(Address);
509
Chris Lattner7076ff22002-06-25 16:13:21 +0000510 Instruction *NewLoad = new LoadInst(Address, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000511
512 // Replace the load instruction with the new load instruction...
513 BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
514
Chris Lattner39db8712002-05-02 17:38:14 +0000515 // Add all of the instructions before the load...
516 NewLoad->getParent()->getInstList().insert(II, BeforeInsts.begin(),
517 BeforeInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000518
519 // If not yielding a pool allocated pointer, use the new load value as the
520 // value in the program instead of the old load value...
521 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000522 if (!getScalar(&I))
523 I.replaceAllUsesWith(NewLoad);
Chris Lattner441e16f2002-04-12 20:23:15 +0000524 }
525
526 // Replace the store instruction with a new one. In the store instruction,
527 // the value stored could be a pointer type, meaning that the new store may
528 // have to change one or both of it's operands.
529 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000530 void visitStoreInst(StoreInst &I) {
531 assert(getScalar(I.getOperand(1)) &&
Chris Lattner441e16f2002-04-12 20:23:15 +0000532 "Store inst found only storing pool allocated pointer. "
533 "Not imp yet!");
534
Chris Lattner7076ff22002-06-25 16:13:21 +0000535 Value *Val = I.getOperand(0); // The value to store...
Chris Lattner39db8712002-05-02 17:38:14 +0000536
Chris Lattner441e16f2002-04-12 20:23:15 +0000537 // Check to see if the value we are storing is a data structure pointer...
Chris Lattner7076ff22002-06-25 16:13:21 +0000538 //if (const ScalarInfo *ValScalar = getScalar(I.getOperand(0)))
539 if (isa<PointerType>(I.getOperand(0)->getType()))
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000540 Val = Constant::getNullValue(POINTERTYPE); // Yes, store a dummy
Chris Lattner441e16f2002-04-12 20:23:15 +0000541
Chris Lattner7076ff22002-06-25 16:13:21 +0000542 Instruction *PoolBase = createPoolBaseInstruction(I.getOperand(1));
Chris Lattner441e16f2002-04-12 20:23:15 +0000543
544 // Cast our index to be a UIntTy so we can use it to index into the pool...
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000545 CastInst *Index = new CastInst(Constant::getNullValue(POINTERTYPE),
Chris Lattner7076ff22002-06-25 16:13:21 +0000546 Type::UIntTy, I.getOperand(1)->getName());
547 ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000548
Chris Lattner39db8712002-05-02 17:38:14 +0000549 // Instructions to add after the Index...
550 vector<Instruction*> AfterInsts;
551
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000552 Instruction *IdxInst =
Chris Lattner7076ff22002-06-25 16:13:21 +0000553 BinaryOperator::create(Instruction::Add, *I.idx_begin(), Index, "idx");
Chris Lattner39db8712002-05-02 17:38:14 +0000554 AfterInsts.push_back(IdxInst);
555
Chris Lattner7076ff22002-06-25 16:13:21 +0000556 vector<Value*> Indices(I.idx_begin(), I.idx_end());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000557 Indices[0] = IdxInst;
Chris Lattner39db8712002-05-02 17:38:14 +0000558 Instruction *Address = new GetElementPtrInst(PoolBase, Indices,
Chris Lattner7076ff22002-06-25 16:13:21 +0000559 I.getName()+"storeaddr");
Chris Lattner39db8712002-05-02 17:38:14 +0000560 AfterInsts.push_back(Address);
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000561
Chris Lattner39db8712002-05-02 17:38:14 +0000562 Instruction *NewStore = new StoreInst(Val, Address);
563 AfterInsts.push_back(NewStore);
Chris Lattner7076ff22002-06-25 16:13:21 +0000564 if (Val != I.getOperand(0)) // Value stored was a pointer?
565 ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I.getOperand(0)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000566
567
568 // Replace the store instruction with the cast instruction...
569 BasicBlock::iterator II = ReplaceInstWith(I, Index);
570
571 // Add the pool base calculator instruction before the index...
Chris Lattner7076ff22002-06-25 16:13:21 +0000572 II = ++Index->getParent()->getInstList().insert(II, PoolBase);
573 ++II;
Chris Lattner441e16f2002-04-12 20:23:15 +0000574
Chris Lattner39db8712002-05-02 17:38:14 +0000575 // Add the instructions that go after the index...
576 Index->getParent()->getInstList().insert(II, AfterInsts.begin(),
577 AfterInsts.end());
Chris Lattner441e16f2002-04-12 20:23:15 +0000578 }
579
580
581 // Create call to poolalloc for every malloc instruction
Chris Lattner7076ff22002-06-25 16:13:21 +0000582 void visitMallocInst(MallocInst &I) {
583 const ScalarInfo &SCI = getScalarRef(&I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000584 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000585
586 CallInst *Call;
Chris Lattner7076ff22002-06-25 16:13:21 +0000587 if (!I.isArrayAllocation()) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000588 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000589 Call = new CallInst(PoolAllocator.PoolAlloc, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000590 } else {
Chris Lattner7076ff22002-06-25 16:13:21 +0000591 Args.push_back(I.getArraySize());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000592 Args.push_back(SCI.Pool.Handle);
Chris Lattner7076ff22002-06-25 16:13:21 +0000593 Call = new CallInst(PoolAllocator.PoolAllocArray, Args, I.getName());
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000594 }
595
Chris Lattner441e16f2002-04-12 20:23:15 +0000596 ReplaceInstWith(I, Call);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000597 }
598
Chris Lattner441e16f2002-04-12 20:23:15 +0000599 // Convert a call to poolfree for every free instruction...
Chris Lattner7076ff22002-06-25 16:13:21 +0000600 void visitFreeInst(FreeInst &I) {
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000601 // Create a new call to poolfree before the free instruction
602 vector<Value*> Args;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000603 Args.push_back(Constant::getNullValue(POINTERTYPE));
Chris Lattner7076ff22002-06-25 16:13:21 +0000604 Args.push_back(getScalarRef(I.getOperand(0)).Pool.Handle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000605 Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
606 ReplaceInstWith(I, NewCall);
Chris Lattner7076ff22002-06-25 16:13:21 +0000607 ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I.getOperand(0)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000608 }
609
610 // visitCallInst - Create a new call instruction with the extra arguments for
611 // all of the memory pools that the call needs.
612 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000613 void visitCallInst(CallInst &I) {
614 TransformFunctionInfo &TI = CallMap[&I];
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000615
616 // Start with all of the old arguments...
Chris Lattner7076ff22002-06-25 16:13:21 +0000617 vector<Value*> Args(I.op_begin()+1, I.op_end());
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000618
Chris Lattner441e16f2002-04-12 20:23:15 +0000619 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
620 // Replace all of the pointer arguments with our new pointer typed values.
621 if (TI.ArgInfo[i].ArgNo != -1)
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000622 Args[TI.ArgInfo[i].ArgNo] = Constant::getNullValue(POINTERTYPE);
Chris Lattner441e16f2002-04-12 20:23:15 +0000623
624 // Add all of the pool arguments...
Chris Lattner396d5d72002-03-30 04:02:31 +0000625 Args.push_back(TI.ArgInfo[i].PoolHandle);
Chris Lattner441e16f2002-04-12 20:23:15 +0000626 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000627
628 Function *NF = PoolAllocator.getTransformedFunction(TI);
Chris Lattner7076ff22002-06-25 16:13:21 +0000629 Instruction *NewCall = new CallInst(NF, Args, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000630 ReplaceInstWith(I, NewCall);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000631
Chris Lattner441e16f2002-04-12 20:23:15 +0000632 // Keep track of the mapping of operands so that we can resolve them to real
633 // values later.
634 Value *RetVal = NewCall;
635 for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
636 if (TI.ArgInfo[i].ArgNo != -1)
637 ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
Chris Lattner7076ff22002-06-25 16:13:21 +0000638 I.getOperand(TI.ArgInfo[i].ArgNo+1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000639 else
640 RetVal = 0; // If returning a pointer, don't change retval...
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000641
Chris Lattner441e16f2002-04-12 20:23:15 +0000642 // If not returning a pointer, use the new call as the value in the program
643 // instead of the old call...
644 //
645 if (RetVal)
Chris Lattner7076ff22002-06-25 16:13:21 +0000646 I.replaceAllUsesWith(RetVal);
Chris Lattner441e16f2002-04-12 20:23:15 +0000647 }
648
649 // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
650 // nodes...
651 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000652 void visitPHINode(PHINode &PN) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000653 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000654 PHINode *NewPhi = new PHINode(POINTERTYPE, PN.getName());
655 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
656 NewPhi->addIncoming(DummyVal, PN.getIncomingBlock(i));
Chris Lattner441e16f2002-04-12 20:23:15 +0000657 ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2,
Chris Lattner7076ff22002-06-25 16:13:21 +0000658 PN.getIncomingValue(i)));
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000659 }
660
Chris Lattner441e16f2002-04-12 20:23:15 +0000661 ReplaceInstWith(PN, NewPhi);
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000662 }
663
Chris Lattner441e16f2002-04-12 20:23:15 +0000664 // visitReturnInst - Replace ret instruction with a new return...
Chris Lattner7076ff22002-06-25 16:13:21 +0000665 void visitReturnInst(ReturnInst &I) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000666 Instruction *Ret = new ReturnInst(Constant::getNullValue(POINTERTYPE));
Chris Lattner441e16f2002-04-12 20:23:15 +0000667 ReplaceInstWith(I, Ret);
Chris Lattner7076ff22002-06-25 16:13:21 +0000668 ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I.getOperand(0)));
Chris Lattner847b6e22002-03-30 20:53:14 +0000669 }
670
Chris Lattner441e16f2002-04-12 20:23:15 +0000671 // visitSetCondInst - Replace a conditional test instruction with a new one
Chris Lattner7076ff22002-06-25 16:13:21 +0000672 void visitSetCondInst(SetCondInst &SCI) {
673 BinaryOperator &I = (BinaryOperator&)SCI;
Chris Lattner0e0c15b2002-04-27 02:29:32 +0000674 Value *DummyVal = Constant::getNullValue(POINTERTYPE);
Chris Lattner7076ff22002-06-25 16:13:21 +0000675 BinaryOperator *New = BinaryOperator::create(I.getOpcode(), DummyVal,
676 DummyVal, I.getName());
Chris Lattner441e16f2002-04-12 20:23:15 +0000677 ReplaceInstWith(I, New);
678
Chris Lattner7076ff22002-06-25 16:13:21 +0000679 ReferencesToUpdate.push_back(RefToUpdate(New, 0, I.getOperand(0)));
680 ReferencesToUpdate.push_back(RefToUpdate(New, 1, I.getOperand(1)));
Chris Lattner441e16f2002-04-12 20:23:15 +0000681
682 // Make sure branches refer to the new condition...
Chris Lattner7076ff22002-06-25 16:13:21 +0000683 I.replaceAllUsesWith(New);
Chris Lattnercf09a2a2002-04-01 00:45:33 +0000684 }
685
Chris Lattner7076ff22002-06-25 16:13:21 +0000686 void visitInstruction(Instruction &I) {
Chris Lattner441e16f2002-04-12 20:23:15 +0000687 cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000688 }
Chris Lattnerf32d65d2002-03-29 21:25:19 +0000689};
690
691
Chris Lattner457e1ac2002-04-15 22:42:23 +0000692// PoolBaseLoadEliminator - Every load and store through a pool allocated
693// pointer causes a load of the real pool base out of the pool descriptor.
694// Iterate through the function, doing a local elimination pass of duplicate
695// loads. This attempts to turn the all too common:
696//
697// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
698// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
699// %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
700// store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
701//
702// into:
703// %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
704// %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
705// store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
706//
707//
708class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
709 // PoolDescValues - Keep track of the values in the current function that are
710 // pool descriptors (loads from which we want to eliminate).
711 //
712 vector<Value*> PoolDescValues;
713
714 // PoolDescMap - As we are analyzing a BB, keep track of which load to use
715 // when referencing a pool descriptor.
716 //
717 map<Value*, LoadInst*> PoolDescMap;
718
719 // These two fields keep track of statistics of how effective we are, if
720 // debugging is enabled.
721 //
722 unsigned Eliminated, Remaining;
723public:
724 // Compact the pool descriptor map into a list of the pool descriptors in the
725 // current context that we should know about...
726 //
727 PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
728 Eliminated = Remaining = 0;
729 for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
730 E = PoolDescs.end(); I != E; ++I)
731 PoolDescValues.push_back(I->second.Handle);
732
733 // Remove duplicates from the list of pool values
734 sort(PoolDescValues.begin(), PoolDescValues.end());
735 PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
736 PoolDescValues.end());
737 }
738
739#ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
Chris Lattner7076ff22002-06-25 16:13:21 +0000740 void visitFunction(Function &F) {
741 cerr << "Pool Load Elim '" << F.getName() << "'\t";
Chris Lattner457e1ac2002-04-15 22:42:23 +0000742 }
743 ~PoolBaseLoadEliminator() {
744 unsigned Total = Eliminated+Remaining;
745 if (Total)
746 cerr << "removed " << Eliminated << "["
747 << Eliminated*100/Total << "%] loads, leaving "
748 << Remaining << ".\n";
749 }
750#endif
751
752 // Loop over the function, looking for loads to eliminate. Because we are a
753 // local transformation, we reset all of our state when we enter a new basic
754 // block.
755 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000756 void visitBasicBlock(BasicBlock &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000757 PoolDescMap.clear(); // Forget state.
758 }
759
760 // Starting with an empty basic block, we scan it looking for loads of the
761 // pool descriptor. When we find a load, we add it to the PoolDescMap,
762 // indicating that we have a value available to recycle next time we see the
763 // poolbase of this instruction being loaded.
764 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000765 void visitLoadInst(LoadInst &LI) {
766 Value *LoadAddr = LI.getPointerOperand();
Chris Lattner457e1ac2002-04-15 22:42:23 +0000767 map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
768 if (VIt != PoolDescMap.end()) { // We already have a value for this load?
Chris Lattner7076ff22002-06-25 16:13:21 +0000769 LI.replaceAllUsesWith(VIt->second); // Make the current load dead
Chris Lattner457e1ac2002-04-15 22:42:23 +0000770 ++Eliminated;
771 } else {
772 // This load might not be a load of a pool pointer, check to see if it is
Chris Lattner7076ff22002-06-25 16:13:21 +0000773 if (LI.getNumOperands() == 4 && // load pool, uint 0, ubyte 0, ubyte 0
Chris Lattner457e1ac2002-04-15 22:42:23 +0000774 find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
775 PoolDescValues.end()) {
776
777 assert("Make sure it's a load of the pool base, not a chaining field" &&
Chris Lattner7076ff22002-06-25 16:13:21 +0000778 LI.getOperand(1) == Constant::getNullValue(Type::UIntTy) &&
779 LI.getOperand(2) == Constant::getNullValue(Type::UByteTy) &&
780 LI.getOperand(3) == Constant::getNullValue(Type::UByteTy));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000781
782 // If it is a load of a pool base, keep track of it for future reference
Anand Shukla2bc64192002-06-25 21:07:58 +0000783 PoolDescMap.insert(std::make_pair(LoadAddr, &LI));
Chris Lattner457e1ac2002-04-15 22:42:23 +0000784 ++Remaining;
785 }
786 }
787 }
788
789 // If we run across a function call, forget all state... Calls to
790 // poolalloc/poolfree can invalidate the pool base pointer, so it should be
791 // reloaded the next time it is used. Furthermore, a call to a random
792 // function might call one of these functions, so be conservative. Through
793 // more analysis, this could be improved in the future.
794 //
Chris Lattner7076ff22002-06-25 16:13:21 +0000795 void visitCallInst(CallInst &) {
Chris Lattner457e1ac2002-04-15 22:42:23 +0000796 PoolDescMap.clear();
797 }
798};
799
Chris Lattner3e78dea2002-04-18 14:43:30 +0000800static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
801 map<DSNode*, PointerValSet> &NodeMapping) {
802 for (unsigned i = 0, e = PVS.size(); i != e; ++i)
803 if (NodeMapping[SrcNode].add(PVS[i])) { // Not in map yet?
804 assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
805 DSNode *DestNode = PVS[i].Node;
806
807 // Loop over all of the outgoing links in the mapped graph
808 for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
809 PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
810 const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
811
812 // Add all of the node mappings now!
813 for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
814 assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
815 addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
816 }
817 }
818 }
819}
820
821// CalculateNodeMapping - There is a partial isomorphism between the graph
822// passed in and the graph that is actually used by the function. We need to
823// figure out what this mapping is so that we can transformFunctionBody the
824// instructions in the function itself. Note that every node in the graph that
825// we are interested in must be both in the local graph of the called function,
826// and in the local graph of the calling function. Because of this, we only
827// define the mapping for these nodes [conveniently these are the only nodes we
828// CAN define a mapping for...]
829//
830// The roots of the graph that we are transforming is rooted in the arguments
831// passed into the function from the caller. This is where we start our
832// mapping calculation.
833//
834// The NodeMapping calculated maps from the callers graph to the called graph.
835//
836static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
837 FunctionDSGraph &CallerGraph,
838 FunctionDSGraph &CalledGraph,
839 map<DSNode*, PointerValSet> &NodeMapping) {
840 int LastArgNo = -2;
841 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
842 // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
843 // corresponds to...
844 //
845 // Only consider first node of sequence. Extra nodes may may be added
846 // to the TFI if the data structure requires more nodes than just the
847 // one the argument points to. We are only interested in the one the
848 // argument points to though.
849 //
850 if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
851 if (TFI.ArgInfo[i].ArgNo == -1) {
852 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
853 NodeMapping);
854 } else {
855 // Figure out which node argument # ArgNo points to in the called graph.
Chris Lattner7076ff22002-06-25 16:13:21 +0000856 Function::aiterator AI = F->abegin();
857 std::advance(AI, TFI.ArgInfo[i].ArgNo);
858 addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[AI],
Chris Lattner3e78dea2002-04-18 14:43:30 +0000859 NodeMapping);
860 }
861 LastArgNo = TFI.ArgInfo[i].ArgNo;
862 }
863 }
864}
Chris Lattner441e16f2002-04-12 20:23:15 +0000865
866
Chris Lattner3e78dea2002-04-18 14:43:30 +0000867
868
869// addCallInfo - For a specified function call CI, figure out which pool
870// descriptors need to be passed in as arguments, and which arguments need to be
871// transformed into indices. If Arg != -1, the specified call argument is
872// passed in as a pointer to a data structure.
873//
874void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
875 int Arg, DSNode *GraphNode,
876 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattner0dc225c2002-03-31 07:17:46 +0000877 assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000878 assert(Func == 0 || Func == CI->getCalledFunction() &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000879 "Function call record should always call the same function!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000880 assert(Call == 0 || Call == CI &&
Chris Lattner0dc225c2002-03-31 07:17:46 +0000881 "Call element already filled in with different value!");
Chris Lattner3e78dea2002-04-18 14:43:30 +0000882 Func = CI->getCalledFunction();
883 Call = CI;
884 //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
Chris Lattner396d5d72002-03-30 04:02:31 +0000885
886 // For now, add the entire graph that is pointed to by the call argument.
887 // This graph can and should be pruned to only what the function itself will
888 // use, because often this will be a dramatically smaller subset of what we
889 // are providing.
890 //
Chris Lattner3e78dea2002-04-18 14:43:30 +0000891 // FIXME: This should use pool links instead of extra arguments!
892 //
Chris Lattnerca9f4d32002-03-30 09:12:35 +0000893 for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
Chris Lattner441e16f2002-04-12 20:23:15 +0000894 I != E; ++I)
Chris Lattner3e78dea2002-04-18 14:43:30 +0000895 ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
896}
897
898static void markReachableNodes(const PointerValSet &Vals,
899 set<DSNode*> &ReachableNodes) {
900 for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
901 DSNode *N = Vals[n].Node;
902 if (ReachableNodes.count(N) == 0) // Haven't already processed node?
903 ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
904 }
905}
906
907// Make sure that all dependant arguments are added to this transformation info.
908// For example, if we call foo(null, P) and foo treats it's first and second
909// arguments as belonging to the same data structure, the we MUST add entries to
910// know that the null needs to be transformed into an index as well.
911//
912void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
913 map<DSNode*, PoolInfo> &PoolDescs) {
914 // FIXME: This does not work for indirect function calls!!!
915 if (Func == 0) return; // FIXME!
916
917 // Make sure argument entries are sorted.
918 finalizeConstruction();
919
920 // Loop over the function signature, checking to see if there are any pointer
921 // arguments that we do not convert... if there is something we haven't
922 // converted, set done to false.
923 //
924 unsigned PtrNo = 0;
925 bool Done = true;
926 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
927 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
928 // We DO transform the ret val... skip all possible entries for retval
929 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
930 PtrNo++;
931 } else {
932 Done = false;
933 }
934
Chris Lattner7076ff22002-06-25 16:13:21 +0000935 unsigned i = 0;
936 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I,++i){
937 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +0000938 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
939 // We DO transform this arg... skip all possible entries for argument
940 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
941 PtrNo++;
942 } else {
943 Done = false;
944 break;
945 }
946 }
947 }
948
949 // If we already have entries for all pointer arguments and retvals, there
950 // certainly is no work to do. Bail out early to avoid building relatively
951 // expensive data structures.
952 //
953 if (Done) return;
954
955#ifdef DEBUG_TRANSFORM_PROGRESS
956 cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
957#endif
958
959 // Otherwise, we MIGHT have to add the arguments/retval if they are part of
960 // the same datastructure graph as some other argument or retval that we ARE
961 // processing.
962 //
963 // Get the data structure graph for the called function.
964 //
965 FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
966
967 // Build a mapping between the nodes in our current graph and the nodes in the
968 // called function's graph. We build it based on our _incomplete_
969 // transformation information, because it contains all of the info that we
970 // should need.
971 //
972 map<DSNode*, PointerValSet> NodeMapping;
973 CalculateNodeMapping(Func, *this,
974 DS->getClosedDSGraph(Call->getParent()->getParent()),
975 CalledDS, NodeMapping);
976
977 // Build the inverted version of the node mapping, that maps from a node in
978 // the called functions graph to a single node in the caller graph.
979 //
980 map<DSNode*, DSNode*> InverseNodeMap;
981 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
982 E = NodeMapping.end(); I != E; ++I) {
983 PointerValSet &CalledNodes = I->second;
984 for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
985 InverseNodeMap[CalledNodes[i].Node] = I->first;
986 }
987 NodeMapping.clear(); // Done with information, free memory
988
989 // Build a set of reachable nodes from the arguments/retval that we ARE
990 // passing in...
991 set<DSNode*> ReachableNodes;
992
993 // Loop through all of the arguments, marking all of the reachable data
994 // structure nodes reachable if they are from this pointer...
995 //
996 for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
997 if (ArgInfo[i].ArgNo == -1) {
998 if (i == 0) // Only process retvals once (performance opt)
999 markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
1000 } else { // If it's an argument value...
Chris Lattner7076ff22002-06-25 16:13:21 +00001001 Function::aiterator AI = Func->abegin();
1002 std::advance(AI, ArgInfo[i].ArgNo);
1003 if (isa<PointerType>(AI->getType()))
1004 markReachableNodes(CalledDS.getValueMap()[AI], ReachableNodes);
Chris Lattner3e78dea2002-04-18 14:43:30 +00001005 }
1006 }
1007
1008 // Now that we know which nodes are already reachable, see if any of the
1009 // arguments that we are not passing values in for can reach one of the
1010 // existing nodes...
1011 //
1012
1013 // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
1014 // nodes we know about. The problem is that if we do this, then I don't know
1015 // how to get pool pointers for this head list. Since we are completely
1016 // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
1017 //
1018
1019 PtrNo = 0;
1020 if (isa<PointerType>(Func->getReturnType())) // Make sure we convert retval
1021 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
1022 // We DO transform the ret val... skip all possible entries for retval
1023 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
1024 PtrNo++;
1025 } else {
1026 // See what the return value points to...
1027
1028 // FIXME: This should generalize to any number of nodes, just see if any
1029 // are reachable.
1030 assert(CalledDS.getRetNodes().size() == 1 &&
1031 "Assumes only one node is returned");
1032 DSNode *N = CalledDS.getRetNodes()[0].Node;
1033
1034 // If the return value is not marked as being passed in, but it NEEDS to
1035 // be transformed, then make it known now.
1036 //
1037 if (ReachableNodes.count(N)) {
1038#ifdef DEBUG_TRANSFORM_PROGRESS
1039 cerr << "ensure dependant arguments adds return value entry!\n";
1040#endif
1041 addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1042
1043 // Keep sorted!
1044 finalizeConstruction();
1045 }
1046 }
1047
Chris Lattner7076ff22002-06-25 16:13:21 +00001048 i = 0;
1049 for (Function::aiterator I = Func->abegin(), E = Func->aend(); I!=E; ++I, ++i)
1050 if (isa<PointerType>(I->getType())) {
Chris Lattner3e78dea2002-04-18 14:43:30 +00001051 if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1052 // We DO transform this arg... skip all possible entries for argument
1053 while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1054 PtrNo++;
1055 } else {
1056 // This should generalize to any number of nodes, just see if any are
1057 // reachable.
Chris Lattner7076ff22002-06-25 16:13:21 +00001058 assert(CalledDS.getValueMap()[I].size() == 1 &&
Chris Lattner3e78dea2002-04-18 14:43:30 +00001059 "Only handle case where pointing to one node so far!");
1060
1061 // If the arg is not marked as being passed in, but it NEEDS to
1062 // be transformed, then make it known now.
1063 //
Chris Lattner7076ff22002-06-25 16:13:21 +00001064 DSNode *N = CalledDS.getValueMap()[I][0].Node;
Chris Lattner3e78dea2002-04-18 14:43:30 +00001065 if (ReachableNodes.count(N)) {
1066#ifdef DEBUG_TRANSFORM_PROGRESS
1067 cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1068#endif
1069 addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1070
1071 // Keep sorted!
1072 finalizeConstruction();
1073 }
1074 }
1075 }
Chris Lattner396d5d72002-03-30 04:02:31 +00001076}
1077
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001078
1079// transformFunctionBody - This transforms the instruction in 'F' to use the
Chris Lattner441e16f2002-04-12 20:23:15 +00001080// pools specified in PoolDescs when modifying data structure nodes specified in
1081// the PoolDescs map. Specifically, scalar values specified in the Scalars
1082// vector must be remapped. IPFGraph is the closed data structure graph for F,
1083// of which the PoolDescriptor nodes come from.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001084//
1085void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
Chris Lattner441e16f2002-04-12 20:23:15 +00001086 map<DSNode*, PoolInfo> &PoolDescs) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001087
1088 // Loop through the value map looking for scalars that refer to nonescaping
1089 // allocations. Add them to the Scalars vector. Note that we may have
1090 // multiple entries in the Scalars vector for each value if it points to more
1091 // than one object.
1092 //
1093 map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1094 vector<ScalarInfo> Scalars;
1095
Chris Lattneracf19022002-04-14 06:14:41 +00001096#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001097 cerr << "Building scalar map for fn '" << F->getName() << "' body:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001098#endif
Chris Lattner847b6e22002-03-30 20:53:14 +00001099
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001100 for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1101 E = ValMap.end(); I != E; ++I) {
1102 const PointerValSet &PVS = I->second; // Set of things pointed to by scalar
1103
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001104 // Check to see if the scalar points to a data structure node...
1105 for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001106 if (PVS[i].Index) { cerr << "Problem in " << F->getName() << " for " << I->first << "\n"; }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001107 assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1108
1109 // If the allocation is in the nonescaping set...
Chris Lattner441e16f2002-04-12 20:23:15 +00001110 map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1111 if (AI != PoolDescs.end()) { // Add it to the list of scalars
1112 Scalars.push_back(ScalarInfo(I->first, AI->second));
Chris Lattneracf19022002-04-14 06:14:41 +00001113#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001114 cerr << "\nScalar Mapping from:" << I->first
1115 << "Scalar Mapping to: "; PVS.print(cerr);
Chris Lattneracf19022002-04-14 06:14:41 +00001116#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001117 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001118 }
1119 }
1120
Chris Lattneracf19022002-04-14 06:14:41 +00001121#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001122 cerr << "\nIn '" << F->getName()
Chris Lattner175f37c2002-03-29 03:40:59 +00001123 << "': Found the following values that point to poolable nodes:\n";
1124
1125 for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
Chris Lattner441e16f2002-04-12 20:23:15 +00001126 cerr << Scalars[i].Val;
1127 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001128#endif
Chris Lattnere0618ca2002-03-29 05:50:20 +00001129
Chris Lattner692ad5d2002-03-29 17:13:46 +00001130 // CallMap - Contain an entry for every call instruction that needs to be
1131 // transformed. Each entry in the map contains information about what we need
1132 // to do to each call site to change it to work.
1133 //
1134 map<CallInst*, TransformFunctionInfo> CallMap;
Chris Lattner66df97d2002-03-29 06:21:38 +00001135
Chris Lattner441e16f2002-04-12 20:23:15 +00001136 // Now we need to figure out what called functions we need to transform, and
Chris Lattner692ad5d2002-03-29 17:13:46 +00001137 // how. To do this, we look at all of the scalars, seeing which functions are
1138 // either used as a scalar value (so they return a data structure), or are
1139 // passed one of our scalar values.
1140 //
1141 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1142 Value *ScalarVal = Scalars[i].Val;
1143
1144 // Check to see if the scalar _IS_ a call...
1145 if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1146 // If so, add information about the pool it will be returning...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001147 CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001148
1149 // Check to see if the scalar is an operand to a call...
1150 for (Value::use_iterator UI = ScalarVal->use_begin(),
1151 UE = ScalarVal->use_end(); UI != UE; ++UI) {
1152 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1153 // Find out which operand this is to the call instruction...
1154 User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1155 assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1156 assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1157
1158 // FIXME: This is broken if the same pointer is passed to a call more
1159 // than once! It will get multiple entries for the first pointer.
1160
1161 // Add the operand number and pool handle to the call table...
Chris Lattner3e78dea2002-04-18 14:43:30 +00001162 CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1163 Scalars[i].Pool.Node, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001164 }
1165 }
1166 }
1167
Chris Lattner3e78dea2002-04-18 14:43:30 +00001168 // Make sure that all dependant arguments are added as well. For example, if
1169 // we call foo(null, P) and foo treats it's first and second arguments as
1170 // belonging to the same data structure, the we MUST set up the CallMap to
1171 // know that the null needs to be transformed into an index as well.
1172 //
1173 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1174 I != CallMap.end(); ++I)
1175 I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1176
Chris Lattneracf19022002-04-14 06:14:41 +00001177#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner692ad5d2002-03-29 17:13:46 +00001178 // Print out call map...
1179 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1180 I != CallMap.end(); ++I) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001181 cerr << "For call: " << I->first;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001182 cerr << I->second.Func->getName() << " must pass pool pointer for args #";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001183 for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001184 cerr << I->second.ArgInfo[i].ArgNo << ", ";
Chris Lattner441e16f2002-04-12 20:23:15 +00001185 cerr << "\n\n";
Chris Lattner692ad5d2002-03-29 17:13:46 +00001186 }
Chris Lattneracf19022002-04-14 06:14:41 +00001187#endif
Chris Lattner692ad5d2002-03-29 17:13:46 +00001188
1189 // Loop through all of the call nodes, recursively creating the new functions
1190 // that we want to call... This uses a map to prevent infinite recursion and
1191 // to avoid duplicating functions unneccesarily.
1192 //
1193 for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1194 E = CallMap.end(); I != E; ++I) {
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001195 // Transform all of the functions we need, or at least ensure there is a
1196 // cached version available.
Chris Lattner441e16f2002-04-12 20:23:15 +00001197 transformFunction(I->second, IPFGraph, PoolDescs);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001198 }
1199
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001200 // Now that all of the functions that we want to call are available, transform
Chris Lattner441e16f2002-04-12 20:23:15 +00001201 // the local function so that it uses the pools locally and passes them to the
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001202 // functions that we just hacked up.
1203 //
1204
1205 // First step, find the instructions to be modified.
1206 vector<Instruction*> InstToFix;
1207 for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1208 Value *ScalarVal = Scalars[i].Val;
1209
1210 // Check to see if the scalar _IS_ an instruction. If so, it is involved.
1211 if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1212 InstToFix.push_back(Inst);
1213
1214 // All all of the instructions that use the scalar as an operand...
1215 for (Value::use_iterator UI = ScalarVal->use_begin(),
1216 UE = ScalarVal->use_end(); UI != UE; ++UI)
Chris Lattner441e16f2002-04-12 20:23:15 +00001217 InstToFix.push_back(cast<Instruction>(*UI));
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001218 }
1219
Chris Lattner50e3d322002-04-13 23:13:18 +00001220 // Make sure that we get return instructions that return a null value from the
1221 // function...
1222 //
1223 if (!IPFGraph.getRetNodes().empty()) {
1224 assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1225 PointerVal RetNode = IPFGraph.getRetNodes()[0];
1226 assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1227
1228 // Only process return instructions if the return value of this function is
1229 // part of one of the data structures we are transforming...
1230 //
1231 if (PoolDescs.count(RetNode.Node)) {
1232 // Loop over all of the basic blocks, adding return instructions...
1233 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001234 if (ReturnInst *RI = dyn_cast<ReturnInst>(I->getTerminator()))
Chris Lattner50e3d322002-04-13 23:13:18 +00001235 InstToFix.push_back(RI);
1236 }
1237 }
1238
1239
1240
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001241 // Eliminate duplicates by sorting, then removing equal neighbors.
1242 sort(InstToFix.begin(), InstToFix.end());
1243 InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1244
Chris Lattner441e16f2002-04-12 20:23:15 +00001245 // Loop over all of the instructions to transform, creating the new
1246 // replacement instructions for them. This also unlinks them from the
1247 // function so they can be safely deleted later.
1248 //
1249 map<Value*, Value*> XFormMap;
1250 NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001251
Chris Lattner441e16f2002-04-12 20:23:15 +00001252 // Visit all instructions... creating the new instructions that we need and
1253 // unlinking the old instructions from the function...
1254 //
Chris Lattneracf19022002-04-14 06:14:41 +00001255#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001256 for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1257 cerr << "Fixing: " << InstToFix[i];
Chris Lattner7076ff22002-06-25 16:13:21 +00001258 NIC.visit(*InstToFix[i]);
Chris Lattner441e16f2002-04-12 20:23:15 +00001259 }
Chris Lattneracf19022002-04-14 06:14:41 +00001260#else
1261 NIC.visit(InstToFix.begin(), InstToFix.end());
1262#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001263
1264 // Make all instructions we will delete "let go" of their operands... so that
1265 // we can safely delete Arguments whose types have changed...
1266 //
1267 for_each(InstToFix.begin(), InstToFix.end(),
Anand Shukla2bc64192002-06-25 21:07:58 +00001268 std::mem_fun(&Instruction::dropAllReferences));
Chris Lattner441e16f2002-04-12 20:23:15 +00001269
1270 // Loop through all of the pointer arguments coming into the function,
1271 // replacing them with arguments of POINTERTYPE to match the function type of
1272 // the function.
1273 //
1274 FunctionType::ParamTypes::const_iterator TI =
1275 F->getFunctionType()->getParamTypes().begin();
Chris Lattner7076ff22002-06-25 16:13:21 +00001276 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++TI) {
1277 if (I->getType() != *TI) {
1278 assert(isa<PointerType>(I->getType()) && *TI == POINTERTYPE);
1279 Argument *NewArg = new Argument(*TI, I->getName());
1280 XFormMap[I] = NewArg; // Map old arg into new arg...
Chris Lattner441e16f2002-04-12 20:23:15 +00001281
Chris Lattner441e16f2002-04-12 20:23:15 +00001282 // Replace the old argument and then delete it...
Chris Lattner7076ff22002-06-25 16:13:21 +00001283 I = F->getArgumentList().erase(I);
1284 I = F->getArgumentList().insert(I, NewArg);
Chris Lattner441e16f2002-04-12 20:23:15 +00001285 }
1286 }
1287
1288 // Now that all of the new instructions have been created, we can update all
1289 // of the references to dummy values to be references to the actual values
1290 // that are computed.
1291 //
1292 NIC.updateReferences();
1293
Chris Lattneracf19022002-04-14 06:14:41 +00001294#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001295 cerr << "TRANSFORMED FUNCTION:\n" << F;
Chris Lattneracf19022002-04-14 06:14:41 +00001296#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001297
1298 // Delete all of the "instructions to fix"
1299 for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001300
Chris Lattner457e1ac2002-04-15 22:42:23 +00001301 // Eliminate pool base loads that we can easily prove are redundant
1302 if (!DisableRLE)
1303 PoolBaseLoadEliminator(PoolDescs).visit(F);
1304
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001305 // Since we have liberally hacked the function to pieces, we want to inform
1306 // the datastructure pass that its internal representation is out of date.
1307 //
1308 DS->invalidateFunction(F);
Chris Lattner692ad5d2002-03-29 17:13:46 +00001309}
1310
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001311
1312
1313// transformFunction - Transform the specified function the specified way. It
1314// we have already transformed that function that way, don't do anything. The
1315// nodes in the TransformFunctionInfo come out of callers data structure graph.
1316//
1317void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
Chris Lattner441e16f2002-04-12 20:23:15 +00001318 FunctionDSGraph &CallerIPGraph,
1319 map<DSNode*, PoolInfo> &CallerPoolDesc) {
Chris Lattner692ad5d2002-03-29 17:13:46 +00001320 if (getTransformedFunction(TFI)) return; // Function xformation already done?
1321
Chris Lattneracf19022002-04-14 06:14:41 +00001322#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001323 cerr << "********** Entering transformFunction for "
Chris Lattner0dc225c2002-03-31 07:17:46 +00001324 << TFI.Func->getName() << ":\n";
1325 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1326 cerr << " ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1327 cerr << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001328#endif
Chris Lattner0dc225c2002-03-31 07:17:46 +00001329
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001330 const FunctionType *OldFuncType = TFI.Func->getFunctionType();
Chris Lattner692ad5d2002-03-29 17:13:46 +00001331
Chris Lattner291a1b12002-03-29 19:05:48 +00001332 assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
Chris Lattner692ad5d2002-03-29 17:13:46 +00001333
Chris Lattner291a1b12002-03-29 19:05:48 +00001334 // Build the type for the new function that we are transforming
1335 vector<const Type*> ArgTys;
Chris Lattner441e16f2002-04-12 20:23:15 +00001336 ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
Chris Lattner291a1b12002-03-29 19:05:48 +00001337 for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1338 ArgTys.push_back(OldFuncType->getParamType(i));
1339
Chris Lattner441e16f2002-04-12 20:23:15 +00001340 const Type *RetType = OldFuncType->getReturnType();
1341
Chris Lattner291a1b12002-03-29 19:05:48 +00001342 // Add one pool pointer for every argument that needs to be supplemented.
Chris Lattner441e16f2002-04-12 20:23:15 +00001343 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1344 if (TFI.ArgInfo[i].ArgNo == -1)
1345 RetType = POINTERTYPE; // Return a pointer
1346 else
1347 ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1348 ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1349 ->second.PoolType));
1350 }
Chris Lattner291a1b12002-03-29 19:05:48 +00001351
1352 // Build the new function type...
Chris Lattner441e16f2002-04-12 20:23:15 +00001353 const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1354 OldFuncType->isVarArg());
Chris Lattner291a1b12002-03-29 19:05:48 +00001355
1356 // The new function is internal, because we know that only we can call it.
1357 // This also helps subsequent IP transformations to eliminate duplicated pool
Chris Lattner441e16f2002-04-12 20:23:15 +00001358 // pointers (which look like the same value is always passed into a parameter,
1359 // allowing it to be easily eliminated).
Chris Lattner291a1b12002-03-29 19:05:48 +00001360 //
1361 Function *NewFunc = new Function(NewFuncType, true,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001362 TFI.Func->getName()+".poolxform");
Chris Lattner291a1b12002-03-29 19:05:48 +00001363 CurModule->getFunctionList().push_back(NewFunc);
1364
Chris Lattner441e16f2002-04-12 20:23:15 +00001365
Chris Lattneracf19022002-04-14 06:14:41 +00001366#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001367 cerr << "Created function prototype: " << NewFunc << "\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001368#endif
Chris Lattner441e16f2002-04-12 20:23:15 +00001369
Chris Lattner291a1b12002-03-29 19:05:48 +00001370 // Add the newly formed function to the TransformedFunctions table so that
1371 // infinite recursion does not occur!
1372 //
1373 TransformedFunctions[TFI] = NewFunc;
1374
1375 // Add arguments to the function... starting with all of the old arguments
1376 vector<Value*> ArgMap;
Chris Lattner7076ff22002-06-25 16:13:21 +00001377 for (Function::const_aiterator I = TFI.Func->abegin(), E = TFI.Func->aend();
1378 I != E; ++I) {
1379 Argument *NFA = new Argument(I->getType(), I->getName());
Chris Lattner291a1b12002-03-29 19:05:48 +00001380 NewFunc->getArgumentList().push_back(NFA);
1381 ArgMap.push_back(NFA); // Keep track of the arguments
1382 }
1383
1384 // Now add all of the arguments corresponding to pools passed in...
1385 for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001386 CallArgInfo &AI = TFI.ArgInfo[i];
Chris Lattner291a1b12002-03-29 19:05:48 +00001387 string Name;
Chris Lattner441e16f2002-04-12 20:23:15 +00001388 if (AI.ArgNo == -1)
1389 Name = "ret";
Chris Lattner291a1b12002-03-29 19:05:48 +00001390 else
Chris Lattner441e16f2002-04-12 20:23:15 +00001391 Name = ArgMap[AI.ArgNo]->getName(); // Get the arg name
1392 const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1393 Argument *NFA = new Argument(Ty, Name+".pool");
Chris Lattner291a1b12002-03-29 19:05:48 +00001394 NewFunc->getArgumentList().push_back(NFA);
1395 }
1396
1397 // Now clone the body of the old function into the new function...
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001398 CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
Chris Lattner291a1b12002-03-29 19:05:48 +00001399
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001400 // Okay, now we have a function that is identical to the old one, except that
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001401 // it has extra arguments for the pools coming in. Now we have to get the
1402 // data structure graph for the function we are replacing, and figure out how
1403 // our graph nodes map to the graph nodes in the dest function.
1404 //
Chris Lattner847b6e22002-03-30 20:53:14 +00001405 FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001406
Chris Lattner441e16f2002-04-12 20:23:15 +00001407 // NodeMapping - Multimap from callers graph to called graph. We are
1408 // guaranteed that the called function graph has more nodes than the caller,
1409 // or exactly the same number of nodes. This is because the called function
1410 // might not know that two nodes are merged when considering the callers
1411 // context, but the caller obviously does. Because of this, a single node in
1412 // the calling function's data structure graph can map to multiple nodes in
1413 // the called functions graph.
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001414 //
1415 map<DSNode*, PointerValSet> NodeMapping;
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001416
Chris Lattner847b6e22002-03-30 20:53:14 +00001417 CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph,
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001418 NodeMapping);
1419
1420 // Print out the node mapping...
Chris Lattneracf19022002-04-14 06:14:41 +00001421#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001422 cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001423 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1424 I != NodeMapping.end(); ++I) {
1425 cerr << "Map: "; I->first->print(cerr);
1426 cerr << "To: "; I->second.print(cerr);
1427 cerr << "\n";
1428 }
Chris Lattneracf19022002-04-14 06:14:41 +00001429#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001430
1431 // Fill in the PoolDescriptor information for the transformed function so that
1432 // it can determine which value holds the pool descriptor for each data
1433 // structure node that it accesses.
1434 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001435 map<DSNode*, PoolInfo> PoolDescs;
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001436
Chris Lattneracf19022002-04-14 06:14:41 +00001437#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner847b6e22002-03-30 20:53:14 +00001438 cerr << "\nCalculating the pool descriptor map:\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001439#endif
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001440
Chris Lattner441e16f2002-04-12 20:23:15 +00001441 // Calculate as much of the pool descriptor map as possible. Since we have
1442 // the node mapping between the caller and callee functions, and we have the
1443 // pool descriptor information of the caller, we can calculate a partical pool
1444 // descriptor map for the called function.
1445 //
1446 // The nodes that we do not have complete information for are the ones that
1447 // are accessed by loading pointers derived from arguments passed in, but that
1448 // are not passed in directly. In this case, we have all of the information
1449 // except a pool value. If the called function refers to this pool, the pool
1450 // value will be loaded from the pool graph and added to the map as neccesary.
1451 //
1452 for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1453 I != NodeMapping.end(); ++I) {
1454 DSNode *CallerNode = I->first;
1455 PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001456
Chris Lattner441e16f2002-04-12 20:23:15 +00001457 // Check to see if we have a node pointer passed in for this value...
1458 Value *CalleeValue = 0;
1459 for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1460 if (TFI.ArgInfo[a].Node == CallerNode) {
1461 // Calculate the argument number that the pool is to the function
1462 // call... The call instruction should not have the pool operands added
1463 // yet.
1464 unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
Chris Lattneracf19022002-04-14 06:14:41 +00001465#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001466 cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
Chris Lattneracf19022002-04-14 06:14:41 +00001467#endif
Chris Lattner7076ff22002-06-25 16:13:21 +00001468 assert(ArgNo < NewFunc->asize() &&
Chris Lattner441e16f2002-04-12 20:23:15 +00001469 "Call already has pool arguments added??");
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001470
Chris Lattner441e16f2002-04-12 20:23:15 +00001471 // Map the pool argument into the called function...
Chris Lattner7076ff22002-06-25 16:13:21 +00001472 Function::aiterator AI = NewFunc->abegin();
1473 std::advance(AI, ArgNo);
1474 CalleeValue = AI;
Chris Lattner441e16f2002-04-12 20:23:15 +00001475 break; // Found value, quit loop
1476 }
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001477
Chris Lattner441e16f2002-04-12 20:23:15 +00001478 // Loop over all of the data structure nodes that this incoming node maps to
1479 // Creating a PoolInfo structure for them.
1480 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1481 assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1482 DSNode *CalleeNode = I->second[i].Node;
1483
1484 // Add the descriptor. We already know everything about it by now, much
1485 // of it is the same as the caller info.
1486 //
Anand Shukla2bc64192002-06-25 21:07:58 +00001487 PoolDescs.insert(std::make_pair(CalleeNode,
Chris Lattner441e16f2002-04-12 20:23:15 +00001488 PoolInfo(CalleeNode, CalleeValue,
1489 CallerPI.NewType,
1490 CallerPI.PoolType)));
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001491 }
Chris Lattner847b6e22002-03-30 20:53:14 +00001492 }
1493
1494 // We must destroy the node mapping so that we don't have latent references
1495 // into the data structure graph for the new function. Otherwise we get
1496 // assertion failures when transformFunctionBody tries to invalidate the
1497 // graph.
1498 //
1499 NodeMapping.clear();
Chris Lattnerca9f4d32002-03-30 09:12:35 +00001500
1501 // Now that we know everything we need about the function, transform the body
1502 // now!
1503 //
Chris Lattner441e16f2002-04-12 20:23:15 +00001504 transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1505
Chris Lattneracf19022002-04-14 06:14:41 +00001506#ifdef DEBUG_TRANSFORM_PROGRESS
Chris Lattner441e16f2002-04-12 20:23:15 +00001507 cerr << "Function after transformation:\n" << NewFunc;
Chris Lattneracf19022002-04-14 06:14:41 +00001508#endif
Chris Lattner66df97d2002-03-29 06:21:38 +00001509}
1510
Chris Lattner8f796d62002-04-13 19:25:57 +00001511static unsigned countPointerTypes(const Type *Ty) {
1512 if (isa<PointerType>(Ty)) {
1513 return 1;
Chris Lattner7076ff22002-06-25 16:13:21 +00001514 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001515 unsigned Num = 0;
1516 for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1517 Num += countPointerTypes(STy->getElementTypes()[i]);
1518 return Num;
Chris Lattner7076ff22002-06-25 16:13:21 +00001519 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Chris Lattner8f796d62002-04-13 19:25:57 +00001520 return countPointerTypes(ATy->getElementType());
1521 } else {
1522 assert(Ty->isPrimitiveType() && "Unknown derived type!");
1523 return 0;
1524 }
1525}
Chris Lattner66df97d2002-03-29 06:21:38 +00001526
1527// CreatePools - Insert instructions into the function we are processing to
1528// create all of the memory pool objects themselves. This also inserts
1529// destruction code. Add an alloca for each pool that is allocated to the
Chris Lattner441e16f2002-04-12 20:23:15 +00001530// PoolDescs vector.
Chris Lattner66df97d2002-03-29 06:21:38 +00001531//
1532void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
Chris Lattner441e16f2002-04-12 20:23:15 +00001533 map<DSNode*, PoolInfo> &PoolDescs) {
1534 // Find all of the return nodes in the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001535 vector<BasicBlock*> ReturnNodes;
1536 for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
Chris Lattner7076ff22002-06-25 16:13:21 +00001537 if (isa<ReturnInst>(I->getTerminator()))
1538 ReturnNodes.push_back(I);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001539
Chris Lattner3e78dea2002-04-18 14:43:30 +00001540#ifdef DEBUG_CREATE_POOLS
1541 cerr << "Allocs that we are pool allocating:\n";
1542 for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1543 Allocs[i]->dump();
1544#endif
1545
Chris Lattner441e16f2002-04-12 20:23:15 +00001546 map<DSNode*, PATypeHolder> AbsPoolTyMap;
1547
1548 // First pass over the allocations to process...
1549 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1550 // Create the pooldescriptor mapping... with null entries for everything
1551 // except the node & NewType fields.
1552 //
1553 map<DSNode*, PoolInfo>::iterator PI =
Anand Shukla2bc64192002-06-25 21:07:58 +00001554 PoolDescs.insert(std::make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
Chris Lattner441e16f2002-04-12 20:23:15 +00001555
Chris Lattner8f796d62002-04-13 19:25:57 +00001556 // Add a symbol table entry for the new type if there was one for the old
1557 // type...
1558 string OldName = CurModule->getTypeName(Allocs[i]->getType());
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001559 if (OldName.empty()) OldName = "node";
1560 CurModule->addTypeName(OldName+".p", PI->second.NewType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001561
Chris Lattner441e16f2002-04-12 20:23:15 +00001562 // Create the abstract pool types that will need to be resolved in a second
1563 // pass once an abstract type is created for each pool.
1564 //
1565 // Can only handle limited shapes for now...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001566 const Type *OldNodeTy = Allocs[i]->getType();
Chris Lattner441e16f2002-04-12 20:23:15 +00001567 vector<const Type*> PoolTypes;
1568
1569 // Pool type is the first element of the pool descriptor type...
1570 PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
Chris Lattner8f796d62002-04-13 19:25:57 +00001571
1572 unsigned NumPointers = countPointerTypes(OldNodeTy);
1573 while (NumPointers--) // Add a different opaque type for each pointer
1574 PoolTypes.push_back(OpaqueType::get());
1575
Chris Lattner441e16f2002-04-12 20:23:15 +00001576 assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1577 "Node should have same number of pointers as pool!");
1578
Chris Lattner8f796d62002-04-13 19:25:57 +00001579 StructType *PoolType = StructType::get(PoolTypes);
1580
1581 // Add a symbol table entry for the pooltype if possible...
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001582 CurModule->addTypeName(OldName+".pool", PoolType);
Chris Lattner8f796d62002-04-13 19:25:57 +00001583
Chris Lattner441e16f2002-04-12 20:23:15 +00001584 // Create the pool type, with opaque values for pointers...
Anand Shukla2bc64192002-06-25 21:07:58 +00001585 AbsPoolTyMap.insert(std::make_pair(Allocs[i], PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001586#ifdef DEBUG_CREATE_POOLS
1587 cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1588#endif
1589 }
1590
1591 // Now that we have types for all of the pool types, link them all together.
1592 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1593 PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1594
1595 // Resolve all of the outgoing pointer types of this pool node...
1596 for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1597 PointerValSet &PVS = Allocs[i]->getLink(p);
1598 assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1599 " probably just leave the type opaque or something dumb.");
1600 unsigned Out;
1601 for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1602 assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1603
1604 assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1605
1606 // The actual struct type could change each time through the loop, so it's
1607 // NOT loop invariant.
Chris Lattner7076ff22002-06-25 16:13:21 +00001608 const StructType *PoolTy = cast<StructType>(PoolTyH.get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001609
1610 // Get the opaque type...
Chris Lattner7076ff22002-06-25 16:13:21 +00001611 DerivedType *ElTy = (DerivedType*)(PoolTy->getElementTypes()[p+1].get());
Chris Lattner441e16f2002-04-12 20:23:15 +00001612
1613#ifdef DEBUG_CREATE_POOLS
1614 cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1615 << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1616#endif
1617
1618 const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1619 ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1620
1621#ifdef DEBUG_CREATE_POOLS
1622 cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1623#endif
1624 }
1625 }
1626
1627 // Create the code that goes in the entry and exit nodes for the function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001628 vector<Instruction*> EntryNodeInsts;
1629 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001630 PoolInfo &PI = PoolDescs[Allocs[i]];
1631
1632 // Fill in the pool type for this pool...
1633 PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1634 assert(!PI.PoolType->isAbstract() &&
1635 "Pool type should not be abstract anymore!");
1636
Chris Lattnere0618ca2002-03-29 05:50:20 +00001637 // Add an allocation and a free for each pool...
Chris Lattnerfc91ee92002-09-13 22:28:50 +00001638 AllocaInst *PoolAlloc = new AllocaInst(PI.PoolType, 0,
1639 CurModule->getTypeName(PI.PoolType));
Chris Lattner441e16f2002-04-12 20:23:15 +00001640 PI.Handle = PoolAlloc;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001641 EntryNodeInsts.push_back(PoolAlloc);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001642 AllocationInst *AI = Allocs[i]->getAllocation();
1643
1644 // Initialize the pool. We need to know how big each allocation is. For
1645 // our purposes here, we assume we are allocating a scalar, or array of
1646 // constant size.
1647 //
Chris Lattneracf19022002-04-14 06:14:41 +00001648 unsigned ElSize = TargetData.getTypeSize(PI.NewType);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001649
1650 vector<Value*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001651 Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
Chris Lattner441e16f2002-04-12 20:23:15 +00001652 Args.push_back(PoolAlloc); // Pool to initialize
Chris Lattnere0618ca2002-03-29 05:50:20 +00001653 EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1654
Chris Lattner441e16f2002-04-12 20:23:15 +00001655 // Add code to destroy the pool in all of the exit nodes of the function...
Chris Lattner8f796d62002-04-13 19:25:57 +00001656 Args.clear();
1657 Args.push_back(PoolAlloc); // Pool to initialize
1658
Chris Lattnere0618ca2002-03-29 05:50:20 +00001659 for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1660 Instruction *Destroy = new CallInst(PoolDestroy, Args);
1661
1662 // Insert it before the return instruction...
1663 BasicBlock *RetNode = ReturnNodes[EN];
Chris Lattner7076ff22002-06-25 16:13:21 +00001664 RetNode->getInstList().insert(RetNode->end()--, Destroy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001665 }
1666 }
1667
Chris Lattner5da145b2002-04-13 19:52:54 +00001668 // Now that all of the pool descriptors have been created, link them together
1669 // so that called functions can get links as neccesary...
1670 //
1671 for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1672 PoolInfo &PI = PoolDescs[Allocs[i]];
1673
1674 // For every pointer in the data structure, initialize a link that
1675 // indicates which pool to access...
1676 //
1677 vector<Value*> Indices(2);
1678 Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1679 for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1680 // Only store an entry for the field if the field is used!
1681 if (!PI.Node->getLink(l).empty()) {
1682 assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1683 PointerVal PV = PI.Node->getLink(l)[0];
1684 assert(PV.Index == 0 && "Subindexing not supported yet!");
1685 PoolInfo &LinkedPool = PoolDescs[PV.Node];
1686 Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1687
1688 EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1689 Indices));
1690 }
1691 }
1692
Chris Lattnere0618ca2002-03-29 05:50:20 +00001693 // Insert the entry node code into the entry block...
Chris Lattner7076ff22002-06-25 16:13:21 +00001694 F->getEntryNode().getInstList().insert(++F->getEntryNode().begin(),
Chris Lattnere0618ca2002-03-29 05:50:20 +00001695 EntryNodeInsts.begin(),
1696 EntryNodeInsts.end());
Chris Lattner175f37c2002-03-29 03:40:59 +00001697}
1698
1699
Chris Lattner441e16f2002-04-12 20:23:15 +00001700// addPoolPrototypes - Add prototypes for the pool functions to the specified
Chris Lattner175f37c2002-03-29 03:40:59 +00001701// module and update the Pool* instance variables to point to them.
1702//
Chris Lattner7076ff22002-06-25 16:13:21 +00001703void PoolAllocate::addPoolPrototypes(Module &M) {
Chris Lattner441e16f2002-04-12 20:23:15 +00001704 // Get poolinit function...
Chris Lattnere0618ca2002-03-29 05:50:20 +00001705 vector<const Type*> Args;
Chris Lattnere0618ca2002-03-29 05:50:20 +00001706 Args.push_back(Type::UIntTy); // Num bytes per element
Chris Lattner441e16f2002-04-12 20:23:15 +00001707 FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001708 PoolInit = M.getOrInsertFunction("poolinit", PoolInitTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001709
Chris Lattnere0618ca2002-03-29 05:50:20 +00001710 // Get pooldestroy function...
1711 Args.pop_back(); // Only takes a pool...
Chris Lattner441e16f2002-04-12 20:23:15 +00001712 FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001713 PoolDestroy = M.getOrInsertFunction("pooldestroy", PoolDestroyTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001714
Chris Lattnere0618ca2002-03-29 05:50:20 +00001715 // Get the poolalloc function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001716 FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001717 PoolAlloc = M.getOrInsertFunction("poolalloc", PoolAllocTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001718
1719 // Get the poolfree function...
Chris Lattner441e16f2002-04-12 20:23:15 +00001720 Args.push_back(POINTERTYPE); // Pointer to free
1721 FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001722 PoolFree = M.getOrInsertFunction("poolfree", PoolFreeTy);
Chris Lattnere0618ca2002-03-29 05:50:20 +00001723
Chris Lattner0e0c15b2002-04-27 02:29:32 +00001724 Args[0] = Type::UIntTy; // Number of slots to allocate
1725 FunctionType *PoolAllocArrayTy = FunctionType::get(POINTERTYPE, Args, true);
Chris Lattner7076ff22002-06-25 16:13:21 +00001726 PoolAllocArray = M.getOrInsertFunction("poolallocarray", PoolAllocArrayTy);
Chris Lattner175f37c2002-03-29 03:40:59 +00001727}
1728
1729
Chris Lattner7076ff22002-06-25 16:13:21 +00001730bool PoolAllocate::run(Module &M) {
Chris Lattner175f37c2002-03-29 03:40:59 +00001731 addPoolPrototypes(M);
Chris Lattner7076ff22002-06-25 16:13:21 +00001732 CurModule = &M;
Chris Lattner175f37c2002-03-29 03:40:59 +00001733
1734 DS = &getAnalysis<DataStructure>();
1735 bool Changed = false;
Chris Lattner291a1b12002-03-29 19:05:48 +00001736
Chris Lattner7076ff22002-06-25 16:13:21 +00001737 for (Module::iterator I = M.begin(); I != M.end(); ++I)
1738 if (!I->isExternal()) {
1739 Changed |= processFunction(I);
Chris Lattnerf32d65d2002-03-29 21:25:19 +00001740 if (Changed) {
1741 cerr << "Only processing one function\n";
1742 break;
1743 }
1744 }
Chris Lattner175f37c2002-03-29 03:40:59 +00001745
1746 CurModule = 0;
1747 DS = 0;
1748 return false;
1749}
Chris Lattner175f37c2002-03-29 03:40:59 +00001750
1751// createPoolAllocatePass - Global function to access the functionality of this
1752// pass...
1753//
Chris Lattner87d180e2002-07-10 22:36:47 +00001754Pass *createPoolAllocatePass() {
1755 assert(0 && "Pool allocator disabled!");
Chris Lattner10073a92002-07-25 06:17:51 +00001756 return 0;
Chris Lattner87d180e2002-07-10 22:36:47 +00001757 //return new PoolAllocate();
1758}
Chris Lattnerd1fd7e92003-01-24 20:13:20 +00001759#endif