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