d7ca3134cf2d8450f07acc468708a1054ad80b6f
[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 is distributed under the University of Illinois Open Source
6 // 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/LLVMContext.h"
23 #include "llvm/Pass.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Support/Compiler.h"
27 using namespace llvm;
28
29 STATISTIC(NumLowered, "Number of allocations lowered");
30
31 namespace {
32   /// LowerAllocations - Turn malloc and free instructions into %malloc and
33   /// %free calls.
34   ///
35   class VISIBILITY_HIDDEN LowerAllocations : public BasicBlockPass {
36     Constant *MallocFunc;   // Functions in the module we are processing
37     Constant *FreeFunc;     // Initialized by doInitialization
38     bool LowerMallocArgToInteger;
39   public:
40     static char ID; // Pass ID, replacement for typeid
41     explicit LowerAllocations(bool LowerToInt = false)
42       : BasicBlockPass(&ID), MallocFunc(0), FreeFunc(0), 
43         LowerMallocArgToInteger(LowerToInt) {}
44
45     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
46       AU.addRequired<TargetData>();
47       AU.setPreservesCFG();
48
49       // This is a cluster of orthogonal Transforms:
50       AU.addPreserved<UnifyFunctionExitNodes>();
51       AU.addPreservedID(PromoteMemoryToRegisterID);
52       AU.addPreservedID(LowerSwitchID);
53       AU.addPreservedID(LowerInvokePassID);
54     }
55
56     /// doPassInitialization - For the lower allocations pass, this ensures that
57     /// a module contains a declaration for a malloc and a free function.
58     ///
59     bool doInitialization(Module &M);
60
61     virtual bool doInitialization(Function &F) {
62       return doInitialization(*F.getParent());
63     }
64
65     /// runOnBasicBlock - This method does the actual work of converting
66     /// instructions over, assuming that the pass has already been initialized.
67     ///
68     bool runOnBasicBlock(BasicBlock &BB);
69   };
70 }
71
72 char LowerAllocations::ID = 0;
73 static RegisterPass<LowerAllocations>
74 X("lowerallocs", "Lower allocations from instructions to calls");
75
76 // Publically exposed interface to pass...
77 const PassInfo *const llvm::LowerAllocationsID = &X;
78 // createLowerAllocationsPass - Interface to this file...
79 Pass *llvm::createLowerAllocationsPass(bool LowerMallocArgToInteger) {
80   return new LowerAllocations(LowerMallocArgToInteger);
81 }
82
83
84 // doInitialization - For the lower allocations pass, this ensures that a
85 // module contains a declaration for a malloc and a free function.
86 //
87 // This function is always successful.
88 //
89 bool LowerAllocations::doInitialization(Module &M) {
90   // Ensure context initialization.
91   BasicBlockPass::doInitialization(M);
92
93   const Type *BPTy = Context->getPointerTypeUnqual(Type::Int8Ty);
94   // Prototype malloc as "char* malloc(...)", because we don't know in
95   // doInitialization whether size_t is int or long.
96   FunctionType *FT = Context->getFunctionType(BPTy, true);
97   MallocFunc = M.getOrInsertFunction("malloc", FT);
98   FreeFunc = M.getOrInsertFunction("free"  , Type::VoidTy, BPTy, (Type *)0);
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 i8 *malloc(size)
120       Value *MallocArg;
121       if (LowerMallocArgToInteger)
122         MallocArg = Context->getConstantInt(Type::Int64Ty,
123                                      TD.getTypeAllocSize(AllocTy));
124       else
125         MallocArg = Context->getConstantExprSizeOf(AllocTy);
126       MallocArg =
127            Context->getConstantExprTruncOrBitCast(cast<Constant>(MallocArg), 
128                                                   IntPtrTy);
129
130       if (MI->isArrayAllocation()) {
131         if (isa<ConstantInt>(MallocArg) &&
132             cast<ConstantInt>(MallocArg)->isOne()) {
133           MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
134         } else if (Constant *CO = dyn_cast<Constant>(MI->getOperand(0))) {
135           CO =
136               Context->getConstantExprIntegerCast(CO, IntPtrTy, false /*ZExt*/);
137           MallocArg = Context->getConstantExprMul(CO, 
138                                                   cast<Constant>(MallocArg));
139         } else {
140           Value *Scale = MI->getOperand(0);
141           if (Scale->getType() != IntPtrTy)
142             Scale = CastInst::CreateIntegerCast(Scale, IntPtrTy, false /*ZExt*/,
143                                                 "", I);
144
145           // Multiply it by the array size if necessary...
146           MallocArg = BinaryOperator::Create(Instruction::Mul, Scale,
147                                              MallocArg, "", I);
148         }
149       }
150
151       // Create the call to Malloc.
152       CallInst *MCall = CallInst::Create(MallocFunc, MallocArg, "", I);
153       MCall->setTailCall();
154
155       // Create a cast instruction to convert to the right type...
156       Value *MCast;
157       if (MCall->getType() != Type::VoidTy)
158         MCast = new BitCastInst(MCall, MI->getType(), "", I);
159       else
160         MCast = Context->getNullValue(MI->getType());
161
162       // Replace all uses of the old malloc inst with the cast inst
163       MI->replaceAllUsesWith(MCast);
164       I = --BBIL.erase(I);         // remove and delete the malloc instr...
165       Changed = true;
166       ++NumLowered;
167     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
168       Value *PtrCast = 
169         new BitCastInst(FI->getOperand(0),
170                         Context->getPointerTypeUnqual(Type::Int8Ty), "", I);
171
172       // Insert a call to the free function...
173       CallInst::Create(FreeFunc, PtrCast, "", I)->setTailCall();
174
175       // Delete the old free instruction
176       I = --BBIL.erase(I);
177       Changed = true;
178       ++NumLowered;
179     }
180   }
181
182   return Changed;
183 }
184