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
35 LowerAllocations() : MallocFunc(0), FreeFunc(0) {}
37 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
38 AU.addRequired<TargetData>();
42 /// doPassInitialization - For the lower allocations pass, this ensures that
43 /// a module contains a declaration for a malloc and a free function.
45 bool doInitialization(Module &M);
47 virtual bool doInitialization(Function &F) {
48 return BasicBlockPass::doInitialization(F);
51 /// runOnBasicBlock - This method does the actual work of converting
52 /// instructions over, assuming that the pass has already been initialized.
54 bool runOnBasicBlock(BasicBlock &BB);
57 RegisterOpt<LowerAllocations>
58 X("lowerallocs", "Lower allocations from instructions to calls");
61 // createLowerAllocationsPass - Interface to this file...
62 FunctionPass *llvm::createLowerAllocationsPass() {
63 return new LowerAllocations();
67 // doInitialization - For the lower allocations pass, this ensures that a
68 // module contains a declaration for a malloc and a free function.
70 // This function is always successful.
72 bool LowerAllocations::doInitialization(Module &M) {
73 const Type *SBPTy = PointerType::get(Type::SByteTy);
74 MallocFunc = M.getNamedFunction("malloc");
75 FreeFunc = M.getNamedFunction("free");
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);
84 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, SBPTy, 0);
89 // runOnBasicBlock - This method does the actual work of converting
90 // instructions over, assuming that the pass has already been initialized.
92 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
94 assert(MallocFunc && FreeFunc && "Pass not initialized!");
96 BasicBlock::InstListType &BBIL = BB.getInstList();
98 const Type *IntPtrTy = getAnalysis<TargetData>().getIntPtrType();
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();
105 // malloc(type) becomes sbyte *malloc(size)
106 Value *MallocArg = ConstantExpr::getCast(ConstantExpr::getSizeOf(AllocTy),
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));
116 Value *Scale = MI->getOperand(0);
117 if (Scale->getType() != IntPtrTy)
118 Scale = new CastInst(Scale, IntPtrTy, "", I);
120 // Multiply it by the array size if necessary...
121 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
126 const FunctionType *MallocFTy = MallocFunc->getFunctionType();
127 std::vector<Value*> MallocArgs;
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);
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)));
143 // Create the call to Malloc...
144 CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
146 // Create a cast instruction to convert to the right type...
148 if (MCall->getType() != Type::VoidTy)
149 MCast = new CastInst(MCall, MI->getType(), "", I);
151 MCast = Constant::getNullValue(MI->getType());
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...
158 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
159 const FunctionType *FreeFTy = FreeFunc->getFunctionType();
160 std::vector<Value*> FreeArgs;
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);
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)));
174 // Insert a call to the free function...
175 new CallInst(FreeFunc, FreeArgs, "", I);
177 // Delete the old free instruction