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