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