d214d2edfe691f7e8e874706beaa004b12a7245a
[oota-llvm.git] / lib / Transforms / IPO / RaiseAllocations.cpp
1 //===- RaiseAllocations.cpp - Convert %malloc & %free calls to insts ------===//
2 //
3 // This file defines the RaiseAllocations pass which convert malloc and free
4 // calls to malloc and free instructions.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/IPO.h"
9 #include "llvm/Module.h"
10 #include "llvm/DerivedTypes.h"
11 #include "llvm/iMemory.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/Pass.h"
15 #include "llvm/Support/CallSite.h"
16 #include "Support/Statistic.h"
17
18 namespace {
19   Statistic<> NumRaised("raiseallocs", "Number of allocations raised");
20
21   // RaiseAllocations - Turn %malloc and %free calls into the appropriate
22   // instruction.
23   //
24   class RaiseAllocations : public Pass {
25     Function *MallocFunc;   // Functions in the module we are processing
26     Function *FreeFunc;     // Initialized by doPassInitializationVirt
27   public:
28     RaiseAllocations() : MallocFunc(0), FreeFunc(0) {}
29     
30     // doPassInitialization - For the raise allocations pass, this finds a
31     // declaration for malloc and free if they exist.
32     //
33     void doInitialization(Module &M);
34     
35     // run - This method does the actual work of converting instructions over.
36     //
37     bool run(Module &M);
38   };
39   
40   RegisterOpt<RaiseAllocations>
41   X("raiseallocs", "Raise allocations from calls to instructions");
42 }  // end anonymous namespace
43
44
45 // createRaiseAllocationsPass - The interface to this file...
46 Pass *createRaiseAllocationsPass() {
47   return new RaiseAllocations();
48 }
49
50
51 // If the module has a symbol table, they might be referring to the malloc and
52 // free functions.  If this is the case, grab the method pointers that the
53 // module is using.
54 //
55 // Lookup %malloc and %free in the symbol table, for later use.  If they don't
56 // exist, or are not external, we do not worry about converting calls to that
57 // function into the appropriate instruction.
58 //
59 void RaiseAllocations::doInitialization(Module &M) {
60   const FunctionType *MallocType =   // Get the type for malloc
61     FunctionType::get(PointerType::get(Type::SByteTy),
62                     std::vector<const Type*>(1, Type::ULongTy), false);
63
64   const FunctionType *FreeType =     // Get the type for free
65     FunctionType::get(Type::VoidTy,
66                    std::vector<const Type*>(1, PointerType::get(Type::SByteTy)),
67                       false);
68
69   // Get Malloc and free prototypes if they exist!
70   MallocFunc = M.getFunction("malloc", MallocType);
71   FreeFunc   = M.getFunction("free"  , FreeType);
72
73   // Check to see if the prototype is wrong, giving us sbyte*(uint) * malloc
74   // This handles the common declaration of: 'void *malloc(unsigned);'
75   if (MallocFunc == 0) {
76     MallocType = FunctionType::get(PointerType::get(Type::SByteTy),
77                             std::vector<const Type*>(1, Type::UIntTy), false);
78     MallocFunc = M.getFunction("malloc", MallocType);
79   }
80
81   // Check to see if the prototype is missing, giving us sbyte*(...) * malloc
82   // This handles the common declaration of: 'void *malloc();'
83   if (MallocFunc == 0) {
84     MallocType = FunctionType::get(PointerType::get(Type::SByteTy),
85                                    std::vector<const Type*>(), true);
86     MallocFunc = M.getFunction("malloc", MallocType);
87   }
88
89   // Check to see if the prototype was forgotten, giving us void (...) * free
90   // This handles the common forward declaration of: 'void free();'
91   if (FreeFunc == 0) {
92     FreeType = FunctionType::get(Type::VoidTy, std::vector<const Type*>(),true);
93     FreeFunc = M.getFunction("free", FreeType);
94   }
95
96   // One last try, check to see if we can find free as 'int (...)* free'.  This
97   // handles the case where NOTHING was declared.
98   if (FreeFunc == 0) {
99     FreeType = FunctionType::get(Type::IntTy, std::vector<const Type*>(),true);
100     FreeFunc = M.getFunction("free", FreeType);
101   }
102
103   // Don't mess with locally defined versions of these functions...
104   if (MallocFunc && !MallocFunc->isExternal()) MallocFunc = 0;
105   if (FreeFunc && !FreeFunc->isExternal())     FreeFunc = 0;
106 }
107
108 // run - Transform calls into instructions...
109 //
110 bool RaiseAllocations::run(Module &M) {
111   // Find the malloc/free prototypes...
112   doInitialization(M);
113
114   bool Changed = false;
115
116   // First, process all of the malloc calls...
117   if (MallocFunc) {
118     std::vector<User*> Users(MallocFunc->use_begin(), MallocFunc->use_end());
119     while (!Users.empty()) {
120       if (Instruction *I = dyn_cast<Instruction>(Users.back())) {
121         CallSite CS = CallSite::get(I);
122         if (CS.getInstruction() && CS.getCalledFunction() == MallocFunc &&
123             CS.arg_begin() != CS.arg_end()) {
124           Value *Source = *CS.arg_begin();
125           
126           // If no prototype was provided for malloc, we may need to cast the
127           // source size.
128           if (Source->getType() != Type::UIntTy)
129             Source = new CastInst(Source, Type::UIntTy, "MallocAmtCast", I);
130           
131           std::string Name(I->getName()); I->setName("");
132           MallocInst *MI = new MallocInst(Type::SByteTy, Source, Name, I);
133           I->replaceAllUsesWith(MI);
134
135           // If the old instruction was an invoke, add an unconditional branch
136           // before the invoke, which will become the new terminator.
137           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
138             new BranchInst(II->getNormalDest(), I);
139
140           // Delete the old call site
141           MI->getParent()->getInstList().erase(I);
142           Changed = true;
143           ++NumRaised;
144         }
145       }
146
147       Users.pop_back();
148     }
149   }
150
151   // Next, process all free calls...
152   if (FreeFunc) {
153     std::vector<User*> Users(FreeFunc->use_begin(), FreeFunc->use_end());
154
155     while (!Users.empty()) {
156       if (Instruction *I = dyn_cast<Instruction>(Users.back())) {
157         CallSite CS = CallSite::get(I);
158         if (CS.getInstruction() && CS.getCalledFunction() == FreeFunc &&
159             CS.arg_begin() != CS.arg_end()) {
160           
161           // If no prototype was provided for free, we may need to cast the
162           // source pointer.  This should be really uncommon, but it's necessary
163           // just in case we are dealing with wierd code like this:
164           //   free((long)ptr);
165           //
166           Value *Source = *CS.arg_begin();
167           if (!isa<PointerType>(Source->getType()))
168             Source = new CastInst(Source, PointerType::get(Type::SByteTy),
169                                   "FreePtrCast", I);
170           new FreeInst(Source, I);
171
172           // If the old instruction was an invoke, add an unconditional branch
173           // before the invoke, which will become the new terminator.
174           if (InvokeInst *II = dyn_cast<InvokeInst>(I))
175             new BranchInst(II->getNormalDest(), I);
176
177           // Delete the old call site
178           I->getParent()->getInstList().erase(I);
179           Changed = true;
180           ++NumRaised;
181         }
182       }
183       
184       Users.pop_back();
185     }
186   }
187
188   return Changed;
189 }