1 //===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 static char ID
; // Pass ID, replacement for typeid
40 explicit LowerAllocations(bool LowerToInt
= false)
41 : BasicBlockPass(&ID
), MallocFunc(0), FreeFunc(0),
42 LowerMallocArgToInteger(LowerToInt
) {}
44 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
45 AU
.addRequired
<TargetData
>();
48 // This is a cluster of orthogonal Transforms:
49 AU
.addPreserved
<UnifyFunctionExitNodes
>();
50 AU
.addPreservedID(PromoteMemoryToRegisterID
);
51 AU
.addPreservedID(LowerSwitchID
);
52 AU
.addPreservedID(LowerInvokePassID
);
55 /// doPassInitialization - For the lower allocations pass, this ensures that
56 /// a module contains a declaration for a malloc and a free function.
58 bool doInitialization(Module
&M
);
60 virtual bool doInitialization(Function
&F
) {
61 return doInitialization(*F
.getParent());
64 /// runOnBasicBlock - This method does the actual work of converting
65 /// instructions over, assuming that the pass has already been initialized.
67 bool runOnBasicBlock(BasicBlock
&BB
);
71 char LowerAllocations::ID
= 0;
72 static RegisterPass
<LowerAllocations
>
73 X("lowerallocs", "Lower allocations from instructions to calls");
75 // Publically exposed interface to pass...
76 const PassInfo
*const llvm::LowerAllocationsID
= &X
;
77 // createLowerAllocationsPass - Interface to this file...
78 Pass
*llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger
) {
79 return new LowerAllocations(LowerMallocArgToInteger
);
83 // doInitialization - For the lower allocations pass, this ensures that a
84 // module contains a declaration for a malloc and a free function.
86 // This function is always successful.
88 bool LowerAllocations::doInitialization(Module
&M
) {
89 const Type
*BPTy
= PointerType::getUnqual(Type::Int8Ty
);
90 // Prototype malloc as "char* malloc(...)", because we don't know in
91 // doInitialization whether size_t is int or long.
92 FunctionType
*FT
= FunctionType::get(BPTy
, std::vector
<const Type
*>(), true);
93 MallocFunc
= M
.getOrInsertFunction("malloc", FT
);
94 FreeFunc
= M
.getOrInsertFunction("free" , Type::VoidTy
, BPTy
, (Type
*)0);
98 // runOnBasicBlock - This method does the actual work of converting
99 // instructions over, assuming that the pass has already been initialized.
101 bool LowerAllocations::runOnBasicBlock(BasicBlock
&BB
) {
102 bool Changed
= false;
103 assert(MallocFunc
&& FreeFunc
&& "Pass not initialized!");
105 BasicBlock::InstListType
&BBIL
= BB
.getInstList();
107 const TargetData
&TD
= getAnalysis
<TargetData
>();
108 const Type
*IntPtrTy
= TD
.getIntPtrType();
110 // Loop over all of the instructions, looking for malloc or free instructions
111 for (BasicBlock::iterator I
= BB
.begin(), E
= BB
.end(); I
!= E
; ++I
) {
112 if (MallocInst
*MI
= dyn_cast
<MallocInst
>(I
)) {
113 const Type
*AllocTy
= MI
->getType()->getElementType();
115 // malloc(type) becomes sbyte *malloc(size)
117 if (LowerMallocArgToInteger
)
118 MallocArg
= ConstantInt::get(Type::Int64Ty
,
119 TD
.getTypePaddedSize(AllocTy
));
121 MallocArg
= ConstantExpr::getSizeOf(AllocTy
);
122 MallocArg
= ConstantExpr::getTruncOrBitCast(cast
<Constant
>(MallocArg
),
125 if (MI
->isArrayAllocation()) {
126 if (isa
<ConstantInt
>(MallocArg
) &&
127 cast
<ConstantInt
>(MallocArg
)->isOne()) {
128 MallocArg
= MI
->getOperand(0); // Operand * 1 = Operand
129 } else if (Constant
*CO
= dyn_cast
<Constant
>(MI
->getOperand(0))) {
130 CO
= ConstantExpr::getIntegerCast(CO
, IntPtrTy
, false /*ZExt*/);
131 MallocArg
= ConstantExpr::getMul(CO
, cast
<Constant
>(MallocArg
));
133 Value
*Scale
= MI
->getOperand(0);
134 if (Scale
->getType() != IntPtrTy
)
135 Scale
= CastInst::CreateIntegerCast(Scale
, IntPtrTy
, false /*ZExt*/,
138 // Multiply it by the array size if necessary...
139 MallocArg
= BinaryOperator::Create(Instruction::Mul
, Scale
,
144 // Create the call to Malloc.
145 CallInst
*MCall
= CallInst::Create(MallocFunc
, MallocArg
, "", I
);
146 MCall
->setTailCall();
148 // Create a cast instruction to convert to the right type...
150 if (MCall
->getType() != Type::VoidTy
)
151 MCast
= new BitCastInst(MCall
, MI
->getType(), "", I
);
153 MCast
= Constant::getNullValue(MI
->getType());
155 // Replace all uses of the old malloc inst with the cast inst
156 MI
->replaceAllUsesWith(MCast
);
157 I
= --BBIL
.erase(I
); // remove and delete the malloc instr...
160 } else if (FreeInst
*FI
= dyn_cast
<FreeInst
>(I
)) {
162 new BitCastInst(FI
->getOperand(0),
163 PointerType::getUnqual(Type::Int8Ty
), "", I
);
165 // Insert a call to the free function...
166 CallInst::Create(FreeFunc
, PtrCast
, "", I
)->setTailCall();
168 // Delete the old free instruction