1 //===-- IndMemRemoval.cpp - Remove indirect allocations and frees ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This pass finds places where memory allocation functions may escape into
11 // indirect land. Some transforms are much easier (aka possible) only if free
12 // or malloc are not called indirectly.
13 // Thus find places where the address of memory functions are taken and construct
14 // bounce functions with direct calls of those functions.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "indmemrem"
19 #include "llvm/Transforms/IPO.h"
20 #include "llvm/Pass.h"
21 #include "llvm/Module.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Type.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/Compiler.h"
29 STATISTIC(NumBounceSites, "Number of sites modified");
30 STATISTIC(NumBounce , "Number of bounce functions created");
33 class VISIBILITY_HIDDEN IndMemRemPass : public ModulePass {
35 virtual bool runOnModule(Module &M);
37 RegisterPass<IndMemRemPass> X("indmemrem","Indirect Malloc and Free Removal");
38 } // end anonymous namespace
41 bool IndMemRemPass::runOnModule(Module &M) {
42 //in Theory, all direct calls of malloc and free should be promoted
43 //to intrinsics. Therefor, this goes through and finds where the
44 //address of free or malloc are taken and replaces those with bounce
45 //functions, ensuring that all malloc and free that might happen
46 //happen through intrinsics.
48 if (Function* F = M.getFunction("free")) {
49 assert(F->isDeclaration() && "free not external?");
50 if (!F->use_empty()) {
51 Function* FN = new Function(F->getFunctionType(),
52 GlobalValue::LinkOnceLinkage,
53 "free_llvm_bounce", &M);
54 BasicBlock* bb = new BasicBlock("entry",FN);
55 Instruction* R = new ReturnInst(bb);
56 new FreeInst(FN->arg_begin(), R);
58 NumBounceSites += F->getNumUses();
59 F->replaceAllUsesWith(FN);
63 if (Function* F = M.getFunction("malloc")) {
64 assert(F->isDeclaration() && "malloc not external?");
65 if (!F->use_empty()) {
66 Function* FN = new Function(F->getFunctionType(),
67 GlobalValue::LinkOnceLinkage,
68 "malloc_llvm_bounce", &M);
69 BasicBlock* bb = new BasicBlock("entry",FN);
70 Instruction* c = CastInst::createIntegerCast(
71 FN->arg_begin(), Type::Int32Ty, false, "c", bb);
72 Instruction* a = new MallocInst(Type::Int8Ty, c, "m", bb);
73 new ReturnInst(a, bb);
75 NumBounceSites += F->getNumUses();
76 F->replaceAllUsesWith(FN);
83 ModulePass *llvm::createIndMemRemPass() {
84 return new IndMemRemPass();