Put all LLVM code into the llvm namespace, as per bug 109.
[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/iMemory.h"
19 #include "llvm/iOther.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Target/TargetData.h"
23 #include "Support/Statistic.h"
24
25 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 LowerAllocations : public BasicBlockPass {
34     Function *MallocFunc;   // Functions in the module we are processing
35     Function *FreeFunc;     // Initialized by doInitialization
36   public:
37     LowerAllocations() : MallocFunc(0), FreeFunc(0) {}
38
39     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
40       AU.addRequired<TargetData>();
41     }
42
43     /// doPassInitialization - For the lower allocations pass, this ensures that
44     /// a module contains a declaration for a malloc and a free function.
45     ///
46     bool doInitialization(Module &M);
47     
48     /// runOnBasicBlock - This method does the actual work of converting
49     /// instructions over, assuming that the pass has already been initialized.
50     ///
51     bool runOnBasicBlock(BasicBlock &BB);
52   };
53
54   RegisterOpt<LowerAllocations>
55   X("lowerallocs", "Lower allocations from instructions to calls");
56 }
57
58 // createLowerAllocationsPass - Interface to this file...
59 FunctionPass *createLowerAllocationsPass() {
60   return new LowerAllocations();
61 }
62
63
64 // doInitialization - For the lower allocations pass, this ensures that a
65 // module contains a declaration for a malloc and a free function.
66 //
67 // This function is always successful.
68 //
69 bool LowerAllocations::doInitialization(Module &M) {
70   const Type *SBPTy = PointerType::get(Type::SByteTy);
71   MallocFunc = M.getOrInsertFunction("malloc", SBPTy, Type::UIntTy, 0);
72   FreeFunc   = M.getOrInsertFunction("free"  , Type::VoidTy, SBPTy, 0);
73
74   return true;
75 }
76
77 // runOnBasicBlock - This method does the actual work of converting
78 // instructions over, assuming that the pass has already been initialized.
79 //
80 bool LowerAllocations::runOnBasicBlock(BasicBlock &BB) {
81   bool Changed = false;
82   assert(MallocFunc && FreeFunc && "Pass not initialized!");
83
84   BasicBlock::InstListType &BBIL = BB.getInstList();
85   TargetData &DataLayout = getAnalysis<TargetData>();
86
87   // Loop over all of the instructions, looking for malloc or free instructions
88   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) {
89     if (MallocInst *MI = dyn_cast<MallocInst>(I)) {
90       const Type *AllocTy = MI->getType()->getElementType();
91       
92       // Get the number of bytes to be allocated for one element of the
93       // requested type...
94       unsigned Size = DataLayout.getTypeSize(AllocTy);
95       
96       // malloc(type) becomes sbyte *malloc(constint)
97       Value *MallocArg = ConstantUInt::get(Type::UIntTy, Size);
98       if (MI->getNumOperands() && Size == 1) {
99         MallocArg = MI->getOperand(0);         // Operand * 1 = Operand
100       } else if (MI->getNumOperands()) {
101         // Multiply it by the array size if necessary...
102         MallocArg = BinaryOperator::create(Instruction::Mul, MI->getOperand(0),
103                                            MallocArg, "", I);
104       }
105       
106       // Create the call to Malloc...
107       CallInst *MCall = new CallInst(MallocFunc,
108                                      std::vector<Value*>(1, MallocArg), "", I);
109       
110       // Create a cast instruction to convert to the right type...
111       CastInst *MCast = new CastInst(MCall, MI->getType(), "", I);
112       
113       // Replace all uses of the old malloc inst with the cast inst
114       MI->replaceAllUsesWith(MCast);
115       I = --BBIL.erase(I);         // remove and delete the malloc instr...
116       Changed = true;
117       ++NumLowered;
118     } else if (FreeInst *FI = dyn_cast<FreeInst>(I)) {
119       // Cast the argument to free into a ubyte*...
120       CastInst *MCast = new CastInst(FI->getOperand(0), 
121                                      PointerType::get(Type::SByteTy), "", I);
122       
123       // Insert a call to the free function...
124       CallInst *FCall = new CallInst(FreeFunc, std::vector<Value*>(1, MCast),
125                                      "", I);
126       
127       // Delete the old free instruction
128       I = --BBIL.erase(I);
129       Changed = true;
130       ++NumLowered;
131     }
132   }
133
134   return Changed;
135 }
136
137 } // End llvm namespace