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 #define DEBUG_TYPE "lowerallocs"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
18 #include "llvm/Module.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Pass.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Support/Compiler.h"
28 STATISTIC(NumLowered, "Number of allocations lowered");
31 /// LowerAllocations - Turn malloc and free instructions into %malloc and
34 class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
35 Function *MallocFunc; // Functions in the module we are processing
36 Function *FreeFunc; // Initialized by doInitialization
37 bool LowerMallocArgToInteger;
39 LowerAllocations(bool LowerToInt = false)
40 : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
42 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
43 AU.addRequired<TargetData>();
46 // This is a cluster of orthogonal Transforms:
47 AU.addPreserved<UnifyFunctionExitNodes>();
48 AU.addPreservedID(PromoteMemoryToRegisterID);
49 AU.addPreservedID(LowerSelectID);
50 AU.addPreservedID(LowerSwitchID);
51 AU.addPreservedID(LowerInvokePassID);
54 /// doPassInitialization - For the lower allocations pass, this ensures that
55 /// a module contains a declaration for a malloc and a free function.
57 bool doInitialization(Module &M);
59 virtual bool doInitialization(Function &F) {
60 return BasicBlockPass::doInitialization(F);
63 /// runOnBasicBlock - This method does the actual work of converting
64 /// instructions over, assuming that the pass has already been initialized.
66 bool runOnBasicBlock(BasicBlock &BB);
69 RegisterPass<LowerAllocations>
70 X("lowerallocs", "Lower allocations from instructions to calls");
73 // Publically exposed interface to pass...
74 const PassInfo *llvm::LowerAllocationsID = X.getPassInfo();
75 // createLowerAllocationsPass - Interface to this file...
76 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
77 return new LowerAllocations(LowerMallocArgToInteger);
81 // doInitialization - For the lower allocations pass, this ensures that a
82 // module contains a declaration for a malloc and a free function.
84 // This function is always successful.
86 bool LowerAllocations::doInitialization(Module &M) {
87 const Type *SBPTy = PointerType::get(Type::SByteTy);
88 MallocFunc = M.getNamedFunction("malloc");
89 FreeFunc = M.getNamedFunction("free");
91 if (MallocFunc == 0) {
92 // Prototype malloc as "void* malloc(...)", because we don't know in
93 // doInitialization whether size_t is int or long.
94 FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
95 MallocFunc = M.getOrInsertFunction("malloc", FT);
98 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, SBPTy, (Type *)0);
103 // runOnBasicBlock - This method does the actual work of converting
104 // instructions over, assuming that the pass has already been initialized.
106 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
107 bool Changed = false;
108 assert(MallocFunc && FreeFunc && "Pass not initialized!");
110 BasicBlock::InstListType &BBIL = BB.getInstList();
112 const TargetData &TD = getAnalysis<TargetData>();
113 const Type *IntPtrTy = TD.getIntPtrType();
115 // Loop over all of the instructions, looking for malloc or free instructions
116 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
117 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
118 const Type *AllocTy = MI->getType()->getElementType();
120 // malloc(type) becomes sbyte *malloc(size)
122 if (LowerMallocArgToInteger)
123 MallocArg = ConstantInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
125 MallocArg = ConstantExpr::getSizeOf(AllocTy);
126 MallocArg = ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg),
129 if (MI->isArrayAllocation()) {
130 if (isa<ConstantInt>(MallocArg) &&
131 cast<ConstantInt>(MallocArg)->getZExtValue() == 1) {
132 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
133 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
134 CO = ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
135 MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
137 Value *Scale = MI->getOperand(0);
138 if (Scale->getType() != IntPtrTy)
139 Scale = CastInst::createIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
142 // Multiply it by the array size if necessary...
143 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
148 const FunctionType *MallocFTy = MallocFunc->getFunctionType();
149 std::vector<Value*> MallocArgs;
151 if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
152 if (MallocFTy->isVarArg()) {
153 if (MallocArg->getType() != IntPtrTy)
154 MallocArg = CastInst::createIntegerCast(MallocArg, IntPtrTy,
155 false /*ZExt*/, "", I);
156 } else if (MallocFTy->getNumParams() > 0 &&
157 MallocFTy->getParamType(0) != Type::UIntTy)
158 MallocArg = CastInst::createIntegerCast(
159 MallocArg, MallocFTy->getParamType(0), false/*ZExt*/, "",I);
160 MallocArgs.push_back(MallocArg);
163 // If malloc is prototyped to take extra arguments, pass nulls.
164 for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
165 MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
167 // Create the call to Malloc...
168 CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
169 MCall->setTailCall();
171 // Create a cast instruction to convert to the right type...
173 if (MCall->getType() != Type::VoidTy)
174 MCast = new BitCastInst(MCall, MI->getType(), "", I);
176 MCast = Constant::getNullValue(MI->getType());
178 // Replace all uses of the old malloc inst with the cast inst
179 MI->replaceAllUsesWith(MCast);
180 I = --BBIL.erase(I); // remove and delete the malloc instr...
183 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
184 const FunctionType *FreeFTy = FreeFunc->getFunctionType();
185 std::vector<Value*> FreeArgs;
187 if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
188 Value *MCast = FI->getOperand(0);
189 if (FreeFTy->getNumParams() > 0 &&
190 FreeFTy->getParamType(0) != MCast->getType())
191 MCast = new BitCastInst(MCast, FreeFTy->getParamType(0), "", I);
192 FreeArgs.push_back(MCast);
195 // If malloc is prototyped to take extra arguments, pass nulls.
196 for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
197 FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
199 // Insert a call to the free function...
200 (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
202 // Delete the old free instruction