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