Use APInt safe isOne() method on ConstantInt instead of getZExtValue()==1
[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     Constant *MallocFunc;   // Functions in the module we are processing
36     Constant *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 Pass *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 *BPTy = PointerType::get(Type::Int8Ty);
88   // Prototype malloc as "char* malloc(...)", because we don't know in
89   // doInitialization whether size_t is int or long.
90   FunctionType *FT = FunctionType::get(BPTy, std::vector<const Type*>(), true);
91   MallocFunc = M.getOrInsertFunction("malloc", FT);
92   FreeFunc = M.getOrInsertFunction("free"  , Type::VoidTy, BPTy, (Type *)0);
93   return true;
94 }
95
96 // runOnBasicBlock - This method does the actual work of converting
97 // instructions over, assuming that the pass has already been initialized.
98 //
99 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
100   bool Changed = false;
101   assert(MallocFunc && FreeFunc && "Pass not initialized!");
102
103   BasicBlock::InstListType &BBIL = BB.getInstList();
104
105   const TargetData &TD = getAnalysis<TargetData>();
106   const Type *IntPtrTy = TD.getIntPtrType();
107
108   // Loop over all of the instructions, looking for malloc or free instructions
109   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
110     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
111       const Type *AllocTy = MI->getType()->getElementType();
112
113       // malloc(type) becomes sbyte *malloc(size)
114       Value *MallocArg;
115       if (LowerMallocArgToInteger)
116         MallocArg = ConstantInt::get(Type::Int64Ty, TD.getTypeSize(AllocTy));
117       else
118         MallocArg = ConstantExpr::getSizeOf(AllocTy);
119       MallocArg = ConstantExpr::getTruncOrBitCast(cast<Constant>(MallocArg), 
120                                                   IntPtrTy);
121
122       if (MI->isArrayAllocation()) {
123         if (isa<ConstantInt>(MallocArg) &&
124             cast<ConstantInt>(MallocArg)->isOne()) {
125           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
126         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
127           CO = ConstantExpr::getIntegerCast(CO, IntPtrTy, false /*ZExt*/);
128           MallocArg = ConstantExpr::getMul(CO, cast<Constant>(MallocArg));
129         } else {
130           Value *Scale = MI->getOperand(0);
131           if (Scale->getType() != IntPtrTy)
132             Scale = CastInst::createIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
133                                                 "", I);
134
135           // Multiply it by the array size if necessary...
136           MallocArg = BinaryOperator::create(Instruction::Mul, Scale,
137                                              MallocArg, "", I);
138         }
139       }
140
141       // Create the call to Malloc.
142       CallInst *MCall = new CallInst(MallocFunc, MallocArg, "", I);
143       MCall->setTailCall();
144
145       // Create a cast instruction to convert to the right type...
146       Value *MCast;
147       if (MCall->getType() != Type::VoidTy)
148         MCast = new BitCastInst(MCall, MI->getType(), "", I);
149       else
150         MCast = Constant::getNullValue(MI->getType());
151
152       // Replace all uses of the old malloc inst with the cast inst
153       MI->replaceAllUsesWith(MCast);
154       I = --BBIL.erase(I);         // remove and delete the malloc instr...
155       Changed = true;
156       ++NumLowered;
157     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
158       Value *PtrCast = new BitCastInst(FI->getOperand(0),
159                                        PointerType::get(Type::Int8Ty), "", I);
160
161       // Insert a call to the free function...
162       (new CallInst(FreeFunc, PtrCast, "", I))->setTailCall();
163
164       // Delete the old free instruction
165       I = --BBIL.erase(I);
166       Changed = true;
167       ++NumLowered;
168     }
169   }
170
171   return Changed;
172 }
173