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 #include "llvm/Transforms/IPO.h"
19 #include "llvm/Pass.h"
20 #include "llvm/Module.h"
21 #include "llvm/Function.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Type.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/ADT/Statistic.h"
32 Statistic<> NumBounceSites("indmemrem", "Number of sites modified");
33 Statistic<> NumBounce ("indmemrem", "Number of bounce functions created");
35 class IndMemRemPass : public ModulePass {
39 virtual bool runOnModule(Module &M);
41 RegisterPass<IndMemRemPass> X("indmemrem","Indirect Malloc and Free Removal");
42 } // end anonymous namespace
45 IndMemRemPass::IndMemRemPass()
49 bool IndMemRemPass::runOnModule(Module &M) {
50 //in Theory, all direct calls of malloc and free should be promoted
51 //to intrinsics. Therefor, this goes through and finds where the
52 //address of free or malloc are taken and replaces those with bounce
53 //functions, ensuring that all malloc and free that might happen
54 //happen through intrinsics.
56 if (Function* F = M.getNamedFunction("free")) {
57 assert(F->isExternal() && "free not external?");
58 if (!F->use_empty()) {
59 Function* FN = new Function(F->getFunctionType(),
60 GlobalValue::LinkOnceLinkage,
61 "free_llvm_bounce", &M);
62 BasicBlock* bb = new BasicBlock("entry",FN);
63 Instruction* R = new ReturnInst(bb);
64 new FreeInst(FN->arg_begin(), R);
66 NumBounceSites += F->getNumUses();
67 F->replaceAllUsesWith(FN);
71 if (Function* F = M.getNamedFunction("malloc")) {
72 assert(F->isExternal() && "malloc not external?");
73 if (!F->use_empty()) {
74 Function* FN = new Function(F->getFunctionType(),
75 GlobalValue::LinkOnceLinkage,
76 "malloc_llvm_bounce", &M);
77 BasicBlock* bb = new BasicBlock("entry",FN);
78 Instruction* c = new CastInst(FN->arg_begin(), Type::UIntTy, "c", bb);
79 Instruction* a = new MallocInst(Type::SByteTy, c, "m", bb);
80 Instruction* R = new ReturnInst(a, bb);
82 NumBounceSites += F->getNumUses();
83 F->replaceAllUsesWith(FN);
90 ModulePass *llvm::createIndMemRemPass() {
91 return new IndMemRemPass();