Add pass ID's for various passes, so they can be AddRequiredID. Patch by
[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 // Publically exposed interface to pass...
64 const PassInfo *llvm::LowerAllocationsID = X.getPassInfo();
65 // createLowerAllocationsPass - Interface to this file...
66 FunctionPass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
67   return new LowerAllocations(LowerMallocArgToInteger);
68 }
69
70
71 // doInitialization - For the lower allocations pass, this ensures that a
72 // module contains a declaration for a malloc and a free function.
73 //
74 // This function is always successful.
75 //
76 bool LowerAllocations::doInitialization(Module &M) {
77   const Type *SBPTy = PointerType::get(Type::SByteTy);
78   MallocFunc = M.getNamedFunction("malloc");
79   FreeFunc   = M.getNamedFunction("free");
80
81   if (MallocFunc == 0) {
82     // Prototype malloc as "void* malloc(...)", because we don't know in
83     // doInitialization whether size_t is int or long.
84     FunctionType *FT = FunctionType::get(SBPTy,std::vector<const Type*>(),true);
85     MallocFunc = M.getOrInsertFunction("malloc", FT);
86   }
87   if (FreeFunc == 0)
88     FreeFunc = M.getOrInsertFunction("free"  , Type::VoidTy, SBPTy, (Type *)0);
89
90   return true;
91 }
92
93 // runOnBasicBlock - This method does the actual work of converting
94 // instructions over, assuming that the pass has already been initialized.
95 //
96 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
97   bool Changed = false;
98   assert(MallocFunc && FreeFunc && "Pass not initialized!");
99
100   BasicBlock::InstListType &BBIL = BB.getInstList();
101
102   const TargetData &TD = getAnalysis<TargetData>();
103   const Type *IntPtrTy = TD.getIntPtrType();
104
105   // Loop over all of the instructions, looking for malloc or free instructions
106   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
107     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
108       const Type *AllocTy = MI->getType()->getElementType();
109
110       // malloc(type) becomes sbyte *malloc(size)
111       Value *MallocArg;
112       if (LowerMallocArgToInteger)
113         MallocArg = ConstantUInt::get(Type::ULongTy, TD.getTypeSize(AllocTy));
114       else
115         MallocArg = ConstantExpr::getSizeOf(AllocTy);
116       MallocArg = ConstantExpr::getCast(cast<Constant>(MallocArg), IntPtrTy);
117
118       if (MI->isArrayAllocation()) {
119         if (isa<ConstantInt>(MallocArg) &&
120             cast<ConstantInt>(MallocArg)->getRawValue() == 1) {
121           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
122         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
123           CO = ConstantExpr::getCast(CO, IntPtrTy);
124           MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
125         } else {
126           Value *Scale = MI->getOperand(0);
127           if (Scale->getType() != IntPtrTy)
128             Scale = new CastInst(Scale, IntPtrTy, "", I);
129
130           // Multiply it by the array size if necessary...
131           MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
132                                              MallocArg, "", I);
133         }
134       }
135
136       const FunctionType *MallocFTy = MallocFunc->getFunctionType();
137       std::vector<Value*> MallocArgs;
138
139       if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
140         if (MallocFTy->isVarArg()) {
141           if (MallocArg->getType() != IntPtrTy)
142             MallocArg = new CastInst(MallocArg, IntPtrTy, "", I);
143         } else if (MallocFTy->getNumParams() > 0 &&
144                    MallocFTy->getParamType(0) != Type::UIntTy)
145           MallocArg = new CastInst(MallocArg, MallocFTy->getParamType(0), "",I);
146         MallocArgs.push_back(MallocArg);
147       }
148
149       // If malloc is prototyped to take extra arguments, pass nulls.
150       for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
151        MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
152
153       // Create the call to Malloc...
154       CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
155       MCall->setTailCall();
156
157       // Create a cast instruction to convert to the right type...
158       Value *MCast;
159       if (MCall->getType() != Type::VoidTy)
160         MCast = new CastInst(MCall, MI->getType(), "", I);
161       else
162         MCast = Constant::getNullValue(MI->getType());
163
164       // Replace all uses of the old malloc inst with the cast inst
165       MI->replaceAllUsesWith(MCast);
166       I = --BBIL.erase(I);         // remove and delete the malloc instr...
167       Changed = true;
168       ++NumLowered;
169     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
170       const FunctionType *FreeFTy = FreeFunc->getFunctionType();
171       std::vector<Value*> FreeArgs;
172
173       if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
174         Value *MCast = FI->getOperand(0);
175         if (FreeFTy->getNumParams() > 0 &&
176             FreeFTy->getParamType(0) != MCast->getType())
177           MCast = new CastInst(MCast, FreeFTy->getParamType(0), "", I);
178         FreeArgs.push_back(MCast);
179       }
180
181       // If malloc is prototyped to take extra arguments, pass nulls.
182       for (unsigned i = 1; i < FreeFTy->getNumParams(); ++i)
183        FreeArgs.push_back(Constant::getNullValue(FreeFTy->getParamType(i)));
184
185       // Insert a call to the free function...
186       (new CallInst(FreeFunc, FreeArgs, "", I))->setTailCall();
187
188       // Delete the old free instruction
189       I = --BBIL.erase(I);
190       Changed = true;
191       ++NumLowered;
192     }
193   }
194
195   return Changed;
196 }
197