Change inferred getCast into specific getCast. Passes all tests.
[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::getIntegerCast(cast<Constant>(MallocArg), 
126                                                IntPtrTy, true /*SExt*/);
127
128       if (MI->isArrayAllocation()) {
129         if (isa<ConstantInt>(MallocArg) &&
130             cast<ConstantInt>(MallocArg)->getZExtValue() == 1) {
131           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
132         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
133           CO = ConstantExpr::getIntegerCast(CO, IntPtrTy, true /*SExt*/);
134           MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
135         } else {
136           Value *Scale = MI->getOperand(0);
137           if (Scale->getType() != IntPtrTy)
138             Scale = CastInst::createInferredCast(Scale, IntPtrTy, "", I);
139
140           // Multiply it by the array size if necessary...
141           MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
142                                              MallocArg, "", I);
143         }
144       }
145
146       const FunctionType *MallocFTy = MallocFunc->getFunctionType();
147       std::vector<Value*> MallocArgs;
148
149       if (MallocFTy->getNumParams() > 0 || MallocFTy->isVarArg()) {
150         if (MallocFTy->isVarArg()) {
151           if (MallocArg->getType() != IntPtrTy)
152             MallocArg = CastInst::createInferredCast(MallocArg, IntPtrTy, "", 
153                                                      I);
154         } else if (MallocFTy->getNumParams() > 0 &&
155                    MallocFTy->getParamType(0) != Type::UIntTy)
156           MallocArg = 
157             CastInst::createInferredCast(MallocArg, MallocFTy->getParamType(0),
158                                          "",I);
159         MallocArgs.push_back(MallocArg);
160       }
161
162       // If malloc is prototyped to take extra arguments, pass nulls.
163       for (unsigned i = 1; i < MallocFTy->getNumParams(); ++i)
164        MallocArgs.push_back(Constant::getNullValue(MallocFTy->getParamType(i)));
165
166       // Create the call to Malloc...
167       CallInst *MCall = new CallInst(MallocFunc, MallocArgs, "", I);
168       MCall->setTailCall();
169
170       // Create a cast instruction to convert to the right type...
171       Value *MCast;
172       if (MCall->getType() != Type::VoidTy)
173         MCast = CastInst::createInferredCast(MCall, MI->getType(), "", I);
174       else
175         MCast = Constant::getNullValue(MI->getType());
176
177       // Replace all uses of the old malloc inst with the cast inst
178       MI->replaceAllUsesWith(MCast);
179       I = --BBIL.erase(I);         // remove and delete the malloc instr...
180       Changed = true;
181       ++NumLowered;
182     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
183       const FunctionType *FreeFTy = FreeFunc->getFunctionType();
184       std::vector<Value*> FreeArgs;
185
186       if (FreeFTy->getNumParams() > 0 || FreeFTy->isVarArg()) {
187         Value *MCast = FI->getOperand(0);
188         if (FreeFTy->getNumParams() > 0 &&
189             FreeFTy->getParamType(0) != MCast->getType())
190           MCast = CastInst::createInferredCast(MCast, FreeFTy->getParamType(0), 
191                                                "", 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