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