Add an optional argument to lower to a specific constant value instead of
[oota-llvm.git] / lib / Transforms / Utils / LowerAllocations.cpp
1 //===- LowerAllocations.cpp - Reduce malloc & free insts to calls ---------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // The LowerAllocations transformation is a target-dependent tranformation
11 // because it depends on the size of data types and alignment constraints.
12 //
13 //===----------------------------------------------------------------------===//
14
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"
23 using namespace llvm;
24
25 namespace {
26   Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
27
28   /// LowerAllocations - Turn malloc and free instructions into %malloc and
29   /// %free calls.
30   ///
31   class LowerAllocations : public BasicBlockPass {
32     Function *MallocFunc;   // Functions in the module we are processing
33     Function *FreeFunc;     // Initialized by doInitialization
34     bool LowerMallocArgToInteger;
35   public:
36     LowerAllocations(bool LowerToInt = false)
37       : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
38
39     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40       AU.addRequired<TargetData>();
41       AU.setPreservesCFG();
42     }
43
44     /// doPassInitialization - For the lower allocations pass, this ensures that
45     /// a module contains a declaration for a malloc and a free function.
46     ///
47     bool doInitialization(Module &M);
48
49     virtual bool doInitialization(Function &F) {
50       return BasicBlockPass::doInitialization(F);
51     }
52     
53     /// runOnBasicBlock - This method does the actual work of converting
54     /// instructions over, assuming that the pass has already been initialized.
55     ///
56     bool runOnBasicBlock(BasicBlock &BB);
57   };
58
59   RegisterOpt<LowerAllocations>
60   X("lowerallocs", "Lower allocations from instructions to calls");
61 }
62
63 // createLowerAllocationsPass - Interface to this file...
64 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
65   return new LowerAllocations(LowerMallocArgToInteger);
66 }
67
68
69 // doInitialization - For the lower allocations pass, this ensures that a
70 // module contains a declaration for a malloc and a free function.
71 //
72 // This function is always successful.
73 //
74 bool LowerAllocations::doInitialization(Module &M) {
75   const Type *SBPTy = PointerType::get(Type::SByteTy);
76   MallocFunc = M.getNamedFunction("malloc");
77   FreeFunc   = M.getNamedFunction("free");
78
79   if (MallocFunc == 0) {
80     // Prototype malloc as "void* malloc(...)", because we don't know in
81     // doInitialization whether size_t is int or long.
82     FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
83     MallocFunc = M.getOrInsertFunction("malloc", FT);
84   }
85   if (FreeFunc == 0)
86     FreeFunc = M.getOrInsertFunction("free"  , Type::VoidTy, SBPTy, 0);
87
88   return true;
89 }
90
91 // runOnBasicBlock - This method does the actual work of converting
92 // instructions over, assuming that the pass has already been initialized.
93 //
94 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
95   bool Changed = false;
96   assert(MallocFunc && FreeFunc && "Pass not initialized!");
97
98   BasicBlock::InstListType &BBIL = BB.getInstList();
99
100   const TargetData &TD = getAnalysis<TargetData>();
101   const Type *IntPtrTy = TD.getIntPtrType();
102
103   // Loop over all of the instructions, looking for malloc or free instructions
104   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
105     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
106       const Type *AllocTy = MI->getType()->getElementType();
107       
108       // malloc(type) becomes sbyte *malloc(size)
109       Value *MallocArg;
110       if (LowerMallocArgToInteger)
111         MallocArg = ConstantUInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
112       else
113         MallocArg = ConstantExpr::getSizeOf(AllocTy);
114       MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
115
116       if (MI->isArrayAllocation()) {
117         if (isa<ConstantInt>(MallocArg) &&
118             cast<ConstantInt>(MallocArg)->getRawValue() == 1) {
119           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
120         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
121           CO = ConstantExpr::getCast(CO, IntPtrTy);
122           MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
123         } else {
124           Value *Scale = MI->getOperand(0);
125           if (Scale->getType() != IntPtrTy)
126             Scale = new CastInst(Scale, IntPtrTy, "", I);
127
128           // Multiply it by the array size if necessary...
129           MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
130                                              MallocArg, "", I);
131         }
132       }
133
134       const FunctionType *MallocFTy = MallocFunc->getFunctionType();
135       std::vector<Value*> MallocArgs;
136       
137       if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
138         if (MallocFTy->isVarArg()) {
139           if (MallocArg->getType() != IntPtrTy)
140             MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
141         } else if (MallocFTy->getNumParams() > 0 &&
142                    MallocFTy->getParamType(0) != Type::UIntTy)
143           MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
144         MallocArgs.push_back(MallocArg);
145       }
146
147       // If malloc is prototyped to take extra arguments, pass nulls.
148       for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
149        MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
150
151       // Create the call to Malloc...
152       CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
153       
154       // Create a cast instruction to convert to the right type...
155       Value *MCast;
156       if (MCall->getType() != Type::VoidTy)
157         MCast = new CastInst(MCall, MI->getType(), "", I);
158       else
159         MCast = Constant::getNullValue(MI->getType());
160       
161       // Replace all uses of the old malloc inst with the cast inst
162       MI->replaceAllUsesWith(MCast);
163       I = --BBIL.erase(I);         // remove and delete the malloc instr...
164       Changed = true;
165       ++NumLowered;
166     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
167       const FunctionType *FreeFTy = FreeFunc->getFunctionType();
168       std::vector<Value*> FreeArgs;
169       
170       if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
171         Value *MCast = FI->getOperand(0);
172         if (FreeFTy->getNumParams() > 0 &&
173             FreeFTy->getParamType(0) != MCast->getType())
174           MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
175         FreeArgs.push_back(MCast);
176       }
177
178       // If malloc is prototyped to take extra arguments, pass nulls.
179       for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
180        FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
181       
182       // Insert a call to the free function...
183       new CallInst(FreeFunc, FreeArgs, "", I);
184       
185       // Delete the old free instruction
186       I = --BBIL.erase(I);
187       Changed = true;
188       ++NumLowered;
189     }
190   }
191
192   return Changed;
193 }
194