For PR950:
[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/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"
25 using namespace llvm;
26
27 namespace {
28   Statistic<> NumLowered("lowerallocs", "Number of allocations lowered");
29
30   /// LowerAllocations - Turn malloc and free instructions into %malloc and
31   /// %free calls.
32   ///
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;
37   public:
38     LowerAllocations(bool LowerToInt = false)
39       : MallocFunc(0), FreeFunc(0), LowerMallocArgToInteger(LowerToInt) {}
40
41     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
42       AU.addRequired<TargetData>();
43       AU.setPreservesCFG();
44
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);
51     }
52
53     /// doPassInitialization - For the lower allocations pass, this ensures that
54     /// a module contains a declaration for a malloc and a free function.
55     ///
56     bool doInitialization(Module &M);
57
58     virtual bool doInitialization(Function &F) {
59       return BasicBlockPass::doInitialization(F);
60     }
61
62     /// runOnBasicBlock - This method does the actual work of converting
63     /// instructions over, assuming that the pass has already been initialized.
64     ///
65     bool runOnBasicBlock(BasicBlock &BB);
66   };
67
68   RegisterPass<LowerAllocations>
69   X("lowerallocs", "Lower allocations from instructions to calls");
70 }
71
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);
77 }
78
79
80 // doInitialization - For the lower allocations pass, this ensures that a
81 // module contains a declaration for a malloc and a free function.
82 //
83 // This function is always successful.
84 //
85 bool LowerAllocations::doInitialization(Module &M) {
86   const Type *SBPTy = PointerType::get(Type::SByteTy);
87   MallocFunc = M.getNamedFunction("malloc");
88   FreeFunc   = M.getNamedFunction("free");
89
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);
95   }
96   if (FreeFunc == 0)
97     FreeFunc = M.getOrInsertFunction("free"  , Type::VoidTy, SBPTy, (Type *)0);
98
99   return true;
100 }
101
102 // runOnBasicBlock - This method does the actual work of converting
103 // instructions over, assuming that the pass has already been initialized.
104 //
105 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
106   bool Changed = false;
107   assert(MallocFunc && FreeFunc && "Pass not initialized!");
108
109   BasicBlock::InstListType &BBIL = BB.getInstList();
110
111   const TargetData &TD = getAnalysis<TargetData>();
112   const Type *IntPtrTy = TD.getIntPtrType();
113
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();
118
119       // malloc(type) becomes sbyte *malloc(size)
120       Value *MallocArg;
121       if (LowerMallocArgToInteger)
122         MallocArg = ConstantInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
123       else
124         MallocArg = ConstantExpr::getSizeOf(AllocTy);
125       MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
126
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));
134         } else {
135           Value *Scale = MI->getOperand(0);
136           if (Scale->getType() != IntPtrTy)
137             Scale = new CastInst(Scale, IntPtrTy, "", I);
138
139           // Multiply it by the array size if necessary...
140           MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
141                                              MallocArg, "", I);
142         }
143       }
144
145       const FunctionType *MallocFTy = MallocFunc->getFunctionType();
146       std::vector<Value*> MallocArgs;
147
148       if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
149         if (MallocFTy->isVarArg()) {
150           if (MallocArg->getType() != IntPtrTy)
151             MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
152         } else if (MallocFTy->getNumParams() > 0 &&
153                    MallocFTy->getParamType(0) != Type::UIntTy)
154           MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
155         MallocArgs.push_back(MallocArg);
156       }
157
158       // If malloc is prototyped to take extra arguments, pass nulls.
159       for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
160        MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
161
162       // Create the call to Malloc...
163       CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
164       MCall->setTailCall();
165
166       // Create a cast instruction to convert to the right type...
167       Value *MCast;
168       if (MCall->getType() != Type::VoidTy)
169         MCast = new CastInst(MCall, MI->getType(), "", I);
170       else
171         MCast = Constant::getNullValue(MI->getType());
172
173       // Replace all uses of the old malloc inst with the cast inst
174       MI->replaceAllUsesWith(MCast);
175       I = --BBIL.erase(I);         // remove and delete the malloc instr...
176       Changed = true;
177       ++NumLowered;
178     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
179       const FunctionType *FreeFTy = FreeFunc->getFunctionType();
180       std::vector<Value*> FreeArgs;
181
182       if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
183         Value *MCast = FI->getOperand(0);
184         if (FreeFTy->getNumParams() > 0 &&
185             FreeFTy->getParamType(0) != MCast->getType())
186           MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
187         FreeArgs.push_back(MCast);
188       }
189
190       // If malloc is prototyped to take extra arguments, pass nulls.
191       for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
192        FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
193
194       // Insert a call to the free function...
195       (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
196
197       // Delete the old free instruction
198       I = --BBIL.erase(I);
199       Changed = true;
200       ++NumLowered;
201     }
202   }
203
204   return Changed;
205 }
206