For PR411:
[oota-llvm.git] / lib / Transforms / IPO / RaiseAllocations.cpp
1 //===- RaiseAllocations.cpp - Convert %malloc & %free calls to insts ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the RaiseAllocations pass which convert malloc and free
11 // calls to malloc and free instructions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "raiseallocs"
16 #include "llvm/Transforms/IPO.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Support/CallSite.h"
23 #include "llvm/ADT/Statistic.h"
24 using namespace llvm;
25
26 STATISTIC(NumRaised, "Number of allocations raised");
27
28 namespace {
29   // RaiseAllocations - Turn %malloc and %free calls into the appropriate
30   // instruction.
31   //
32   class RaiseAllocations : public ModulePass {
33     Function *MallocFunc;   // Functions in the module we are processing
34     Function *FreeFunc;     // Initialized by doPassInitializationVirt
35   public:
36     RaiseAllocations() : MallocFunc(0), FreeFunc(0) {}
37
38     // doPassInitialization - For the raise allocations pass, this finds a
39     // declaration for malloc and free if they exist.
40     //
41     void doInitialization(Module &M);
42
43     // run - This method does the actual work of converting instructions over.
44     //
45     bool runOnModule(Module &M);
46   };
47
48   RegisterPass<RaiseAllocations>
49   X("raiseallocs", "Raise allocations from calls to instructions");
50 }  // end anonymous namespace
51
52
53 // createRaiseAllocationsPass - The interface to this file...
54 ModulePass *llvm::createRaiseAllocationsPass() {
55   return new RaiseAllocations();
56 }
57
58
59 // If the module has a symbol table, they might be referring to the malloc and
60 // free functions.  If this is the case, grab the method pointers that the
61 // module is using.
62 //
63 // Lookup %malloc and %free in the symbol table, for later use.  If they don't
64 // exist, or are not external, we do not worry about converting calls to that
65 // function into the appropriate instruction.
66 //
67 void RaiseAllocations::doInitialization(Module &M) {
68
69   // Get Malloc and free prototypes if they exist!
70   MallocFunc = M.getFunction("malloc");
71   if (MallocFunc) {
72     const FunctionType* TyWeHave = MallocFunc->getFunctionType();
73
74     // Get the expected prototype for malloc
75     const FunctionType *Malloc1Type = 
76       FunctionType::get(PointerType::get(Type::Int8Ty),
77                       std::vector<const Type*>(1, Type::Int64Ty), false);
78
79     // Chck to see if we got the expected malloc
80     if (TyWeHave != Malloc1Type) {
81       // Check to see if the prototype is wrong, giving us sbyte*(uint) * malloc
82       // This handles the common declaration of: 'void *malloc(unsigned);'
83       const FunctionType *Malloc2Type = 
84         FunctionType::get(PointerType::get(Type::Int8Ty),
85                           std::vector<const Type*>(1, Type::Int32Ty), false);
86       if (TyWeHave != Malloc2Type) {
87         // Check to see if the prototype is missing, giving us 
88         // sbyte*(...) * malloc
89         // This handles the common declaration of: 'void *malloc();'
90         const FunctionType *Malloc3Type = 
91           FunctionType::get(PointerType::get(Type::Int8Ty),
92                             std::vector<const Type*>(), true);
93         if (TyWeHave != Malloc3Type)
94           // Give up
95           MallocFunc = 0;
96       }
97     }
98   }
99
100   FreeFunc = M.getFunction("free");
101   if (FreeFunc) {
102     const FunctionType* TyWeHave = FreeFunc->getFunctionType();
103     
104     // Get the expected prototype for void free(i8*)
105     const FunctionType *Free1Type = FunctionType::get(Type::VoidTy,
106         std::vector<const Type*>(1, PointerType::get(Type::Int8Ty)), false);
107
108     if (TyWeHave != Free1Type) {
109       // Check to see if the prototype was forgotten, giving us 
110       // void (...) * free
111       // This handles the common forward declaration of: 'void free();'
112       const FunctionType* Free2Type = FunctionType::get(Type::VoidTy, 
113         std::vector<const Type*>(),true);
114
115       if (TyWeHave != Free2Type) {
116         // One last try, check to see if we can find free as 
117         // int (...)* free.  This handles the case where NOTHING was declared.
118         const FunctionType* Free3Type = FunctionType::get(Type::Int32Ty, 
119           std::vector<const Type*>(),true);
120         
121         if (TyWeHave != Free3Type) {
122           // Give up.
123           FreeFunc = 0;
124         }
125       }
126     }
127   }
128
129   // Don't mess with locally defined versions of these functions...
130   if (MallocFunc && !MallocFunc->isDeclaration()) MallocFunc = 0;
131   if (FreeFunc && !FreeFunc->isDeclaration())     FreeFunc = 0;
132 }
133
134 // run - Transform calls into instructions...
135 //
136 bool RaiseAllocations::runOnModule(Module &M) {
137   // Find the malloc/free prototypes...
138   doInitialization(M);
139
140   bool Changed = false;
141
142   // First, process all of the malloc calls...
143   if (MallocFunc) {
144     std::vector<User*> Users(MallocFunc->use_begin(), MallocFunc->use_end());
145     std::vector<Value*> EqPointers;   // Values equal to MallocFunc
146     while (!Users.empty()) {
147       User *U = Users.back();
148       Users.pop_back();
149
150       if (Instruction *I = dyn_cast<Instruction>(U)) {
151         CallSite CS = CallSite::get(I);
152         if (CS.getInstruction() && CS.arg_begin() != CS.arg_end() &&
153             (CS.getCalledFunction() == MallocFunc ||
154              std::find(EqPointers.begin(), EqPointers.end(),
155                        CS.getCalledValue()) != EqPointers.end())) {
156
157           Value *Source = *CS.arg_begin();
158
159           // If no prototype was provided for malloc, we may need to cast the
160           // source size.
161           if (Source->getType() != Type::Int32Ty)
162             Source = 
163               CastInst::createIntegerCast(Source, Type::Int32Ty, false/*ZExt*/,
164                                           "MallocAmtCast", I);
165
166           std::string Name(I->getName()); I->setName("");
167           MallocInst *MI = new MallocInst(Type::Int8Ty, Source, Name, I);
168           I->replaceAllUsesWith(MI);
169
170           // If the old instruction was an invoke, add an unconditional branch
171           // before the invoke, which will become the new terminator.
172           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
173             new BranchInst(II->getNormalDest(), I);
174
175           // Delete the old call site
176           MI->getParent()->getInstList().erase(I);
177           Changed = true;
178           ++NumRaised;
179         }
180       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
181         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
182         EqPointers.push_back(GV);
183       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
184         if (CE->isCast()) {
185           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
186           EqPointers.push_back(CE);
187         }
188       }
189     }
190   }
191
192   // Next, process all free calls...
193   if (FreeFunc) {
194     std::vector<User*> Users(FreeFunc->use_begin(), FreeFunc->use_end());
195     std::vector<Value*> EqPointers;   // Values equal to FreeFunc
196
197     while (!Users.empty()) {
198       User *U = Users.back();
199       Users.pop_back();
200
201       if (Instruction *I = dyn_cast<Instruction>(U)) {
202         CallSite CS = CallSite::get(I);
203         if (CS.getInstruction() && CS.arg_begin() != CS.arg_end() &&
204             (CS.getCalledFunction() == FreeFunc ||
205              std::find(EqPointers.begin(), EqPointers.end(),
206                        CS.getCalledValue()) != EqPointers.end())) {
207
208           // If no prototype was provided for free, we may need to cast the
209           // source pointer.  This should be really uncommon, but it's necessary
210           // just in case we are dealing with weird code like this:
211           //   free((long)ptr);
212           //
213           Value *Source = *CS.arg_begin();
214           if (!isa<PointerType>(Source->getType()))
215             Source = new IntToPtrInst(Source, PointerType::get(Type::Int8Ty), 
216                                       "FreePtrCast", I);
217           new FreeInst(Source, I);
218
219           // If the old instruction was an invoke, add an unconditional branch
220           // before the invoke, which will become the new terminator.
221           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
222             new BranchInst(II->getNormalDest(), I);
223
224           // Delete the old call site
225           if (I->getType() != Type::VoidTy)
226             I->replaceAllUsesWith(UndefValue::get(I->getType()));
227           I->eraseFromParent();
228           Changed = true;
229           ++NumRaised;
230         }
231       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(U)) {
232         Users.insert(Users.end(), GV->use_begin(), GV->use_end());
233         EqPointers.push_back(GV);
234       } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
235         if (CE->isCast()) {
236           Users.insert(Users.end(), CE->use_begin(), CE->use_end());
237           EqPointers.push_back(CE);
238         }
239       }
240     }
241   }
242
243   return Changed;
244 }