Eliminate duplicate or unneccesary #include's
[oota-llvm.git] / lib / Transforms / Utils / LowerAllocations.cpp
1 //===- ChangeAllocations.cpp - Modify %malloc & %free calls -----------------=//
2 //
3 // This file defines two passes that convert malloc and free instructions to
4 // calls to and from %malloc & %free function calls.  The LowerAllocations
5 // transformation is a target dependant tranformation because it depends on the
6 // size of data types and alignment constraints.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Transforms/ChangeAllocations.h"
11 #include "llvm/Module.h"
12 #include "llvm/Function.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/iMemory.h"
15 #include "llvm/iOther.h"
16 #include "llvm/Pass.h"
17 #include "TransformInternals.h"
18 using std::vector;
19
20 namespace {
21
22 // LowerAllocations - Turn malloc and free instructions into %malloc and %free
23 // calls.
24 //
25 class LowerAllocations : public BasicBlockPass {
26   Function *MallocFunc;   // Functions in the module we are processing
27   Function *FreeFunc;     // Initialized by doInitialization
28
29   const TargetData &DataLayout;
30 public:
31   inline LowerAllocations(const TargetData &TD) : DataLayout(TD) {
32     MallocFunc = FreeFunc = 0;
33   }
34
35   const char *getPassName() const { return "Lower Allocations"; }
36
37   // doPassInitialization - For the lower allocations pass, this ensures that a
38   // module contains a declaration for a malloc and a free function.
39   //
40   bool doInitialization(Module *M);
41
42   // runOnBasicBlock - This method does the actual work of converting
43   // instructions over, assuming that the pass has already been initialized.
44   //
45   bool runOnBasicBlock(BasicBlock *BB);
46 };
47
48 // RaiseAllocations - Turn %malloc and %free calls into the appropriate
49 // instruction.
50 //
51 class RaiseAllocations : public BasicBlockPass {
52   Function *MallocFunc;   // Functions in the module we are processing
53   Function *FreeFunc;     // Initialized by doPassInitializationVirt
54 public:
55   inline RaiseAllocations() : MallocFunc(0), FreeFunc(0) {}
56
57   const char *getPassName() const { return "Raise Allocations"; }
58
59   // doPassInitialization - For the raise allocations pass, this finds a
60   // declaration for malloc and free if they exist.
61   //
62   bool doInitialization(Module *M);
63
64   // runOnBasicBlock - This method does the actual work of converting
65   // instructions over, assuming that the pass has already been initialized.
66   //
67   bool runOnBasicBlock(BasicBlock *BB);
68 };
69
70 }  // end anonymous namespace
71
72 // doInitialization - For the lower allocations pass, this ensures that a
73 // module contains a declaration for a malloc and a free function.
74 //
75 // This function is always successful.
76 //
77 bool LowerAllocations::doInitialization(Module *M) {
78   const FunctionType *MallocType = 
79     FunctionType::get(PointerType::get(Type::SByteTy),
80                       vector<const Type*>(1, Type::UIntTy), false);
81   const FunctionType *FreeType = 
82     FunctionType::get(Type::VoidTy,
83                       vector<const Type*>(1, PointerType::get(Type::SByteTy)),
84                       false);
85
86   MallocFunc = M->getOrInsertFunction("malloc", MallocType);
87   FreeFunc   = M->getOrInsertFunction("free"  , FreeType);
88
89   return false;
90 }
91
92 // runOnBasicBlock - This method does the actual work of converting
93 // instructions over, assuming that the pass has already been initialized.
94 //
95 bool LowerAllocations::runOnBasicBlock(BasicBlock *BB) {
96   bool Changed = false;
97   assert(MallocFunc && FreeFunc && BB && "Pass not initialized!");
98
99   // Loop over all of the instructions, looking for malloc or free instructions
100   for (unsigned i = 0; i < BB->size(); ++i) {
101     BasicBlock::InstListType &BBIL = BB->getInstList();
102     if (MallocInst *MI = dyn_cast<MallocInst>(*(BBIL.begin()+i))) {
103       BBIL.remove(BBIL.begin()+i);   // remove the malloc instr...
104         
105       const Type *AllocTy =cast<PointerType>(MI->getType())->getElementType();
106       
107       // Get the number of bytes to be allocated for one element of the
108       // requested type...
109       unsigned Size = DataLayout.getTypeSize(AllocTy);
110       
111       // malloc(type) becomes sbyte *malloc(constint)
112       Value *MallocArg = ConstantUInt::get(Type::UIntTy, Size);
113       if (MI->getNumOperands() && Size == 1) {
114         MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
115       } else if (MI->getNumOperands()) {
116         // Multiply it by the array size if neccesary...
117         MallocArg = BinaryOperator::create(Instruction::Mul,MI->getOperand(0),
118                                            MallocArg);
119         BBIL.insert(BBIL.begin()+i++, cast<Instruction>(MallocArg));
120       }
121       
122       // Create the call to Malloc...
123       CallInst *MCall = new CallInst(MallocFunc,
124                                      vector<Value*>(1, MallocArg));
125       BBIL.insert(BBIL.begin()+i, MCall);
126       
127       // Create a cast instruction to convert to the right type...
128       CastInst *MCast = new CastInst(MCall, MI->getType());
129       BBIL.insert(BBIL.begin()+i+1, MCast);
130       
131       // Replace all uses of the old malloc inst with the cast inst
132       MI->replaceAllUsesWith(MCast);
133       delete MI;                          // Delete the malloc inst
134       Changed = true;
135     } else if (FreeInst *FI = dyn_cast<FreeInst>(*(BBIL.begin()+i))) {
136       BBIL.remove(BB->getInstList().begin()+i);
137       
138       // Cast the argument to free into a ubyte*...
139       CastInst *MCast = new CastInst(FI->getOperand(0), 
140                                      PointerType::get(Type::UByteTy));
141       BBIL.insert(BBIL.begin()+i, MCast);
142       
143       // Insert a call to the free function...
144       CallInst *FCall = new CallInst(FreeFunc,
145                                      vector<Value*>(1, MCast));
146       BBIL.insert(BBIL.begin()+i+1, FCall);
147       
148       // Delete the old free instruction
149       delete FI;
150       Changed = true;
151     }
152   }
153
154   return Changed;
155 }
156
157 bool RaiseAllocations::doInitialization(Module *M) {
158   // If the module has a symbol table, they might be referring to the malloc
159   // and free functions.  If this is the case, grab the method pointers that 
160   // the module is using.
161   //
162   // Lookup %malloc and %free in the symbol table, for later use.  If they
163   // don't exist, or are not external, we do not worry about converting calls
164   // to that function into the appropriate instruction.
165   //
166   const FunctionType *MallocType =   // Get the type for malloc
167     FunctionType::get(PointerType::get(Type::SByteTy),
168                       vector<const Type*>(1, Type::UIntTy), false);
169
170   const FunctionType *FreeType =     // Get the type for free
171     FunctionType::get(Type::VoidTy,
172                       vector<const Type*>(1, PointerType::get(Type::SByteTy)),
173                       false);
174
175   MallocFunc = M->getFunction("malloc", MallocType);
176   FreeFunc   = M->getFunction("free"  , FreeType);
177
178   // Don't mess with locally defined versions of these functions...
179   if (MallocFunc && !MallocFunc->isExternal()) MallocFunc = 0;
180   if (FreeFunc && !FreeFunc->isExternal())     FreeFunc = 0;
181   return false;
182 }
183
184 // doOneCleanupPass - Do one pass over the input method, fixing stuff up.
185 //
186 bool RaiseAllocations::runOnBasicBlock(BasicBlock *BB) {
187   bool Changed = false;
188   BasicBlock::InstListType &BIL = BB->getInstList();
189
190   for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
191     Instruction *I = *BI;
192
193     if (CallInst *CI = dyn_cast<CallInst>(I)) {
194       if (CI->getCalledValue() == MallocFunc) {      // Replace call to malloc?
195         const Type *PtrSByte = PointerType::get(Type::SByteTy);
196         MallocInst *MallocI = new MallocInst(PtrSByte, CI->getOperand(1),
197                                              CI->getName());
198         CI->setName("");
199         ReplaceInstWithInst(BIL, BI, MallocI);
200         Changed = true;
201         continue;  // Skip the ++BI
202       } else if (CI->getCalledValue() == FreeFunc) { // Replace call to free?
203         ReplaceInstWithInst(BIL, BI, new FreeInst(CI->getOperand(1)));
204         Changed = true;
205         continue;  // Skip the ++BI
206       }
207     }
208
209     ++BI;
210   }
211
212   return Changed;
213 }
214
215 Pass *createLowerAllocationsPass(const TargetData &TD) {
216   return new LowerAllocations(TD);
217 }
218 Pass *createRaiseAllocationsPass() {
219   return new RaiseAllocations();
220 }