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"
24 #include "llvm/Support/Compiler.h"
28 Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
30 /// LowerAllocations - Turn malloc and free instructions into %malloc and
33 class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
34 Function *MallocFunc; // Functions in the module we are processing
35 Function *FreeFunc; // Initialized by doInitialization
36 bool LowerMallocArgToInteger;
38 LowerAllocations(bool LowerToInt = false)
39 : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
41 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42 AU.addRequired<TargetData>();
45 // This is a cluster of orthogonal Transforms:
46 AU.addPreserved<UnifyFunctionExitNodes>();
47 AU.addPreservedID(PromoteMemoryToRegisterID);
48 AU.addPreservedID(LowerSelectID);
49 AU.addPreservedID(LowerSwitchID);
50 AU.addPreservedID(LowerInvokePassID);
53 /// doPassInitialization - For the lower allocations pass, this ensures that
54 /// a module contains a declaration for a malloc and a free function.
56 bool doInitialization(Module &M);
58 virtual bool doInitialization(Function &F) {
59 return BasicBlockPass::doInitialization(F);
62 /// runOnBasicBlock - This method does the actual work of converting
63 /// instructions over, assuming that the pass has already been initialized.
65 bool runOnBasicBlock(BasicBlock &BB);
68 RegisterPass<LowerAllocations>
69 X("lowerallocs", "Lower allocations from instructions to calls");
72 // Publically exposed interface to pass...
73 const PassInfo *llvm::LowerAllocationsID = X.getPassInfo();
74 // createLowerAllocationsPass - Interface to this file...
75 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
76 return new LowerAllocations(LowerMallocArgToInteger);
80 // doInitialization - For the lower allocations pass, this ensures that a
81 // module contains a declaration for a malloc and a free function.
83 // This function is always successful.
85 bool LowerAllocations::doInitialization(Module &M) {
86 const Type *SBPTy = PointerType::get(Type::SByteTy);
87 MallocFunc = M.getNamedFunction("malloc");
88 FreeFunc = M.getNamedFunction("free");
90 if (MallocFunc == 0) {
91 // Prototype malloc as "void* malloc(...)", because we don't know in
92 // doInitialization whether size_t is int or long.
93 FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
94 MallocFunc = M.getOrInsertFunction("malloc", FT);
97 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, SBPTy, (Type *)0);
102 // runOnBasicBlock - This method does the actual work of converting
103 // instructions over, assuming that the pass has already been initialized.
105 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
106 bool Changed = false;
107 assert(MallocFunc && FreeFunc && "Pass not initialized!");
109 BasicBlock::InstListType &BBIL = BB.getInstList();
111 const TargetData &TD = getAnalysis<TargetData>();
112 const Type *IntPtrTy = TD.getIntPtrType();
114 // Loop over all of the instructions, looking for malloc or free instructions
115 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
116 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
117 const Type *AllocTy = MI->getType()->getElementType();
119 // malloc(type) becomes sbyte *malloc(size)
121 if (LowerMallocArgToInteger)
122 MallocArg = ConstantInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
124 MallocArg = ConstantExpr::getSizeOf(AllocTy);
125 MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
127 if (MI->isArrayAllocation()) {
128 if (isa<ConstantInt>(MallocArg) &&
129 cast<ConstantInt>(MallocArg)->getZExtValue() == 1) {
130 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
131 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
132 CO = ConstantExpr::getCast(CO, IntPtrTy);
133 MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
135 Value *Scale = MI->getOperand(0);
136 if (Scale->getType() != IntPtrTy)
137 Scale = CastInst::createInferredCast(Scale, IntPtrTy, "", I);
139 // Multiply it by the array size if necessary...
140 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
145 const FunctionType *MallocFTy = MallocFunc->getFunctionType();
146 std::vector<Value*> MallocArgs;
148 if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
149 if (MallocFTy->isVarArg()) {
150 if (MallocArg->getType() != IntPtrTy)
151 MallocArg = CastInst::createInferredCast(MallocArg, IntPtrTy, "",
153 } else if (MallocFTy->getNumParams() > 0 &&
154 MallocFTy->getParamType(0) != Type::UIntTy)
156 CastInst::createInferredCast(MallocArg, MallocFTy->getParamType(0),
158 MallocArgs.push_back(MallocArg);
161 // If malloc is prototyped to take extra arguments, pass nulls.
162 for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
163 MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
165 // Create the call to Malloc...
166 CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
167 MCall->setTailCall();
169 // Create a cast instruction to convert to the right type...
171 if (MCall->getType() != Type::VoidTy)
172 MCast = CastInst::createInferredCast(MCall, MI->getType(), "", I);
174 MCast = Constant::getNullValue(MI->getType());
176 // Replace all uses of the old malloc inst with the cast inst
177 MI->replaceAllUsesWith(MCast);
178 I = --BBIL.erase(I); // remove and delete the malloc instr...
181 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
182 const FunctionType *FreeFTy = FreeFunc->getFunctionType();
183 std::vector<Value*> FreeArgs;
185 if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
186 Value *MCast = FI->getOperand(0);
187 if (FreeFTy->getNumParams() > 0 &&
188 FreeFTy->getParamType(0) != MCast->getType())
189 MCast = CastInst::createInferredCast(MCast, FreeFTy->getParamType(0),
191 FreeArgs.push_back(MCast);
194 // If malloc is prototyped to take extra arguments, pass nulls.
195 for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
196 FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
198 // Insert a call to the free function...
199 (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
201 // Delete the old free instruction