1 //===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
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 // The LowerAllocations transformation is a target-dependent tranformation
11 // because it depends on the size of data types and alignment constraints.
13 //===----------------------------------------------------------------------===//
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"
26 Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
28 /// LowerAllocations - Turn malloc and free instructions into %malloc and
31 class LowerAllocations : public BasicBlockPass {
32 Function *MallocFunc; // Functions in the module we are processing
33 Function *FreeFunc; // Initialized by doInitialization
34 bool LowerMallocArgToInteger;
36 LowerAllocations(bool LowerToInt = false)
37 : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
39 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<TargetData>();
44 /// doPassInitialization - For the lower allocations pass, this ensures that
45 /// a module contains a declaration for a malloc and a free function.
47 bool doInitialization(Module &M);
49 virtual bool doInitialization(Function &F) {
50 return BasicBlockPass::doInitialization(F);
53 /// runOnBasicBlock - This method does the actual work of converting
54 /// instructions over, assuming that the pass has already been initialized.
56 bool runOnBasicBlock(BasicBlock &BB);
59 RegisterOpt<LowerAllocations>
60 X("lowerallocs", "Lower allocations from instructions to calls");
63 // createLowerAllocationsPass - Interface to this file...
64 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
65 return new LowerAllocations(LowerMallocArgToInteger);
69 // doInitialization - For the lower allocations pass, this ensures that a
70 // module contains a declaration for a malloc and a free function.
72 // This function is always successful.
74 bool LowerAllocations::doInitialization(Module &M) {
75 const Type *SBPTy = PointerType::get(Type::SByteTy);
76 MallocFunc = M.getNamedFunction("malloc");
77 FreeFunc = M.getNamedFunction("free");
79 if (MallocFunc == 0) {
80 // Prototype malloc as "void* malloc(...)", because we don't know in
81 // doInitialization whether size_t is int or long.
82 FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
83 MallocFunc = M.getOrInsertFunction("malloc", FT);
86 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, SBPTy, 0);
91 // runOnBasicBlock - This method does the actual work of converting
92 // instructions over, assuming that the pass has already been initialized.
94 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
96 assert(MallocFunc && FreeFunc && "Pass not initialized!");
98 BasicBlock::InstListType &BBIL = BB.getInstList();
100 const TargetData &TD = getAnalysis<TargetData>();
101 const Type *IntPtrTy = TD.getIntPtrType();
103 // Loop over all of the instructions, looking for malloc or free instructions
104 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
105 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
106 const Type *AllocTy = MI->getType()->getElementType();
108 // malloc(type) becomes sbyte *malloc(size)
110 if (LowerMallocArgToInteger)
111 MallocArg = ConstantUInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
113 MallocArg = ConstantExpr::getSizeOf(AllocTy);
114 MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
116 if (MI->isArrayAllocation()) {
117 if (isa<ConstantInt>(MallocArg) &&
118 cast<ConstantInt>(MallocArg)->getRawValue() == 1) {
119 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
120 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
121 CO = ConstantExpr::getCast(CO, IntPtrTy);
122 MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
124 Value *Scale = MI->getOperand(0);
125 if (Scale->getType() != IntPtrTy)
126 Scale = new CastInst(Scale, IntPtrTy, "", I);
128 // Multiply it by the array size if necessary...
129 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
134 const FunctionType *MallocFTy = MallocFunc->getFunctionType();
135 std::vector<Value*> MallocArgs;
137 if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
138 if (MallocFTy->isVarArg()) {
139 if (MallocArg->getType() != IntPtrTy)
140 MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
141 } else if (MallocFTy->getNumParams() > 0 &&
142 MallocFTy->getParamType(0) != Type::UIntTy)
143 MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
144 MallocArgs.push_back(MallocArg);
147 // If malloc is prototyped to take extra arguments, pass nulls.
148 for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
149 MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
151 // Create the call to Malloc...
152 CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
153 MCall->setTailCall();
155 // Create a cast instruction to convert to the right type...
157 if (MCall->getType() != Type::VoidTy)
158 MCast = new CastInst(MCall, MI->getType(), "", I);
160 MCast = Constant::getNullValue(MI->getType());
162 // Replace all uses of the old malloc inst with the cast inst
163 MI->replaceAllUsesWith(MCast);
164 I = --BBIL.erase(I); // remove and delete the malloc instr...
167 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
168 const FunctionType *FreeFTy = FreeFunc->getFunctionType();
169 std::vector<Value*> FreeArgs;
171 if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
172 Value *MCast = FI->getOperand(0);
173 if (FreeFTy->getNumParams() > 0 &&
174 FreeFTy->getParamType(0) != MCast->getType())
175 MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
176 FreeArgs.push_back(MCast);
179 // If malloc is prototyped to take extra arguments, pass nulls.
180 for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
181 FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
183 // Insert a call to the free function...
184 (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
186 // Delete the old free instruction