Get rid of getSizeOf, using ConstantExpr::getSizeOf instead.
[oota-llvm.git] / lib / Transforms / Utils / LowerAllocations.cpp
1 //===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
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 // The LowerAllocations transformation is a target-dependent tranformation
11 // because it depends on the size of data types and alignment constraints.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Module.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Pass.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Target/TargetData.h"
23 using namespace llvm;
24
25 namespace {
26   Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
27
28   /// LowerAllocations - Turn malloc and free instructions into %malloc and
29   /// %free calls.
30   ///
31   class LowerAllocations : public BasicBlockPass {
32     Function *MallocFunc;   // Functions in the module we are processing
33     Function *FreeFunc;     // Initialized by doInitialization
34   public:
35     LowerAllocations() : MallocFunc(0), FreeFunc(0) {}
36
37     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
38       AU.addRequired<TargetData>();
39       AU.setPreservesCFG();
40     }
41
42     /// doPassInitialization - For the lower allocations pass, this ensures that
43     /// a module contains a declaration for a malloc and a free function.
44     ///
45     bool doInitialization(Module &M);
46
47     virtual bool doInitialization(Function &F) {
48       return BasicBlockPass::doInitialization(F);
49     }
50     
51     /// runOnBasicBlock - This method does the actual work of converting
52     /// instructions over, assuming that the pass has already been initialized.
53     ///
54     bool runOnBasicBlock(BasicBlock &BB);
55   };
56
57   RegisterOpt<LowerAllocations>
58   X("lowerallocs", "Lower allocations from instructions to calls");
59 }
60
61 // createLowerAllocationsPass - Interface to this file...
62 FunctionPass *llvm::createLowerAllocationsPass() {
63   return new LowerAllocations();
64 }
65
66
67 // doInitialization - For the lower allocations pass, this ensures that a
68 // module contains a declaration for a malloc and a free function.
69 //
70 // This function is always successful.
71 //
72 bool LowerAllocations::doInitialization(Module &M) {
73   const Type *SBPTy = PointerType::get(Type::SByteTy);
74   MallocFunc = M.getNamedFunction("malloc");
75   FreeFunc   = M.getNamedFunction("free");
76
77   if (MallocFunc == 0) {
78     // Prototype malloc as "void* malloc(...)", because we don't know in
79     // doInitialization whether size_t is int or long.
80     FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
81     MallocFunc = M.getOrInsertFunction("malloc", FT);
82   }
83   if (FreeFunc == 0)
84     FreeFunc = M.getOrInsertFunction("free"  , Type::VoidTy, SBPTy, 0);
85
86   return true;
87 }
88
89 // runOnBasicBlock - This method does the actual work of converting
90 // instructions over, assuming that the pass has already been initialized.
91 //
92 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
93   bool Changed = false;
94   assert(MallocFunc && FreeFunc && "Pass not initialized!");
95
96   BasicBlock::InstListType &BBIL = BB.getInstList();
97
98   const Type *IntPtrTy = getAnalysis<TargetData>().getIntPtrType();
99
100   // Loop over all of the instructions, looking for malloc or free instructions
101   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
102     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
103       const Type *AllocTy = MI->getType()->getElementType();
104       
105       // malloc(type) becomes sbyte *malloc(size)
106       Value *MallocArg = ConstantExpr::getCast(ConstantExpr::getSizeOf(AllocTy),
107                                                IntPtrTy);
108       if (MI->isArrayAllocation()) {
109         if (isa<ConstantInt>(MallocArg) &&
110             cast<ConstantInt>(MallocArg)->getRawValue() == 1) {
111           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
112         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
113           CO = ConstantExpr::getCast(CO, IntPtrTy);
114           MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
115         } else {
116           Value *Scale = MI->getOperand(0);
117           if (Scale->getType() != IntPtrTy)
118             Scale = new CastInst(Scale, IntPtrTy, "", I);
119
120           // Multiply it by the array size if necessary...
121           MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
122                                              MallocArg, "", I);
123         }
124       }
125
126       const FunctionType *MallocFTy = MallocFunc->getFunctionType();
127       std::vector<Value*> MallocArgs;
128       
129       if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
130         if (MallocFTy->isVarArg()) {
131           if (MallocArg->getType() != IntPtrTy)
132             MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
133         } else if (MallocFTy->getNumParams() > 0 &&
134                    MallocFTy->getParamType(0) != Type::UIntTy)
135           MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
136         MallocArgs.push_back(MallocArg);
137       }
138
139       // If malloc is prototyped to take extra arguments, pass nulls.
140       for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
141        MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
142
143       // Create the call to Malloc...
144       CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
145       
146       // Create a cast instruction to convert to the right type...
147       Value *MCast;
148       if (MCall->getType() != Type::VoidTy)
149         MCast = new CastInst(MCall, MI->getType(), "", I);
150       else
151         MCast = Constant::getNullValue(MI->getType());
152       
153       // Replace all uses of the old malloc inst with the cast inst
154       MI->replaceAllUsesWith(MCast);
155       I = --BBIL.erase(I);         // remove and delete the malloc instr...
156       Changed = true;
157       ++NumLowered;
158     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
159       const FunctionType *FreeFTy = FreeFunc->getFunctionType();
160       std::vector<Value*> FreeArgs;
161       
162       if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
163         Value *MCast = FI->getOperand(0);
164         if (FreeFTy->getNumParams() > 0 &&
165             FreeFTy->getParamType(0) != MCast->getType())
166           MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
167         FreeArgs.push_back(MCast);
168       }
169
170       // If malloc is prototyped to take extra arguments, pass nulls.
171       for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
172        FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
173       
174       // Insert a call to the free function...
175       new CallInst(FreeFunc, FreeArgs, "", I);
176       
177       // Delete the old free instruction
178       I = --BBIL.erase(I);
179       Changed = true;
180       ++NumLowered;
181     }
182   }
183
184   return Changed;
185 }
186