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 Constant *MallocFunc; // Functions in the module we are processing
36 Constant *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 *BPTy = PointerType::get(Type::Int8Ty);
88 // Prototype malloc as "char* malloc(...)", because we don't know in
89 // doInitialization whether size_t is int or long.
90 FunctionType *FT = FunctionType::get(BPTy, std::vector<const Type*>(), true);
91 MallocFunc = M.getOrInsertFunction("malloc", FT);
92 FreeFunc = M.getOrInsertFunction("free" , Type::VoidTy, BPTy, (Type *)0);
96 // runOnBasicBlock - This method does the actual work of converting
97 // instructions over, assuming that the pass has already been initialized.
99 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
100 bool Changed = false;
101 assert(MallocFunc && FreeFunc && "Pass not initialized!");
103 BasicBlock::InstListType &BBIL = BB.getInstList();
105 const TargetData &TD = getAnalysis<TargetData>();
106 const Type *IntPtrTy = TD.getIntPtrType();
108 // Loop over all of the instructions, looking for malloc or free instructions
109 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
110 if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
111 const Type *AllocTy = MI->getType()->getElementType();
113 // malloc(type) becomes sbyte *malloc(size)
115 if (LowerMallocArgToInteger)
116 MallocArg = ConstantInt::get(Type::Int64Ty, TD.getTypeSize(AllocTy));
118 MallocArg = ConstantExpr::getSizeOf(AllocTy);
119 MallocArg = ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg),
122 if (MI->isArrayAllocation()) {
123 if (isa<ConstantInt>(MallocArg) &&
124 cast<ConstantInt>(MallocArg)->getZExtValue() == 1) {
125 MallocArg = MI->getOperand(0); // Operand * 1 = Operand
126 } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
127 CO = ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
128 MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
130 Value *Scale = MI->getOperand(0);
131 if (Scale->getType() != IntPtrTy)
132 Scale = CastInst::createIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
135 // Multiply it by the array size if necessary...
136 MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
141 // Create the call to Malloc.
142 CallInst *MCall = new CallInst(MallocFunc, MallocArg, "", I);
143 MCall->setTailCall();
145 // Create a cast instruction to convert to the right type...
147 if (MCall->getType() != Type::VoidTy)
148 MCast = new BitCastInst(MCall, MI->getType(), "", I);
150 MCast = Constant::getNullValue(MI->getType());
152 // Replace all uses of the old malloc inst with the cast inst
153 MI->replaceAllUsesWith(MCast);
154 I = --BBIL.erase(I); // remove and delete the malloc instr...
157 } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
158 Value *PtrCast = new BitCastInst(FI->getOperand(0),
159 PointerType::get(Type::Int8Ty), "", I);
161 // Insert a call to the free function...
162 (new CallInst(FreeFunc, PtrCast, "", I))->setTailCall();
164 // Delete the old free instruction