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/Transforms/Utils/UnifyFunctionExitNodes.h"
17 #include "llvm/Module.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Pass.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Target/TargetData.h"
27 Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
29 /// LowerAllocations - Turn malloc and free instructions into %malloc and
32 class LowerAllocations : public BasicBlockPass {
33 Function *MallocFunc; // Functions in the module we are processing
34 Function *FreeFunc; // Initialized by doInitialization
35 bool LowerMallocArgToInteger;
37 LowerAllocations(bool LowerToInt = false)
38 : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
40 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41 AU.addRequired<TargetData>();
44 // This is a cluster of orthogonal Transforms:
45 AU.addPreserved<UnifyFunctionExitNodes>();
46 AU.addPreservedID(PromoteMemoryToRegisterID);
47 AU.addPreservedID(LowerSelectID);
48 AU.addPreservedID(LowerSwitchID);
51 /// doPassInitialization - For the lower allocations pass, this ensures that
52 /// a module contains a declaration for a malloc and a free function.
54 bool doInitialization(Module &M);
56 virtual bool doInitialization(Function &F) {
57 return BasicBlockPass::doInitialization(F);
60 /// runOnBasicBlock - This method does the actual work of converting
61 /// instructions over, assuming that the pass has already been initialized.
63 bool runOnBasicBlock(BasicBlock &BB);
66 RegisterOpt<LowerAllocations>
67 X("lowerallocs", "Lower allocations from instructions to calls");
70 // Publically exposed interface to pass...
71 const PassInfo *llvm::LowerAllocationsID = X.getPassInfo();
72 // createLowerAllocationsPass - Interface to this file...
73 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
74 return new LowerAllocations(LowerMallocArgToInteger);
78 // doInitialization - For the lower allocations pass, this ensures that a
79 // module contains a declaration for a malloc and a free function.
81 // This function is always successful.
83 bool LowerAllocations::doInitialization(Module &M) {
84 const Type *SBPTy = PointerType::get(Type::SByteTy);
85 MallocFunc = M.getNamedFunction("malloc");
86 FreeFunc = M.getNamedFunction("free");
88 if (MallocFunc == 0) {
89 // Prototype malloc as "void* malloc(...)", because we don't know in
90 // doInitialization whether size_t is int or long.
91 FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
92 MallocFunc = M.getOrInsertFunction("malloc", FT);
95 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, SBPTy, (Type *)0);
100 // runOnBasicBlock - This method does the actual work of converting
101 // instructions over, assuming that the pass has already been initialized.
103 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
104 bool Changed = false;
105 assert(MallocFunc && FreeFunc && "Pass not initialized!");
107 BasicBlock::InstListType &BBIL = BB.getInstList();
109 const TargetData &TD = getAnalysis<TargetData>();
110 const Type *IntPtrTy = TD.getIntPtrType();
112 // Loop over all of the instructions, looking for malloc or free instructions
113 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
114 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
115 const Type *AllocTy = MI->getType()->getElementType();
117 // malloc(type) becomes sbyte *malloc(size)
119 if (LowerMallocArgToInteger)
120 MallocArg = ConstantUInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
122 MallocArg = ConstantExpr::getSizeOf(AllocTy);
123 MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
125 if (MI->isArrayAllocation()) {
126 if (isa<ConstantInt>(MallocArg) &&
127 cast<ConstantInt>(MallocArg)->getRawValue() == 1) {
128 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
129 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
130 CO = ConstantExpr::getCast(CO, IntPtrTy);
131 MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
133 Value *Scale = MI->getOperand(0);
134 if (Scale->getType() != IntPtrTy)
135 Scale = new CastInst(Scale, IntPtrTy, "", I);
137 // Multiply it by the array size if necessary...
138 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
143 const FunctionType *MallocFTy = MallocFunc->getFunctionType();
144 std::vector<Value*> MallocArgs;
146 if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
147 if (MallocFTy->isVarArg()) {
148 if (MallocArg->getType() != IntPtrTy)
149 MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
150 } else if (MallocFTy->getNumParams() > 0 &&
151 MallocFTy->getParamType(0) != Type::UIntTy)
152 MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
153 MallocArgs.push_back(MallocArg);
156 // If malloc is prototyped to take extra arguments, pass nulls.
157 for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
158 MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
160 // Create the call to Malloc...
161 CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
162 MCall->setTailCall();
164 // Create a cast instruction to convert to the right type...
166 if (MCall->getType() != Type::VoidTy)
167 MCast = new CastInst(MCall, MI->getType(), "", I);
169 MCast = Constant::getNullValue(MI->getType());
171 // Replace all uses of the old malloc inst with the cast inst
172 MI->replaceAllUsesWith(MCast);
173 I = --BBIL.erase(I); // remove and delete the malloc instr...
176 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
177 const FunctionType *FreeFTy = FreeFunc->getFunctionType();
178 std::vector<Value*> FreeArgs;
180 if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
181 Value *MCast = FI->getOperand(0);
182 if (FreeFTy->getNumParams() > 0 &&
183 FreeFTy->getParamType(0) != MCast->getType())
184 MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
185 FreeArgs.push_back(MCast);
188 // If malloc is prototyped to take extra arguments, pass nulls.
189 for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
190 FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
192 // Insert a call to the free function...
193 (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
195 // Delete the old free instruction