Programs that actually free memory were broken
[oota-llvm.git] / lib / Transforms / IPO / OldPoolAllocate.cpp
1 //===-- 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 // This pass requires a DCE & instcombine pass to be run after it for best
8 // results.
9 //
10 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Transforms/IPO/PoolAllocate.h"
13 #include "llvm/Transforms/CloneFunction.h"
14 #include "llvm/Analysis/DataStructure.h"
15 #include "llvm/Analysis/DataStructureGraph.h"
16 #include "llvm/Module.h"
17 #include "llvm/Function.h"
18 #include "llvm/BasicBlock.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iPHINode.h"
22 #include "llvm/iOther.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/ConstantVals.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "llvm/Argument.h"
28 #include "Support/DepthFirstIterator.h"
29 #include "Support/STLExtras.h"
30 #include <algorithm>
31
32 // DEBUG_CREATE_POOLS - Enable this to turn on debug output for the pool
33 // creation phase in the top level function of a transformed data structure.
34 //
35 //#define DEBUG_CREATE_POOLS 1
36
37 // DEBUG_TRANSFORM_PROGRESS - Enable this to get lots of debug output on what
38 // the transformation is doing.
39 //
40 //#define DEBUG_TRANSFORM_PROGRESS 1
41
42 // DEBUG_POOLBASE_LOAD_ELIMINATOR - Turn this on to get statistics about how
43 // many static loads were eliminated from a function...
44 //
45 #define DEBUG_POOLBASE_LOAD_ELIMINATOR 1
46
47 #include "Support/CommandLine.h"
48 enum PtrSize {
49   Ptr8bits, Ptr16bits, Ptr32bits
50 };
51
52 static cl::Enum<enum PtrSize> ReqPointerSize("ptrsize", 0,
53                                       "Set pointer size for -poolalloc pass",
54   clEnumValN(Ptr32bits, "32", "Use 32 bit indices for pointers"),
55   clEnumValN(Ptr16bits, "16", "Use 16 bit indices for pointers"),
56   clEnumValN(Ptr8bits ,  "8", "Use 8 bit indices for pointers"), 0);
57
58 static cl::Flag DisableRLE("no-pool-load-elim", "Disable pool load elimination after poolalloc pass", cl::Hidden);
59
60 const Type *POINTERTYPE;
61
62 // FIXME: This is dependant on the sparc backend layout conventions!!
63 static TargetData TargetData("test");
64
65 static const Type *getPointerTransformedType(const Type *Ty) {
66   if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
67     return POINTERTYPE;
68   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
69     vector<const Type *> NewElTypes;
70     NewElTypes.reserve(STy->getElementTypes().size());
71     for (StructType::ElementTypes::const_iterator
72            I = STy->getElementTypes().begin(),
73            E = STy->getElementTypes().end(); I != E; ++I)
74       NewElTypes.push_back(getPointerTransformedType(*I));
75     return StructType::get(NewElTypes);
76   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
77     return ArrayType::get(getPointerTransformedType(ATy->getElementType()),
78                                                     ATy->getNumElements());
79   } else {
80     assert(Ty->isPrimitiveType() && "Unknown derived type!");
81     return Ty;
82   }
83 }
84
85 namespace {
86   struct PoolInfo {
87     DSNode *Node;           // The node this pool allocation represents
88     Value  *Handle;         // LLVM value of the pool in the current context
89     const Type *NewType;    // The transformed type of the memory objects
90     const Type *PoolType;   // The type of the pool
91
92     const Type *getOldType() const { return Node->getType(); }
93
94     PoolInfo() {  // Define a default ctor for map::operator[]
95       cerr << "Map subscript used to get element that doesn't exist!\n";
96       abort();  // Invalid
97     }
98
99     PoolInfo(DSNode *N, Value *H, const Type *NT, const Type *PT)
100       : Node(N), Handle(H), NewType(NT), PoolType(PT) {
101       // Handle can be null...
102       assert(N && NT && PT && "Pool info null!");
103     }
104
105     PoolInfo(DSNode *N) : Node(N), Handle(0), NewType(0), PoolType(0) {
106       assert(N && "Invalid pool info!");
107
108       // The new type of the memory object is the same as the old type, except
109       // that all of the pointer values are replaced with POINTERTYPE values.
110       NewType = getPointerTransformedType(getOldType());
111     }
112   };
113
114   // ScalarInfo - Information about an LLVM value that we know points to some
115   // datastructure we are processing.
116   //
117   struct ScalarInfo {
118     Value  *Val;            // Scalar value in Current Function
119     PoolInfo Pool;          // The pool the scalar points into
120     
121     ScalarInfo(Value *V, const PoolInfo &PI) : Val(V), Pool(PI) {
122       assert(V && "Null value passed to ScalarInfo ctor!");
123     }
124   };
125
126   // CallArgInfo - Information on one operand for a call that got expanded.
127   struct CallArgInfo {
128     int ArgNo;          // Call argument number this corresponds to
129     DSNode *Node;       // The graph node for the pool
130     Value *PoolHandle;  // The LLVM value that is the pool pointer
131
132     CallArgInfo(int Arg, DSNode *N, Value *PH)
133       : ArgNo(Arg), Node(N), PoolHandle(PH) {
134       assert(Arg >= -1 && N && PH && "Illegal values to CallArgInfo ctor!");
135     }
136
137     // operator< when sorting, sort by argument number.
138     bool operator<(const CallArgInfo &CAI) const {
139       return ArgNo < CAI.ArgNo;
140     }
141   };
142
143   // TransformFunctionInfo - Information about how a function eeds to be
144   // transformed.
145   //
146   struct TransformFunctionInfo {
147     // ArgInfo - Maintain information about the arguments that need to be
148     // processed.  Each CallArgInfo corresponds to an argument that needs to
149     // have a pool pointer passed into the transformed function with it.
150     //
151     // As a special case, "argument" number -1 corresponds to the return value.
152     //
153     vector<CallArgInfo> ArgInfo;
154
155     // Func - The function to be transformed...
156     Function *Func;
157
158     // The call instruction that is used to map CallArgInfo PoolHandle values
159     // into the new function values.
160     CallInst *Call;
161
162     // default ctor...
163     TransformFunctionInfo() : Func(0), Call(0) {}
164     
165     bool operator<(const TransformFunctionInfo &TFI) const {
166       if (Func < TFI.Func) return true;
167       if (Func > TFI.Func) return false;
168       if (ArgInfo.size() < TFI.ArgInfo.size()) return true;
169       if (ArgInfo.size() > TFI.ArgInfo.size()) return false;
170       return ArgInfo < TFI.ArgInfo;
171     }
172
173     void finalizeConstruction() {
174       // Sort the vector so that the return value is first, followed by the
175       // argument records, in order.  Note that this must be a stable sort so
176       // that the entries with the same sorting criteria (ie they are multiple
177       // pool entries for the same argument) are kept in depth first order.
178       stable_sort(ArgInfo.begin(), ArgInfo.end());
179     }
180
181     // addCallInfo - For a specified function call CI, figure out which pool
182     // descriptors need to be passed in as arguments, and which arguments need
183     // to be transformed into indices.  If Arg != -1, the specified call
184     // argument is passed in as a pointer to a data structure.
185     //
186     void addCallInfo(DataStructure *DS, CallInst *CI, int Arg,
187                      DSNode *GraphNode, map<DSNode*, PoolInfo> &PoolDescs);
188
189     // Make sure that all dependant arguments are added to this transformation
190     // info.  For example, if we call foo(null, P) and foo treats it's first and
191     // second arguments as belonging to the same data structure, the we MUST add
192     // entries to know that the null needs to be transformed into an index as
193     // well.
194     //
195     void ensureDependantArgumentsIncluded(DataStructure *DS,
196                                           map<DSNode*, PoolInfo> &PoolDescs);
197   };
198
199
200   // Define the pass class that we implement...
201   struct PoolAllocate : public Pass {
202     PoolAllocate() {
203       switch (ReqPointerSize) {
204       case Ptr32bits: POINTERTYPE = Type::UIntTy; break;
205       case Ptr16bits: POINTERTYPE = Type::UShortTy; break;
206       case Ptr8bits:  POINTERTYPE = Type::UByteTy; break;
207       }
208
209       CurModule = 0; DS = 0;
210       PoolInit = PoolDestroy = PoolAlloc = PoolFree = 0;
211     }
212
213     // getPoolType - Get the type used by the backend for a pool of a particular
214     // type.  This pool record is used to allocate nodes of type NodeType.
215     //
216     // Here, PoolTy = { NodeType*, sbyte*, uint }*
217     //
218     const StructType *getPoolType(const Type *NodeType) {
219       vector<const Type*> PoolElements;
220       PoolElements.push_back(PointerType::get(NodeType));
221       PoolElements.push_back(PointerType::get(Type::SByteTy));
222       PoolElements.push_back(Type::UIntTy);
223       StructType *Result = StructType::get(PoolElements);
224
225       // Add a name to the symbol table to correspond to the backend
226       // representation of this pool...
227       assert(CurModule && "No current module!?");
228       string Name = CurModule->getTypeName(NodeType);
229       if (Name.empty()) Name = CurModule->getTypeName(PoolElements[0]);
230       CurModule->addTypeName(Name+"oolbe", Result);
231
232       return Result;
233     }
234
235     bool run(Module *M);
236
237     // getAnalysisUsageInfo - This function requires data structure information
238     // to be able to see what is pool allocatable.
239     //
240     virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Required,
241                                       Pass::AnalysisSet &,Pass::AnalysisSet &) {
242       Required.push_back(DataStructure::ID);
243     }
244
245   public:
246     // CurModule - The module being processed.
247     Module *CurModule;
248
249     // DS - The data structure graph for the module being processed.
250     DataStructure *DS;
251
252     // Prototypes that we add to support pool allocation...
253     Function *PoolInit, *PoolDestroy, *PoolAlloc, *PoolFree;
254
255     // The map of already transformed functions... note that the keys of this
256     // map do not have meaningful values for 'Call' or the 'PoolHandle' elements
257     // of the ArgInfo elements.
258     //
259     map<TransformFunctionInfo, Function*> TransformedFunctions;
260
261     // getTransformedFunction - Get a transformed function, or return null if
262     // the function specified hasn't been transformed yet.
263     //
264     Function *getTransformedFunction(TransformFunctionInfo &TFI) const {
265       map<TransformFunctionInfo, Function*>::const_iterator I =
266         TransformedFunctions.find(TFI);
267       if (I != TransformedFunctions.end()) return I->second;
268       return 0;
269     }
270
271
272     // addPoolPrototypes - Add prototypes for the pool functions to the
273     // specified module and update the Pool* instance variables to point to
274     // them.
275     //
276     void addPoolPrototypes(Module *M);
277
278
279     // CreatePools - Insert instructions into the function we are processing to
280     // create all of the memory pool objects themselves.  This also inserts
281     // destruction code.  Add an alloca for each pool that is allocated to the
282     // PoolDescs map.
283     //
284     void CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
285                      map<DSNode*, PoolInfo> &PoolDescs);
286
287     // processFunction - Convert a function to use pool allocation where
288     // available.
289     //
290     bool processFunction(Function *F);
291
292     // transformFunctionBody - This transforms the instruction in 'F' to use the
293     // pools specified in PoolDescs when modifying data structure nodes
294     // specified in the PoolDescs map.  IPFGraph is the closed data structure
295     // graph for F, of which the PoolDescriptor nodes come from.
296     //
297     void transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
298                                map<DSNode*, PoolInfo> &PoolDescs);
299
300     // transformFunction - Transform the specified function the specified way.
301     // It we have already transformed that function that way, don't do anything.
302     // The nodes in the TransformFunctionInfo come out of callers data structure
303     // graph, and the PoolDescs passed in are the caller's.
304     //
305     void transformFunction(TransformFunctionInfo &TFI,
306                            FunctionDSGraph &CallerIPGraph,
307                            map<DSNode*, PoolInfo> &PoolDescs);
308
309   };
310 }
311
312 // isNotPoolableAlloc - This is a predicate that returns true if the specified
313 // allocation node in a data structure graph is eligable for pool allocation.
314 //
315 static bool isNotPoolableAlloc(const AllocDSNode *DS) {
316   if (DS->isAllocaNode()) return true;  // Do not pool allocate alloca's.
317
318   MallocInst *MI = cast<MallocInst>(DS->getAllocation());
319   if (MI->isArrayAllocation() && !isa<Constant>(MI->getArraySize()))
320     return true;   // Do not allow variable size allocations...
321
322   return false;
323 }
324
325 // processFunction - Convert a function to use pool allocation where
326 // available.
327 //
328 bool PoolAllocate::processFunction(Function *F) {
329   // Get the closed datastructure graph for the current function... if there are
330   // any allocations in this graph that are not escaping, we need to pool
331   // allocate them here!
332   //
333   FunctionDSGraph &IPGraph = DS->getClosedDSGraph(F);
334
335   // Get all of the allocations that do not escape the current function.  Since
336   // they are still live (they exist in the graph at all), this means we must
337   // have scalar references to these nodes, but the scalars are never returned.
338   // 
339   vector<AllocDSNode*> Allocs;
340   IPGraph.getNonEscapingAllocations(Allocs);
341
342   // Filter out allocations that we cannot handle.  Currently, this includes
343   // variable sized array allocations and alloca's (which we do not want to
344   // pool allocate)
345   //
346   Allocs.erase(remove_if(Allocs.begin(), Allocs.end(), isNotPoolableAlloc),
347                Allocs.end());
348
349
350   if (Allocs.empty()) return false;  // Nothing to do.
351
352 #ifdef DEBUG_TRANSFORM_PROGRESS
353   cerr << "Transforming Function: " << F->getName() << "\n";
354 #endif
355
356   // Insert instructions into the function we are processing to create all of
357   // the memory pool objects themselves.  This also inserts destruction code.
358   // This fills in the PoolDescs map to associate the alloc node with the
359   // allocation of the memory pool corresponding to it.
360   // 
361   map<DSNode*, PoolInfo> PoolDescs;
362   CreatePools(F, Allocs, PoolDescs);
363
364 #ifdef DEBUG_TRANSFORM_PROGRESS
365   cerr << "Transformed Entry Function: \n" << F;
366 #endif
367
368   // Now we need to figure out what called functions we need to transform, and
369   // how.  To do this, we look at all of the scalars, seeing which functions are
370   // either used as a scalar value (so they return a data structure), or are
371   // passed one of our scalar values.
372   //
373   transformFunctionBody(F, IPGraph, PoolDescs);
374
375   return true;
376 }
377
378
379 //===----------------------------------------------------------------------===//
380 //
381 // NewInstructionCreator - This class is used to traverse the function being
382 // modified, changing each instruction visit'ed to use and provide pointer
383 // indexes instead of real pointers.  This is what changes the body of a
384 // function to use pool allocation.
385 //
386 class NewInstructionCreator : public InstVisitor<NewInstructionCreator> {
387   PoolAllocate &PoolAllocator;
388   vector<ScalarInfo> &Scalars;
389   map<CallInst*, TransformFunctionInfo> &CallMap;
390   map<Value*, Value*> &XFormMap;   // Map old pointers to new indexes
391
392   struct RefToUpdate {
393     Instruction *I;       // Instruction to update
394     unsigned     OpNum;   // Operand number to update
395     Value       *OldVal;  // The old value it had
396
397     RefToUpdate(Instruction *i, unsigned o, Value *ov)
398       : I(i), OpNum(o), OldVal(ov) {}
399   };
400   vector<RefToUpdate> ReferencesToUpdate;
401
402   const ScalarInfo &getScalarRef(const Value *V) {
403     for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
404       if (Scalars[i].Val == V) return Scalars[i];
405
406     cerr << "Could not find scalar " << V << " in scalar map!\n";
407     assert(0 && "Scalar not found in getScalar!");
408     abort();
409     return Scalars[0];
410   }
411   
412   const ScalarInfo *getScalar(const Value *V) {
413     for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
414       if (Scalars[i].Val == V) return &Scalars[i];
415     return 0;
416   }
417
418   BasicBlock::iterator ReplaceInstWith(Instruction *I, Instruction *New) {
419     BasicBlock *BB = I->getParent();
420     BasicBlock::iterator RI = find(BB->begin(), BB->end(), I);
421     BB->getInstList().replaceWith(RI, New);
422     XFormMap[I] = New;
423     return RI;
424   }
425
426   LoadInst *createPoolBaseInstruction(Value *PtrVal) {
427     const ScalarInfo &SC = getScalarRef(PtrVal);
428     vector<Value*> Args(3);
429     Args[0] = ConstantUInt::get(Type::UIntTy, 0);  // No pointer offset
430     Args[1] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of pool descriptr
431     Args[2] = ConstantUInt::get(Type::UByteTy, 0); // Field #0 of poolalloc val
432     return new LoadInst(SC.Pool.Handle, Args, PtrVal->getName()+".poolbase");
433   }
434
435
436 public:
437   NewInstructionCreator(PoolAllocate &PA, vector<ScalarInfo> &S,
438                         map<CallInst*, TransformFunctionInfo> &C,
439                         map<Value*, Value*> &X)
440     : PoolAllocator(PA), Scalars(S), CallMap(C), XFormMap(X) {}
441
442
443   // updateReferences - The NewInstructionCreator is responsible for creating
444   // new instructions to replace the old ones in the function, and then link up
445   // references to values to their new values.  For it to do this, however, it
446   // keeps track of information about the value mapping of old values to new
447   // values that need to be patched up.  Given this value map and a set of
448   // instruction operands to patch, updateReferences performs the updates.
449   //
450   void updateReferences() {
451     for (unsigned i = 0, e = ReferencesToUpdate.size(); i != e; ++i) {
452       RefToUpdate &Ref = ReferencesToUpdate[i];
453       Value *NewVal = XFormMap[Ref.OldVal];
454
455       if (NewVal == 0) {
456         if (isa<Constant>(Ref.OldVal) &&  // Refering to a null ptr?
457             cast<Constant>(Ref.OldVal)->isNullValue()) {
458           // Transform the null pointer into a null index... caching in XFormMap
459           XFormMap[Ref.OldVal] = NewVal =Constant::getNullConstant(POINTERTYPE);
460           //} else if (isa<Argument>(Ref.OldVal)) {
461         } else {
462           cerr << "Unknown reference to: " << Ref.OldVal << "\n";
463           assert(XFormMap[Ref.OldVal] &&
464                  "Reference to value that was not updated found!");
465         }
466       }
467         
468       Ref.I->setOperand(Ref.OpNum, NewVal);
469     }
470     ReferencesToUpdate.clear();
471   }
472
473   //===--------------------------------------------------------------------===//
474   // Transformation methods:
475   //   These methods specify how each type of instruction is transformed by the
476   // NewInstructionCreator instance...
477   //===--------------------------------------------------------------------===//
478
479   void visitGetElementPtrInst(GetElementPtrInst *I) {
480     assert(0 && "Cannot transform get element ptr instructions yet!");
481   }
482
483   // Replace the load instruction with a new one.
484   void visitLoadInst(LoadInst *I) {
485     Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(0));
486
487     // Cast our index to be a UIntTy so we can use it to index into the pool...
488     CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
489                                    Type::UIntTy, I->getOperand(0)->getName());
490
491     ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(0)));
492
493     vector<Value*> Indices(I->idx_begin(), I->idx_end());
494     assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
495            "Cannot handle array indexing yet!");
496     Indices[0] = Index;
497     Instruction *NewLoad = new LoadInst(PoolBase, Indices, I->getName());
498
499     // Replace the load instruction with the new load instruction...
500     BasicBlock::iterator II = ReplaceInstWith(I, NewLoad);
501
502     // Add the pool base calculator instruction before the load...
503     II = NewLoad->getParent()->getInstList().insert(II, PoolBase) + 1;
504
505     // Add the cast before the load instruction...
506     NewLoad->getParent()->getInstList().insert(II, Index);
507
508     // If not yielding a pool allocated pointer, use the new load value as the
509     // value in the program instead of the old load value...
510     //
511     if (!getScalar(I))
512       I->replaceAllUsesWith(NewLoad);
513   }
514
515   // Replace the store instruction with a new one.  In the store instruction,
516   // the value stored could be a pointer type, meaning that the new store may
517   // have to change one or both of it's operands.
518   //
519   void visitStoreInst(StoreInst *I) {
520     assert(getScalar(I->getOperand(1)) &&
521            "Store inst found only storing pool allocated pointer.  "
522            "Not imp yet!");
523
524     Value *Val = I->getOperand(0);  // The value to store...
525     // Check to see if the value we are storing is a data structure pointer...
526     if (const ScalarInfo *ValScalar = getScalar(I->getOperand(0)))
527       Val = Constant::getNullConstant(POINTERTYPE);  // Yes, store a dummy
528
529     Instruction *PoolBase = createPoolBaseInstruction(I->getOperand(1));
530
531     // Cast our index to be a UIntTy so we can use it to index into the pool...
532     CastInst *Index = new CastInst(Constant::getNullConstant(POINTERTYPE),
533                                    Type::UIntTy, I->getOperand(1)->getName());
534     ReferencesToUpdate.push_back(RefToUpdate(Index, 0, I->getOperand(1)));
535
536     vector<Value*> Indices(I->idx_begin(), I->idx_end());
537     assert(Indices[0] == ConstantUInt::get(Type::UIntTy, 0) &&
538            "Cannot handle array indexing yet!");
539     Indices[0] = Index;
540     Instruction *NewStore = new StoreInst(Val, PoolBase, Indices);
541
542     if (Val != I->getOperand(0))    // Value stored was a pointer?
543       ReferencesToUpdate.push_back(RefToUpdate(NewStore, 0, I->getOperand(0)));
544
545
546     // Replace the store instruction with the cast instruction...
547     BasicBlock::iterator II = ReplaceInstWith(I, Index);
548
549     // Add the pool base calculator instruction before the index...
550     II = Index->getParent()->getInstList().insert(II, PoolBase) + 2;
551
552     // Add the store after the cast instruction...
553     Index->getParent()->getInstList().insert(II, NewStore);
554   }
555
556
557   // Create call to poolalloc for every malloc instruction
558   void visitMallocInst(MallocInst *I) {
559     vector<Value*> Args;
560     Args.push_back(getScalarRef(I).Pool.Handle);
561     CallInst *Call = new CallInst(PoolAllocator.PoolAlloc, Args, I->getName());
562     ReplaceInstWith(I, Call);
563   }
564
565   // Convert a call to poolfree for every free instruction...
566   void visitFreeInst(FreeInst *I) {
567     // Create a new call to poolfree before the free instruction
568     vector<Value*> Args;
569     Args.push_back(Constant::getNullConstant(POINTERTYPE));
570     Args.push_back(getScalarRef(I->getOperand(0)).Pool.Handle);
571     Instruction *NewCall = new CallInst(PoolAllocator.PoolFree, Args);
572     ReplaceInstWith(I, NewCall);
573     ReferencesToUpdate.push_back(RefToUpdate(NewCall, 1, I->getOperand(0)));
574   }
575
576   // visitCallInst - Create a new call instruction with the extra arguments for
577   // all of the memory pools that the call needs.
578   //
579   void visitCallInst(CallInst *I) {
580     TransformFunctionInfo &TI = CallMap[I];
581
582     // Start with all of the old arguments...
583     vector<Value*> Args(I->op_begin()+1, I->op_end());
584
585     for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i) {
586       // Replace all of the pointer arguments with our new pointer typed values.
587       if (TI.ArgInfo[i].ArgNo != -1)
588         Args[TI.ArgInfo[i].ArgNo] = Constant::getNullConstant(POINTERTYPE);
589
590       // Add all of the pool arguments...
591       Args.push_back(TI.ArgInfo[i].PoolHandle);
592     }
593     
594     Function *NF = PoolAllocator.getTransformedFunction(TI);
595     Instruction *NewCall = new CallInst(NF, Args, I->getName());
596     ReplaceInstWith(I, NewCall);
597
598     // Keep track of the mapping of operands so that we can resolve them to real
599     // values later.
600     Value *RetVal = NewCall;
601     for (unsigned i = 0, e = TI.ArgInfo.size(); i != e; ++i)
602       if (TI.ArgInfo[i].ArgNo != -1)
603         ReferencesToUpdate.push_back(RefToUpdate(NewCall, TI.ArgInfo[i].ArgNo+1,
604                                         I->getOperand(TI.ArgInfo[i].ArgNo+1)));
605       else
606         RetVal = 0;   // If returning a pointer, don't change retval...
607
608     // If not returning a pointer, use the new call as the value in the program
609     // instead of the old call...
610     //
611     if (RetVal)
612       I->replaceAllUsesWith(RetVal);
613   }
614
615   // visitPHINode - Create a new PHI node of POINTERTYPE for all of the old Phi
616   // nodes...
617   //
618   void visitPHINode(PHINode *PN) {
619     Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
620     PHINode *NewPhi = new PHINode(POINTERTYPE, PN->getName());
621     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
622       NewPhi->addIncoming(DummyVal, PN->getIncomingBlock(i));
623       ReferencesToUpdate.push_back(RefToUpdate(NewPhi, i*2, 
624                                                PN->getIncomingValue(i)));
625     }
626
627     ReplaceInstWith(PN, NewPhi);
628   }
629
630   // visitReturnInst - Replace ret instruction with a new return...
631   void visitReturnInst(ReturnInst *I) {
632     Instruction *Ret = new ReturnInst(Constant::getNullConstant(POINTERTYPE));
633     ReplaceInstWith(I, Ret);
634     ReferencesToUpdate.push_back(RefToUpdate(Ret, 0, I->getOperand(0)));
635   }
636
637   // visitSetCondInst - Replace a conditional test instruction with a new one
638   void visitSetCondInst(SetCondInst *SCI) {
639     BinaryOperator *I = (BinaryOperator*)SCI;
640     Value *DummyVal = Constant::getNullConstant(POINTERTYPE);
641     BinaryOperator *New = BinaryOperator::create(I->getOpcode(), DummyVal,
642                                                  DummyVal, I->getName());
643     ReplaceInstWith(I, New);
644
645     ReferencesToUpdate.push_back(RefToUpdate(New, 0, I->getOperand(0)));
646     ReferencesToUpdate.push_back(RefToUpdate(New, 1, I->getOperand(1)));
647
648     // Make sure branches refer to the new condition...
649     I->replaceAllUsesWith(New);
650   }
651
652   void visitInstruction(Instruction *I) {
653     cerr << "Unknown instruction to FunctionBodyTransformer:\n" << I;
654   }
655 };
656
657
658 // PoolBaseLoadEliminator - Every load and store through a pool allocated
659 // pointer causes a load of the real pool base out of the pool descriptor.
660 // Iterate through the function, doing a local elimination pass of duplicate
661 // loads.  This attempts to turn the all too common:
662 //
663 // %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
664 // %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
665 // %reg109.poolbase23 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
666 // store double %reg207, %root.p* %reg109.poolbase23, uint %reg109, ...
667 //
668 // into:
669 // %reg109.poolbase22 = load %root.pool* %root.pool, uint 0, ubyte 0, ubyte 0
670 // %reg207 = load %root.p* %reg109.poolbase22, uint %reg109, ubyte 0, ubyte 0
671 // store double %reg207, %root.p* %reg109.poolbase22, uint %reg109, ...
672 //
673 //
674 class PoolBaseLoadEliminator : public InstVisitor<PoolBaseLoadEliminator> {
675   // PoolDescValues - Keep track of the values in the current function that are
676   // pool descriptors (loads from which we want to eliminate).
677   //
678   vector<Value*>      PoolDescValues;
679
680   // PoolDescMap - As we are analyzing a BB, keep track of which load to use
681   // when referencing a pool descriptor.
682   //
683   map<Value*, LoadInst*> PoolDescMap;
684
685   // These two fields keep track of statistics of how effective we are, if
686   // debugging is enabled.
687   //
688   unsigned Eliminated, Remaining;
689 public:
690   // Compact the pool descriptor map into a list of the pool descriptors in the
691   // current context that we should know about...
692   //
693   PoolBaseLoadEliminator(const map<DSNode*, PoolInfo> &PoolDescs) {
694     Eliminated = Remaining = 0;
695     for (map<DSNode*, PoolInfo>::const_iterator I = PoolDescs.begin(),
696            E = PoolDescs.end(); I != E; ++I)
697       PoolDescValues.push_back(I->second.Handle);
698     
699     // Remove duplicates from the list of pool values
700     sort(PoolDescValues.begin(), PoolDescValues.end());
701     PoolDescValues.erase(unique(PoolDescValues.begin(), PoolDescValues.end()),
702                          PoolDescValues.end());
703   }
704
705 #ifdef DEBUG_POOLBASE_LOAD_ELIMINATOR
706   void visitFunction(Function *F) {
707     cerr << "Pool Load Elim '" << F->getName() << "'\t";
708   }
709   ~PoolBaseLoadEliminator() {
710     unsigned Total = Eliminated+Remaining;
711     if (Total)
712       cerr << "removed " << Eliminated << "["
713            << Eliminated*100/Total << "%] loads, leaving "
714            << Remaining << ".\n";
715   }
716 #endif
717
718   // Loop over the function, looking for loads to eliminate.  Because we are a
719   // local transformation, we reset all of our state when we enter a new basic
720   // block.
721   //
722   void visitBasicBlock(BasicBlock *) {
723     PoolDescMap.clear();  // Forget state.
724   }
725
726   // Starting with an empty basic block, we scan it looking for loads of the
727   // pool descriptor.  When we find a load, we add it to the PoolDescMap,
728   // indicating that we have a value available to recycle next time we see the
729   // poolbase of this instruction being loaded.
730   //
731   void visitLoadInst(LoadInst *LI) {
732     Value *LoadAddr = LI->getPointerOperand();
733     map<Value*, LoadInst*>::iterator VIt = PoolDescMap.find(LoadAddr);
734     if (VIt != PoolDescMap.end()) {  // We already have a value for this load?
735       LI->replaceAllUsesWith(VIt->second);   // Make the current load dead
736       ++Eliminated;
737     } else {
738       // This load might not be a load of a pool pointer, check to see if it is
739       if (LI->getNumOperands() == 4 &&  // load pool, uint 0, ubyte 0, ubyte 0
740           find(PoolDescValues.begin(), PoolDescValues.end(), LoadAddr) !=
741           PoolDescValues.end()) {
742
743         assert("Make sure it's a load of the pool base, not a chaining field" &&
744                LI->getOperand(1) == Constant::getNullConstant(Type::UIntTy) &&
745                LI->getOperand(2) == Constant::getNullConstant(Type::UByteTy) &&
746                LI->getOperand(3) == Constant::getNullConstant(Type::UByteTy));
747
748         // If it is a load of a pool base, keep track of it for future reference
749         PoolDescMap.insert(make_pair(LoadAddr, LI));
750         ++Remaining;
751       }
752     }
753   }
754
755   // If we run across a function call, forget all state...  Calls to
756   // poolalloc/poolfree can invalidate the pool base pointer, so it should be
757   // reloaded the next time it is used.  Furthermore, a call to a random
758   // function might call one of these functions, so be conservative.  Through
759   // more analysis, this could be improved in the future.
760   //
761   void visitCallInst(CallInst *) {
762     PoolDescMap.clear();
763   }
764 };
765
766 static void addNodeMapping(DSNode *SrcNode, const PointerValSet &PVS,
767                            map<DSNode*, PointerValSet> &NodeMapping) {
768   for (unsigned i = 0, e = PVS.size(); i != e; ++i)
769     if (NodeMapping[SrcNode].add(PVS[i])) {  // Not in map yet?
770       assert(PVS[i].Index == 0 && "Node indexing not supported yet!");
771       DSNode *DestNode = PVS[i].Node;
772
773       // Loop over all of the outgoing links in the mapped graph
774       for (unsigned l = 0, le = DestNode->getNumOutgoingLinks(); l != le; ++l) {
775         PointerValSet &SrcSet = SrcNode->getOutgoingLink(l);
776         const PointerValSet &DestSet = DestNode->getOutgoingLink(l);
777
778         // Add all of the node mappings now!
779         for (unsigned si = 0, se = SrcSet.size(); si != se; ++si) {
780           assert(SrcSet[si].Index == 0 && "Can't handle node offset!");
781           addNodeMapping(SrcSet[si].Node, DestSet, NodeMapping);
782         }
783       }
784     }
785 }
786
787 // CalculateNodeMapping - There is a partial isomorphism between the graph
788 // passed in and the graph that is actually used by the function.  We need to
789 // figure out what this mapping is so that we can transformFunctionBody the
790 // instructions in the function itself.  Note that every node in the graph that
791 // we are interested in must be both in the local graph of the called function,
792 // and in the local graph of the calling function.  Because of this, we only
793 // define the mapping for these nodes [conveniently these are the only nodes we
794 // CAN define a mapping for...]
795 //
796 // The roots of the graph that we are transforming is rooted in the arguments
797 // passed into the function from the caller.  This is where we start our
798 // mapping calculation.
799 //
800 // The NodeMapping calculated maps from the callers graph to the called graph.
801 //
802 static void CalculateNodeMapping(Function *F, TransformFunctionInfo &TFI,
803                                  FunctionDSGraph &CallerGraph,
804                                  FunctionDSGraph &CalledGraph, 
805                                  map<DSNode*, PointerValSet> &NodeMapping) {
806   int LastArgNo = -2;
807   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
808     // Figure out what nodes in the called graph the TFI.ArgInfo[i].Node node
809     // corresponds to...
810     //
811     // Only consider first node of sequence.  Extra nodes may may be added
812     // to the TFI if the data structure requires more nodes than just the
813     // one the argument points to.  We are only interested in the one the
814     // argument points to though.
815     //
816     if (TFI.ArgInfo[i].ArgNo != LastArgNo) {
817       if (TFI.ArgInfo[i].ArgNo == -1) {
818         addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getRetNodes(),
819                        NodeMapping);
820       } else {
821         // Figure out which node argument # ArgNo points to in the called graph.
822         Value *Arg = F->getArgumentList()[TFI.ArgInfo[i].ArgNo];     
823         addNodeMapping(TFI.ArgInfo[i].Node, CalledGraph.getValueMap()[Arg],
824                        NodeMapping);
825       }
826       LastArgNo = TFI.ArgInfo[i].ArgNo;
827     }
828   }
829 }
830
831
832
833
834 // addCallInfo - For a specified function call CI, figure out which pool
835 // descriptors need to be passed in as arguments, and which arguments need to be
836 // transformed into indices.  If Arg != -1, the specified call argument is
837 // passed in as a pointer to a data structure.
838 //
839 void TransformFunctionInfo::addCallInfo(DataStructure *DS, CallInst *CI,
840                                         int Arg, DSNode *GraphNode,
841                                         map<DSNode*, PoolInfo> &PoolDescs) {
842   assert(CI->getCalledFunction() && "Cannot handle indirect calls yet!");
843   assert(Func == 0 || Func == CI->getCalledFunction() &&
844          "Function call record should always call the same function!");
845   assert(Call == 0 || Call == CI &&
846          "Call element already filled in with different value!");
847   Func = CI->getCalledFunction();
848   Call = CI;
849   //FunctionDSGraph &CalledGraph = DS->getClosedDSGraph(Func);
850
851   // For now, add the entire graph that is pointed to by the call argument.
852   // This graph can and should be pruned to only what the function itself will
853   // use, because often this will be a dramatically smaller subset of what we
854   // are providing.
855   //
856   // FIXME: This should use pool links instead of extra arguments!
857   //
858   for (df_iterator<DSNode*> I = df_begin(GraphNode), E = df_end(GraphNode);
859        I != E; ++I)
860     ArgInfo.push_back(CallArgInfo(Arg, *I, PoolDescs[*I].Handle));
861 }
862
863 static void markReachableNodes(const PointerValSet &Vals,
864                                set<DSNode*> &ReachableNodes) {
865   for (unsigned n = 0, ne = Vals.size(); n != ne; ++n) {
866     DSNode *N = Vals[n].Node;
867     if (ReachableNodes.count(N) == 0)   // Haven't already processed node?
868       ReachableNodes.insert(df_begin(N), df_end(N)); // Insert all
869   }
870 }
871
872 // Make sure that all dependant arguments are added to this transformation info.
873 // For example, if we call foo(null, P) and foo treats it's first and second
874 // arguments as belonging to the same data structure, the we MUST add entries to
875 // know that the null needs to be transformed into an index as well.
876 //
877 void TransformFunctionInfo::ensureDependantArgumentsIncluded(DataStructure *DS,
878                                            map<DSNode*, PoolInfo> &PoolDescs) {
879   // FIXME: This does not work for indirect function calls!!!
880   if (Func == 0) return;  // FIXME!
881
882   // Make sure argument entries are sorted.
883   finalizeConstruction();
884
885   // Loop over the function signature, checking to see if there are any pointer
886   // arguments that we do not convert...  if there is something we haven't
887   // converted, set done to false.
888   //
889   unsigned PtrNo = 0;
890   bool Done = true;
891   if (isa<PointerType>(Func->getReturnType()))    // Make sure we convert retval
892     if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
893       // We DO transform the ret val... skip all possible entries for retval
894       while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
895         PtrNo++;
896     } else {
897       Done = false;
898     }
899
900   for (unsigned i = 0, e = Func->getArgumentList().size(); i != e; ++i) {
901     Argument *Arg = Func->getArgumentList()[i];
902     if (isa<PointerType>(Arg->getType())) {
903       if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
904         // We DO transform this arg... skip all possible entries for argument
905         while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
906           PtrNo++;
907       } else {
908         Done = false;
909         break;
910       }
911     }
912   }
913
914   // If we already have entries for all pointer arguments and retvals, there
915   // certainly is no work to do.  Bail out early to avoid building relatively
916   // expensive data structures.
917   //
918   if (Done) return;
919
920 #ifdef DEBUG_TRANSFORM_PROGRESS
921   cerr << "Must ensure dependant arguments for: " << Func->getName() << "\n";
922 #endif
923
924   // Otherwise, we MIGHT have to add the arguments/retval if they are part of
925   // the same datastructure graph as some other argument or retval that we ARE
926   // processing.
927   //
928   // Get the data structure graph for the called function.
929   //
930   FunctionDSGraph &CalledDS = DS->getClosedDSGraph(Func);
931
932   // Build a mapping between the nodes in our current graph and the nodes in the
933   // called function's graph.  We build it based on our _incomplete_
934   // transformation information, because it contains all of the info that we
935   // should need.
936   //
937   map<DSNode*, PointerValSet> NodeMapping;
938   CalculateNodeMapping(Func, *this,
939                        DS->getClosedDSGraph(Call->getParent()->getParent()),
940                        CalledDS, NodeMapping);
941
942   // Build the inverted version of the node mapping, that maps from a node in
943   // the called functions graph to a single node in the caller graph.
944   // 
945   map<DSNode*, DSNode*> InverseNodeMap;
946   for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin(),
947          E = NodeMapping.end(); I != E; ++I) {
948     PointerValSet &CalledNodes = I->second;
949     for (unsigned i = 0, e = CalledNodes.size(); i != e; ++i)
950       InverseNodeMap[CalledNodes[i].Node] = I->first;
951   }
952   NodeMapping.clear();  // Done with information, free memory
953   
954   // Build a set of reachable nodes from the arguments/retval that we ARE
955   // passing in...
956   set<DSNode*> ReachableNodes;
957
958   // Loop through all of the arguments, marking all of the reachable data
959   // structure nodes reachable if they are from this pointer...
960   //
961   for (unsigned i = 0, e = ArgInfo.size(); i != e; ++i) {
962     if (ArgInfo[i].ArgNo == -1) {
963       if (i == 0)   // Only process retvals once (performance opt)
964         markReachableNodes(CalledDS.getRetNodes(), ReachableNodes);
965     } else {  // If it's an argument value...
966       Argument *Arg = Func->getArgumentList()[ArgInfo[i].ArgNo];
967       if (isa<PointerType>(Arg->getType()))
968         markReachableNodes(CalledDS.getValueMap()[Arg], ReachableNodes);
969     }
970   }
971
972   // Now that we know which nodes are already reachable, see if any of the
973   // arguments that we are not passing values in for can reach one of the
974   // existing nodes...
975   //
976
977   // <FIXME> IN THEORY, we should allow arbitrary paths from the argument to
978   // nodes we know about.  The problem is that if we do this, then I don't know
979   // how to get pool pointers for this head list.  Since we are completely
980   // deadline driven, I'll just allow direct accesses to the graph. </FIXME>
981   //
982   
983   PtrNo = 0;
984   if (isa<PointerType>(Func->getReturnType()))    // Make sure we convert retval
985     if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == -1) {
986       // We DO transform the ret val... skip all possible entries for retval
987       while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == -1)
988         PtrNo++;
989     } else {
990       // See what the return value points to...
991
992       // FIXME: This should generalize to any number of nodes, just see if any
993       // are reachable.
994       assert(CalledDS.getRetNodes().size() == 1 &&
995              "Assumes only one node is returned");
996       DSNode *N = CalledDS.getRetNodes()[0].Node;
997       
998       // If the return value is not marked as being passed in, but it NEEDS to
999       // be transformed, then make it known now.
1000       //
1001       if (ReachableNodes.count(N)) {
1002 #ifdef DEBUG_TRANSFORM_PROGRESS
1003         cerr << "ensure dependant arguments adds return value entry!\n";
1004 #endif
1005         addCallInfo(DS, Call, -1, InverseNodeMap[N], PoolDescs);
1006
1007         // Keep sorted!
1008         finalizeConstruction();
1009       }
1010     }
1011
1012   for (unsigned i = 0, e = Func->getArgumentList().size(); i != e; ++i) {
1013     Argument *Arg = Func->getArgumentList()[i];
1014     if (isa<PointerType>(Arg->getType())) {
1015       if (PtrNo < ArgInfo.size() && ArgInfo[PtrNo++].ArgNo == (int)i) {
1016         // We DO transform this arg... skip all possible entries for argument
1017         while (PtrNo < ArgInfo.size() && ArgInfo[PtrNo].ArgNo == (int)i)
1018           PtrNo++;
1019       } else {
1020         // This should generalize to any number of nodes, just see if any are
1021         // reachable.
1022         assert(CalledDS.getValueMap()[Arg].size() == 1 &&
1023                "Only handle case where pointing to one node so far!");
1024
1025         // If the arg is not marked as being passed in, but it NEEDS to
1026         // be transformed, then make it known now.
1027         //
1028         DSNode *N = CalledDS.getValueMap()[Arg][0].Node;
1029         if (ReachableNodes.count(N)) {
1030 #ifdef DEBUG_TRANSFORM_PROGRESS
1031           cerr << "ensure dependant arguments adds for arg #" << i << "\n";
1032 #endif
1033           addCallInfo(DS, Call, i, InverseNodeMap[N], PoolDescs);
1034
1035           // Keep sorted!
1036           finalizeConstruction();
1037         }
1038       }
1039     }
1040   }
1041 }
1042
1043
1044 // transformFunctionBody - This transforms the instruction in 'F' to use the
1045 // pools specified in PoolDescs when modifying data structure nodes specified in
1046 // the PoolDescs map.  Specifically, scalar values specified in the Scalars
1047 // vector must be remapped.  IPFGraph is the closed data structure graph for F,
1048 // of which the PoolDescriptor nodes come from.
1049 //
1050 void PoolAllocate::transformFunctionBody(Function *F, FunctionDSGraph &IPFGraph,
1051                                          map<DSNode*, PoolInfo> &PoolDescs) {
1052
1053   // Loop through the value map looking for scalars that refer to nonescaping
1054   // allocations.  Add them to the Scalars vector.  Note that we may have
1055   // multiple entries in the Scalars vector for each value if it points to more
1056   // than one object.
1057   //
1058   map<Value*, PointerValSet> &ValMap = IPFGraph.getValueMap();
1059   vector<ScalarInfo> Scalars;
1060
1061 #ifdef DEBUG_TRANSFORM_PROGRESS
1062   cerr << "Building scalar map:\n";
1063 #endif
1064
1065   for (map<Value*, PointerValSet>::iterator I = ValMap.begin(),
1066          E = ValMap.end(); I != E; ++I) {
1067     const PointerValSet &PVS = I->second;  // Set of things pointed to by scalar
1068
1069     // Check to see if the scalar points to a data structure node...
1070     for (unsigned i = 0, e = PVS.size(); i != e; ++i) {
1071       assert(PVS[i].Index == 0 && "Nonzero not handled yet!");
1072         
1073       // If the allocation is in the nonescaping set...
1074       map<DSNode*, PoolInfo>::iterator AI = PoolDescs.find(PVS[i].Node);
1075       if (AI != PoolDescs.end()) {              // Add it to the list of scalars
1076         Scalars.push_back(ScalarInfo(I->first, AI->second));
1077 #ifdef DEBUG_TRANSFORM_PROGRESS
1078         cerr << "\nScalar Mapping from:" << I->first
1079              << "Scalar Mapping to: "; PVS.print(cerr);
1080 #endif
1081       }
1082     }
1083   }
1084
1085 #ifdef DEBUG_TRANSFORM_PROGRESS
1086   cerr << "\nIn '" << F->getName()
1087        << "': Found the following values that point to poolable nodes:\n";
1088
1089   for (unsigned i = 0, e = Scalars.size(); i != e; ++i)
1090     cerr << Scalars[i].Val;
1091   cerr << "\n";
1092 #endif
1093
1094   // CallMap - Contain an entry for every call instruction that needs to be
1095   // transformed.  Each entry in the map contains information about what we need
1096   // to do to each call site to change it to work.
1097   //
1098   map<CallInst*, TransformFunctionInfo> CallMap;
1099
1100   // Now we need to figure out what called functions we need to transform, and
1101   // how.  To do this, we look at all of the scalars, seeing which functions are
1102   // either used as a scalar value (so they return a data structure), or are
1103   // passed one of our scalar values.
1104   //
1105   for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1106     Value *ScalarVal = Scalars[i].Val;
1107
1108     // Check to see if the scalar _IS_ a call...
1109     if (CallInst *CI = dyn_cast<CallInst>(ScalarVal))
1110       // If so, add information about the pool it will be returning...
1111       CallMap[CI].addCallInfo(DS, CI, -1, Scalars[i].Pool.Node, PoolDescs);
1112
1113     // Check to see if the scalar is an operand to a call...
1114     for (Value::use_iterator UI = ScalarVal->use_begin(),
1115            UE = ScalarVal->use_end(); UI != UE; ++UI) {
1116       if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1117         // Find out which operand this is to the call instruction...
1118         User::op_iterator OI = find(CI->op_begin(), CI->op_end(), ScalarVal);
1119         assert(OI != CI->op_end() && "Call on use list but not an operand!?");
1120         assert(OI != CI->op_begin() && "Pointer operand is call destination?");
1121
1122         // FIXME: This is broken if the same pointer is passed to a call more
1123         // than once!  It will get multiple entries for the first pointer.
1124
1125         // Add the operand number and pool handle to the call table...
1126         CallMap[CI].addCallInfo(DS, CI, OI-CI->op_begin()-1,
1127                                 Scalars[i].Pool.Node, PoolDescs);
1128       }
1129     }
1130   }
1131
1132   // Make sure that all dependant arguments are added as well.  For example, if
1133   // we call foo(null, P) and foo treats it's first and second arguments as
1134   // belonging to the same data structure, the we MUST set up the CallMap to
1135   // know that the null needs to be transformed into an index as well.
1136   //
1137   for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1138        I != CallMap.end(); ++I)
1139     I->second.ensureDependantArgumentsIncluded(DS, PoolDescs);
1140
1141 #ifdef DEBUG_TRANSFORM_PROGRESS
1142   // Print out call map...
1143   for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin();
1144        I != CallMap.end(); ++I) {
1145     cerr << "For call: " << I->first;
1146     cerr << I->second.Func->getName() << " must pass pool pointer for args #";
1147     for (unsigned i = 0; i < I->second.ArgInfo.size(); ++i)
1148       cerr << I->second.ArgInfo[i].ArgNo << ", ";
1149     cerr << "\n\n";
1150   }
1151 #endif
1152
1153   // Loop through all of the call nodes, recursively creating the new functions
1154   // that we want to call...  This uses a map to prevent infinite recursion and
1155   // to avoid duplicating functions unneccesarily.
1156   //
1157   for (map<CallInst*, TransformFunctionInfo>::iterator I = CallMap.begin(),
1158          E = CallMap.end(); I != E; ++I) {
1159     // Transform all of the functions we need, or at least ensure there is a
1160     // cached version available.
1161     transformFunction(I->second, IPFGraph, PoolDescs);
1162   }
1163
1164   // Now that all of the functions that we want to call are available, transform
1165   // the local function so that it uses the pools locally and passes them to the
1166   // functions that we just hacked up.
1167   //
1168
1169   // First step, find the instructions to be modified.
1170   vector<Instruction*> InstToFix;
1171   for (unsigned i = 0, e = Scalars.size(); i != e; ++i) {
1172     Value *ScalarVal = Scalars[i].Val;
1173
1174     // Check to see if the scalar _IS_ an instruction.  If so, it is involved.
1175     if (Instruction *Inst = dyn_cast<Instruction>(ScalarVal))
1176       InstToFix.push_back(Inst);
1177
1178     // All all of the instructions that use the scalar as an operand...
1179     for (Value::use_iterator UI = ScalarVal->use_begin(),
1180            UE = ScalarVal->use_end(); UI != UE; ++UI)
1181       InstToFix.push_back(cast<Instruction>(*UI));
1182   }
1183
1184   // Make sure that we get return instructions that return a null value from the
1185   // function...
1186   //
1187   if (!IPFGraph.getRetNodes().empty()) {
1188     assert(IPFGraph.getRetNodes().size() == 1 && "Can only return one node?");
1189     PointerVal RetNode = IPFGraph.getRetNodes()[0];
1190     assert(RetNode.Index == 0 && "Subindexing not implemented yet!");
1191
1192     // Only process return instructions if the return value of this function is
1193     // part of one of the data structures we are transforming...
1194     //
1195     if (PoolDescs.count(RetNode.Node)) {
1196       // Loop over all of the basic blocks, adding return instructions...
1197       for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1198         if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator()))
1199           InstToFix.push_back(RI);
1200     }
1201   }
1202
1203
1204
1205   // Eliminate duplicates by sorting, then removing equal neighbors.
1206   sort(InstToFix.begin(), InstToFix.end());
1207   InstToFix.erase(unique(InstToFix.begin(), InstToFix.end()), InstToFix.end());
1208
1209   // Loop over all of the instructions to transform, creating the new
1210   // replacement instructions for them.  This also unlinks them from the
1211   // function so they can be safely deleted later.
1212   //
1213   map<Value*, Value*> XFormMap;  
1214   NewInstructionCreator NIC(*this, Scalars, CallMap, XFormMap);
1215
1216   // Visit all instructions... creating the new instructions that we need and
1217   // unlinking the old instructions from the function...
1218   //
1219 #ifdef DEBUG_TRANSFORM_PROGRESS
1220   for (unsigned i = 0, e = InstToFix.size(); i != e; ++i) {
1221     cerr << "Fixing: " << InstToFix[i];
1222     NIC.visit(InstToFix[i]);
1223   }
1224 #else
1225   NIC.visit(InstToFix.begin(), InstToFix.end());
1226 #endif
1227
1228   // Make all instructions we will delete "let go" of their operands... so that
1229   // we can safely delete Arguments whose types have changed...
1230   //
1231   for_each(InstToFix.begin(), InstToFix.end(),
1232            mem_fun(&Instruction::dropAllReferences));
1233
1234   // Loop through all of the pointer arguments coming into the function,
1235   // replacing them with arguments of POINTERTYPE to match the function type of
1236   // the function.
1237   //
1238   FunctionType::ParamTypes::const_iterator TI =
1239     F->getFunctionType()->getParamTypes().begin();
1240   for (Function::ArgumentListType::iterator I = F->getArgumentList().begin(),
1241          E = F->getArgumentList().end(); I != E; ++I, ++TI) {
1242     Argument *Arg = *I;
1243     if (Arg->getType() != *TI) {
1244       assert(isa<PointerType>(Arg->getType()) && *TI == POINTERTYPE);
1245       Argument *NewArg = new Argument(*TI, Arg->getName());
1246       XFormMap[Arg] = NewArg;  // Map old arg into new arg...
1247
1248       // Replace the old argument and then delete it...
1249       delete F->getArgumentList().replaceWith(I, NewArg);
1250     }
1251   }
1252
1253   // Now that all of the new instructions have been created, we can update all
1254   // of the references to dummy values to be references to the actual values
1255   // that are computed.
1256   //
1257   NIC.updateReferences();
1258
1259 #ifdef DEBUG_TRANSFORM_PROGRESS
1260   cerr << "TRANSFORMED FUNCTION:\n" << F;
1261 #endif
1262
1263   // Delete all of the "instructions to fix"
1264   for_each(InstToFix.begin(), InstToFix.end(), deleter<Instruction>);
1265
1266   // Eliminate pool base loads that we can easily prove are redundant
1267   if (!DisableRLE)
1268     PoolBaseLoadEliminator(PoolDescs).visit(F);
1269
1270   // Since we have liberally hacked the function to pieces, we want to inform
1271   // the datastructure pass that its internal representation is out of date.
1272   //
1273   DS->invalidateFunction(F);
1274 }
1275
1276
1277
1278 // transformFunction - Transform the specified function the specified way.  It
1279 // we have already transformed that function that way, don't do anything.  The
1280 // nodes in the TransformFunctionInfo come out of callers data structure graph.
1281 //
1282 void PoolAllocate::transformFunction(TransformFunctionInfo &TFI,
1283                                      FunctionDSGraph &CallerIPGraph,
1284                                      map<DSNode*, PoolInfo> &CallerPoolDesc) {
1285   if (getTransformedFunction(TFI)) return;  // Function xformation already done?
1286
1287 #ifdef DEBUG_TRANSFORM_PROGRESS
1288   cerr << "********** Entering transformFunction for "
1289        << TFI.Func->getName() << ":\n";
1290   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i)
1291     cerr << "  ArgInfo[" << i << "] = " << TFI.ArgInfo[i].ArgNo << "\n";
1292   cerr << "\n";
1293 #endif
1294
1295   const FunctionType *OldFuncType = TFI.Func->getFunctionType();
1296
1297   assert(!OldFuncType->isVarArg() && "Vararg functions not handled yet!");
1298
1299   // Build the type for the new function that we are transforming
1300   vector<const Type*> ArgTys;
1301   ArgTys.reserve(OldFuncType->getNumParams()+TFI.ArgInfo.size());
1302   for (unsigned i = 0, e = OldFuncType->getNumParams(); i != e; ++i)
1303     ArgTys.push_back(OldFuncType->getParamType(i));
1304
1305   const Type *RetType = OldFuncType->getReturnType();
1306   
1307   // Add one pool pointer for every argument that needs to be supplemented.
1308   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1309     if (TFI.ArgInfo[i].ArgNo == -1)
1310       RetType = POINTERTYPE;  // Return a pointer
1311     else
1312       ArgTys[TFI.ArgInfo[i].ArgNo] = POINTERTYPE; // Pass a pointer
1313     ArgTys.push_back(PointerType::get(CallerPoolDesc.find(TFI.ArgInfo[i].Node)
1314                                         ->second.PoolType));
1315   }
1316
1317   // Build the new function type...
1318   const FunctionType *NewFuncType = FunctionType::get(RetType, ArgTys,
1319                                                       OldFuncType->isVarArg());
1320
1321   // The new function is internal, because we know that only we can call it.
1322   // This also helps subsequent IP transformations to eliminate duplicated pool
1323   // pointers (which look like the same value is always passed into a parameter,
1324   // allowing it to be easily eliminated).
1325   //
1326   Function *NewFunc = new Function(NewFuncType, true,
1327                                    TFI.Func->getName()+".poolxform");
1328   CurModule->getFunctionList().push_back(NewFunc);
1329
1330
1331 #ifdef DEBUG_TRANSFORM_PROGRESS
1332   cerr << "Created function prototype: " << NewFunc << "\n";
1333 #endif
1334
1335   // Add the newly formed function to the TransformedFunctions table so that
1336   // infinite recursion does not occur!
1337   //
1338   TransformedFunctions[TFI] = NewFunc;
1339
1340   // Add arguments to the function... starting with all of the old arguments
1341   vector<Value*> ArgMap;
1342   for (unsigned i = 0, e = TFI.Func->getArgumentList().size(); i != e; ++i) {
1343     const Argument *OFA = TFI.Func->getArgumentList()[i];
1344     Argument *NFA = new Argument(OFA->getType(), OFA->getName());
1345     NewFunc->getArgumentList().push_back(NFA);
1346     ArgMap.push_back(NFA);  // Keep track of the arguments 
1347   }
1348
1349   // Now add all of the arguments corresponding to pools passed in...
1350   for (unsigned i = 0, e = TFI.ArgInfo.size(); i != e; ++i) {
1351     CallArgInfo &AI = TFI.ArgInfo[i];
1352     string Name;
1353     if (AI.ArgNo == -1)
1354       Name = "ret";
1355     else
1356       Name = ArgMap[AI.ArgNo]->getName();  // Get the arg name
1357     const Type *Ty = PointerType::get(CallerPoolDesc[AI.Node].PoolType);
1358     Argument *NFA = new Argument(Ty, Name+".pool");
1359     NewFunc->getArgumentList().push_back(NFA);
1360   }
1361
1362   // Now clone the body of the old function into the new function...
1363   CloneFunctionInto(NewFunc, TFI.Func, ArgMap);
1364   
1365   // Okay, now we have a function that is identical to the old one, except that
1366   // it has extra arguments for the pools coming in.  Now we have to get the 
1367   // data structure graph for the function we are replacing, and figure out how
1368   // our graph nodes map to the graph nodes in the dest function.
1369   //
1370   FunctionDSGraph &DSGraph = DS->getClosedDSGraph(NewFunc);  
1371
1372   // NodeMapping - Multimap from callers graph to called graph.  We are
1373   // guaranteed that the called function graph has more nodes than the caller,
1374   // or exactly the same number of nodes.  This is because the called function
1375   // might not know that two nodes are merged when considering the callers
1376   // context, but the caller obviously does.  Because of this, a single node in
1377   // the calling function's data structure graph can map to multiple nodes in
1378   // the called functions graph.
1379   //
1380   map<DSNode*, PointerValSet> NodeMapping;
1381
1382   CalculateNodeMapping(NewFunc, TFI, CallerIPGraph, DSGraph, 
1383                        NodeMapping);
1384
1385   // Print out the node mapping...
1386 #ifdef DEBUG_TRANSFORM_PROGRESS
1387   cerr << "\nNode mapping for call of " << NewFunc->getName() << "\n";
1388   for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1389        I != NodeMapping.end(); ++I) {
1390     cerr << "Map: "; I->first->print(cerr);
1391     cerr << "To:  "; I->second.print(cerr);
1392     cerr << "\n";
1393   }
1394 #endif
1395
1396   // Fill in the PoolDescriptor information for the transformed function so that
1397   // it can determine which value holds the pool descriptor for each data
1398   // structure node that it accesses.
1399   //
1400   map<DSNode*, PoolInfo> PoolDescs;
1401
1402 #ifdef DEBUG_TRANSFORM_PROGRESS
1403   cerr << "\nCalculating the pool descriptor map:\n";
1404 #endif
1405
1406   // Calculate as much of the pool descriptor map as possible.  Since we have
1407   // the node mapping between the caller and callee functions, and we have the
1408   // pool descriptor information of the caller, we can calculate a partical pool
1409   // descriptor map for the called function.
1410   //
1411   // The nodes that we do not have complete information for are the ones that
1412   // are accessed by loading pointers derived from arguments passed in, but that
1413   // are not passed in directly.  In this case, we have all of the information
1414   // except a pool value.  If the called function refers to this pool, the pool
1415   // value will be loaded from the pool graph and added to the map as neccesary.
1416   //
1417   for (map<DSNode*, PointerValSet>::iterator I = NodeMapping.begin();
1418        I != NodeMapping.end(); ++I) {
1419     DSNode *CallerNode = I->first;
1420     PoolInfo &CallerPI = CallerPoolDesc[CallerNode];
1421
1422     // Check to see if we have a node pointer passed in for this value...
1423     Value *CalleeValue = 0;
1424     for (unsigned a = 0, ae = TFI.ArgInfo.size(); a != ae; ++a)
1425       if (TFI.ArgInfo[a].Node == CallerNode) {
1426         // Calculate the argument number that the pool is to the function
1427         // call...  The call instruction should not have the pool operands added
1428         // yet.
1429         unsigned ArgNo = TFI.Call->getNumOperands()-1+a;
1430 #ifdef DEBUG_TRANSFORM_PROGRESS
1431         cerr << "Should be argument #: " << ArgNo << "[i = " << a << "]\n";
1432 #endif
1433         assert(ArgNo < NewFunc->getArgumentList().size() &&
1434                "Call already has pool arguments added??");
1435
1436         // Map the pool argument into the called function...
1437         CalleeValue = NewFunc->getArgumentList()[ArgNo];
1438         break;  // Found value, quit loop
1439       }
1440
1441     // Loop over all of the data structure nodes that this incoming node maps to
1442     // Creating a PoolInfo structure for them.
1443     for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
1444       assert(I->second[i].Index == 0 && "Doesn't handle subindexing yet!");
1445       DSNode *CalleeNode = I->second[i].Node;
1446      
1447       // Add the descriptor.  We already know everything about it by now, much
1448       // of it is the same as the caller info.
1449       // 
1450       PoolDescs.insert(make_pair(CalleeNode,
1451                                  PoolInfo(CalleeNode, CalleeValue,
1452                                           CallerPI.NewType,
1453                                           CallerPI.PoolType)));
1454     }
1455   }
1456
1457   // We must destroy the node mapping so that we don't have latent references
1458   // into the data structure graph for the new function.  Otherwise we get
1459   // assertion failures when transformFunctionBody tries to invalidate the
1460   // graph.
1461   //
1462   NodeMapping.clear();
1463
1464   // Now that we know everything we need about the function, transform the body
1465   // now!
1466   //
1467   transformFunctionBody(NewFunc, DSGraph, PoolDescs);
1468   
1469 #ifdef DEBUG_TRANSFORM_PROGRESS
1470   cerr << "Function after transformation:\n" << NewFunc;
1471 #endif
1472 }
1473
1474 static unsigned countPointerTypes(const Type *Ty) {
1475   if (isa<PointerType>(Ty)) {
1476     return 1;
1477   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1478     unsigned Num = 0;
1479     for (unsigned i = 0, e = STy->getElementTypes().size(); i != e; ++i)
1480       Num += countPointerTypes(STy->getElementTypes()[i]);
1481     return Num;
1482   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1483     return countPointerTypes(ATy->getElementType());
1484   } else {
1485     assert(Ty->isPrimitiveType() && "Unknown derived type!");
1486     return 0;
1487   }
1488 }
1489
1490 // CreatePools - Insert instructions into the function we are processing to
1491 // create all of the memory pool objects themselves.  This also inserts
1492 // destruction code.  Add an alloca for each pool that is allocated to the
1493 // PoolDescs vector.
1494 //
1495 void PoolAllocate::CreatePools(Function *F, const vector<AllocDSNode*> &Allocs,
1496                                map<DSNode*, PoolInfo> &PoolDescs) {
1497   // Find all of the return nodes in the function...
1498   vector<BasicBlock*> ReturnNodes;
1499   for (Function::iterator I = F->begin(), E = F->end(); I != E; ++I)
1500     if (isa<ReturnInst>((*I)->getTerminator()))
1501       ReturnNodes.push_back(*I);
1502
1503 #ifdef DEBUG_CREATE_POOLS
1504   cerr << "Allocs that we are pool allocating:\n";
1505   for (unsigned i = 0, e = Allocs.size(); i != e; ++i)
1506     Allocs[i]->dump();
1507 #endif
1508
1509   map<DSNode*, PATypeHolder> AbsPoolTyMap;
1510
1511   // First pass over the allocations to process...
1512   for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1513     // Create the pooldescriptor mapping... with null entries for everything
1514     // except the node & NewType fields.
1515     //
1516     map<DSNode*, PoolInfo>::iterator PI =
1517       PoolDescs.insert(make_pair(Allocs[i], PoolInfo(Allocs[i]))).first;
1518
1519     // Add a symbol table entry for the new type if there was one for the old
1520     // type...
1521     string OldName = CurModule->getTypeName(Allocs[i]->getType());
1522     if (!OldName.empty())
1523       CurModule->addTypeName(OldName+".p", PI->second.NewType);
1524
1525     // Create the abstract pool types that will need to be resolved in a second
1526     // pass once an abstract type is created for each pool.
1527     //
1528     // Can only handle limited shapes for now...
1529     StructType *OldNodeTy = cast<StructType>(Allocs[i]->getType());
1530     vector<const Type*> PoolTypes;
1531
1532     // Pool type is the first element of the pool descriptor type...
1533     PoolTypes.push_back(getPoolType(PoolDescs[Allocs[i]].NewType));
1534
1535     unsigned NumPointers = countPointerTypes(OldNodeTy);
1536     while (NumPointers--)   // Add a different opaque type for each pointer
1537       PoolTypes.push_back(OpaqueType::get());
1538
1539     assert(Allocs[i]->getNumLinks() == PoolTypes.size()-1 &&
1540            "Node should have same number of pointers as pool!");
1541
1542     StructType *PoolType = StructType::get(PoolTypes);
1543
1544     // Add a symbol table entry for the pooltype if possible...
1545     if (!OldName.empty()) CurModule->addTypeName(OldName+".pool", PoolType);
1546
1547     // Create the pool type, with opaque values for pointers...
1548     AbsPoolTyMap.insert(make_pair(Allocs[i], PoolType));
1549 #ifdef DEBUG_CREATE_POOLS
1550     cerr << "POOL TY: " << AbsPoolTyMap.find(Allocs[i])->second.get() << "\n";
1551 #endif
1552   }
1553   
1554   // Now that we have types for all of the pool types, link them all together.
1555   for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1556     PATypeHolder &PoolTyH = AbsPoolTyMap.find(Allocs[i])->second;
1557
1558     // Resolve all of the outgoing pointer types of this pool node...
1559     for (unsigned p = 0, pe = Allocs[i]->getNumLinks(); p != pe; ++p) {
1560       PointerValSet &PVS = Allocs[i]->getLink(p);
1561       assert(!PVS.empty() && "Outgoing edge is empty, field unused, can"
1562              " probably just leave the type opaque or something dumb.");
1563       unsigned Out;
1564       for (Out = 0; AbsPoolTyMap.count(PVS[Out].Node) == 0; ++Out)
1565         assert(Out != PVS.size() && "No edge to an outgoing allocation node!?");
1566       
1567       assert(PVS[Out].Index == 0 && "Subindexing not implemented yet!");
1568
1569       // The actual struct type could change each time through the loop, so it's
1570       // NOT loop invariant.
1571       StructType *PoolTy = cast<StructType>(PoolTyH.get());
1572
1573       // Get the opaque type...
1574       DerivedType *ElTy =
1575         cast<DerivedType>(PoolTy->getElementTypes()[p+1].get());
1576
1577 #ifdef DEBUG_CREATE_POOLS
1578       cerr << "Refining " << ElTy << " of " << PoolTy << " to "
1579            << AbsPoolTyMap.find(PVS[Out].Node)->second.get() << "\n";
1580 #endif
1581
1582       const Type *RefPoolTy = AbsPoolTyMap.find(PVS[Out].Node)->second.get();
1583       ElTy->refineAbstractTypeTo(PointerType::get(RefPoolTy));
1584
1585 #ifdef DEBUG_CREATE_POOLS
1586       cerr << "Result pool type is: " << PoolTyH.get() << "\n";
1587 #endif
1588     }
1589   }
1590
1591   // Create the code that goes in the entry and exit nodes for the function...
1592   vector<Instruction*> EntryNodeInsts;
1593   for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1594     PoolInfo &PI = PoolDescs[Allocs[i]];
1595     
1596     // Fill in the pool type for this pool...
1597     PI.PoolType = AbsPoolTyMap.find(Allocs[i])->second.get();
1598     assert(!PI.PoolType->isAbstract() &&
1599            "Pool type should not be abstract anymore!");
1600
1601     // Add an allocation and a free for each pool...
1602     AllocaInst *PoolAlloc
1603       = new AllocaInst(PointerType::get(PI.PoolType), 0,
1604                        CurModule->getTypeName(PI.PoolType));
1605     PI.Handle = PoolAlloc;
1606     EntryNodeInsts.push_back(PoolAlloc);
1607     AllocationInst *AI = Allocs[i]->getAllocation();
1608
1609     // Initialize the pool.  We need to know how big each allocation is.  For
1610     // our purposes here, we assume we are allocating a scalar, or array of
1611     // constant size.
1612     //
1613     unsigned ElSize = TargetData.getTypeSize(PI.NewType);
1614
1615     vector<Value*> Args;
1616     Args.push_back(ConstantUInt::get(Type::UIntTy, ElSize));
1617     Args.push_back(PoolAlloc);    // Pool to initialize
1618     EntryNodeInsts.push_back(new CallInst(PoolInit, Args));
1619
1620     // Add code to destroy the pool in all of the exit nodes of the function...
1621     Args.clear();
1622     Args.push_back(PoolAlloc);    // Pool to initialize
1623     
1624     for (unsigned EN = 0, ENE = ReturnNodes.size(); EN != ENE; ++EN) {
1625       Instruction *Destroy = new CallInst(PoolDestroy, Args);
1626
1627       // Insert it before the return instruction...
1628       BasicBlock *RetNode = ReturnNodes[EN];
1629       RetNode->getInstList().insert(RetNode->end()-1, Destroy);
1630     }
1631   }
1632
1633   // Now that all of the pool descriptors have been created, link them together
1634   // so that called functions can get links as neccesary...
1635   //
1636   for (unsigned i = 0, e = Allocs.size(); i != e; ++i) {
1637     PoolInfo &PI = PoolDescs[Allocs[i]];
1638
1639     // For every pointer in the data structure, initialize a link that
1640     // indicates which pool to access...
1641     //
1642     vector<Value*> Indices(2);
1643     Indices[0] = ConstantUInt::get(Type::UIntTy, 0);
1644     for (unsigned l = 0, le = PI.Node->getNumLinks(); l != le; ++l)
1645       // Only store an entry for the field if the field is used!
1646       if (!PI.Node->getLink(l).empty()) {
1647         assert(PI.Node->getLink(l).size() == 1 && "Should have only one link!");
1648         PointerVal PV = PI.Node->getLink(l)[0];
1649         assert(PV.Index == 0 && "Subindexing not supported yet!");
1650         PoolInfo &LinkedPool = PoolDescs[PV.Node];
1651         Indices[1] = ConstantUInt::get(Type::UByteTy, 1+l);
1652       
1653         EntryNodeInsts.push_back(new StoreInst(LinkedPool.Handle, PI.Handle,
1654                                                Indices));
1655       }
1656   }
1657
1658   // Insert the entry node code into the entry block...
1659   F->getEntryNode()->getInstList().insert(F->getEntryNode()->begin()+1,
1660                                           EntryNodeInsts.begin(),
1661                                           EntryNodeInsts.end());
1662 }
1663
1664
1665 // addPoolPrototypes - Add prototypes for the pool functions to the specified
1666 // module and update the Pool* instance variables to point to them.
1667 //
1668 void PoolAllocate::addPoolPrototypes(Module *M) {
1669   // Get poolinit function...
1670   vector<const Type*> Args;
1671   Args.push_back(Type::UIntTy);     // Num bytes per element
1672   FunctionType *PoolInitTy = FunctionType::get(Type::VoidTy, Args, true);
1673   PoolInit = M->getOrInsertFunction("poolinit", PoolInitTy);
1674
1675   // Get pooldestroy function...
1676   Args.pop_back();  // Only takes a pool...
1677   FunctionType *PoolDestroyTy = FunctionType::get(Type::VoidTy, Args, true);
1678   PoolDestroy = M->getOrInsertFunction("pooldestroy", PoolDestroyTy);
1679
1680   // Get the poolalloc function...
1681   FunctionType *PoolAllocTy = FunctionType::get(POINTERTYPE, Args, true);
1682   PoolAlloc = M->getOrInsertFunction("poolalloc", PoolAllocTy);
1683
1684   // Get the poolfree function...
1685   Args.push_back(POINTERTYPE);       // Pointer to free
1686   FunctionType *PoolFreeTy = FunctionType::get(Type::VoidTy, Args, true);
1687   PoolFree = M->getOrInsertFunction("poolfree", PoolFreeTy);
1688
1689   // Add the %PoolTy type to the symbol table of the module...
1690   //M->addTypeName("PoolTy", PoolTy->getElementType());
1691 }
1692
1693
1694 bool PoolAllocate::run(Module *M) {
1695   addPoolPrototypes(M);
1696   CurModule = M;
1697   
1698   DS = &getAnalysis<DataStructure>();
1699   bool Changed = false;
1700
1701   // We cannot use an iterator here because it will get invalidated when we add
1702   // functions to the module later...
1703   for (unsigned i = 0; i != M->size(); ++i)
1704     if (!M->getFunctionList()[i]->isExternal()) {
1705       Changed |= processFunction(M->getFunctionList()[i]);
1706       if (Changed) {
1707         cerr << "Only processing one function\n";
1708         break;
1709       }
1710     }
1711
1712   CurModule = 0;
1713   DS = 0;
1714   return false;
1715 }
1716
1717
1718 // createPoolAllocatePass - Global function to access the functionality of this
1719 // pass...
1720 //
1721 Pass *createPoolAllocatePass() { return new PoolAllocate(); }