Start using the new function cloning header
[oota-llvm.git] / lib / Transforms / IPO / InlineSimple.cpp
1 //===- FunctionInlining.cpp - Code to perform function inlining -----------===//
2 //
3 // This file implements inlining of functions.
4 //
5 // Specifically, this:
6 //   * Exports functionality to inline any function call
7 //   * Inlines functions that consist of a single basic block
8 //   * Is able to inline ANY function call
9 //   . Has a smart heuristic for when to inline a function
10 //
11 // Notice that:
12 //   * This pass opens up a lot of opportunities for constant propogation.  It
13 //     is a good idea to to run a constant propogation pass, then a DCE pass 
14 //     sometime after running this pass.
15 //
16 // FIXME: This pass should transform alloca instructions in the called function
17 //        into malloc/free pairs!
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Transforms/IPO.h"
22 #include "llvm/Transforms/Utils/Cloning.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iPHINode.h"
27 #include "llvm/iOther.h"
28 #include "llvm/Type.h"
29 #include "Support/Statistic.h"
30 #include <algorithm>
31
32 static Statistic<> NumInlined("inline", "Number of functions inlined");
33 using std::cerr;
34
35 // RemapInstruction - Convert the instruction operands from referencing the 
36 // current values into those specified by ValueMap.
37 //
38 static inline void RemapInstruction(Instruction *I, 
39                                     std::map<const Value *, Value*> &ValueMap) {
40
41   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
42     const Value *Op = I->getOperand(op);
43     Value *V = ValueMap[Op];
44     if (!V && (isa<GlobalValue>(Op) || isa<Constant>(Op)))
45       continue;  // Globals and constants don't get relocated
46
47     if (!V) {
48       cerr << "Val = \n" << Op << "Addr = " << (void*)Op;
49       cerr << "\nInst = " << I;
50     }
51     assert(V && "Referenced value not in value map!");
52     I->setOperand(op, V);
53   }
54 }
55
56 // InlineFunction - This function forcibly inlines the called function into the
57 // basic block of the caller.  This returns false if it is not possible to
58 // inline this call.  The program is still in a well defined state if this 
59 // occurs though.
60 //
61 // Note that this only does one level of inlining.  For example, if the 
62 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now 
63 // exists in the instruction stream.  Similiarly this will inline a recursive
64 // function by one level.
65 //
66 bool InlineFunction(CallInst *CI) {
67   assert(isa<CallInst>(CI) && "InlineFunction only works on CallInst nodes");
68   assert(CI->getParent() && "Instruction not embedded in basic block!");
69   assert(CI->getParent()->getParent() && "Instruction not in function!");
70
71   const Function *CalledFunc = CI->getCalledFunction();
72   if (CalledFunc == 0 ||   // Can't inline external function or indirect call!
73       CalledFunc->isExternal()) return false;
74
75   //cerr << "Inlining " << CalledFunc->getName() << " into " 
76   //     << CurrentMeth->getName() << "\n";
77
78   BasicBlock *OrigBB = CI->getParent();
79
80   // Call splitBasicBlock - The original basic block now ends at the instruction
81   // immediately before the call.  The original basic block now ends with an
82   // unconditional branch to NewBB, and NewBB starts with the call instruction.
83   //
84   BasicBlock *NewBB = OrigBB->splitBasicBlock(CI);
85   NewBB->setName("InlinedFunctionReturnNode");
86
87   // Remove (unlink) the CallInst from the start of the new basic block.  
88   NewBB->getInstList().remove(CI);
89
90   // If we have a return value generated by this call, convert it into a PHI 
91   // node that gets values from each of the old RET instructions in the original
92   // function.
93   //
94   PHINode *PHI = 0;
95   if (CalledFunc->getReturnType() != Type::VoidTy) {
96     // The PHI node should go at the front of the new basic block to merge all 
97     // possible incoming values.
98     //
99     PHI = new PHINode(CalledFunc->getReturnType(), CI->getName(),
100                       NewBB->begin());
101
102     // Anything that used the result of the function call should now use the PHI
103     // node as their operand.
104     //
105     CI->replaceAllUsesWith(PHI);
106   }
107
108   // Keep a mapping between the original function's values and the new
109   // duplicated code's values.  This includes all of: Function arguments,
110   // instruction values, constant pool entries, and basic blocks.
111   //
112   std::map<const Value *, Value*> ValueMap;
113
114   // Add the function arguments to the mapping: (start counting at 1 to skip the
115   // function reference itself)
116   //
117   Function::const_aiterator PTI = CalledFunc->abegin();
118   for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
119     ValueMap[PTI] = CI->getOperand(a);
120   
121   ValueMap[NewBB] = NewBB;  // Returns get converted to reference NewBB
122
123   // Loop over all of the basic blocks in the function, inlining them as 
124   // appropriate.  Keep track of the first basic block of the function...
125   //
126   for (Function::const_iterator BB = CalledFunc->begin(); 
127        BB != CalledFunc->end(); ++BB) {
128     assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
129     
130     // Create a new basic block to copy instructions into!
131     BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
132     if (BB->hasName()) IBB->setName(BB->getName()+".i");  // .i = inlined once
133
134     ValueMap[BB] = IBB;                       // Add basic block mapping.
135
136     // Make sure to capture the mapping that a return will use...
137     // TODO: This assumes that the RET is returning a value computed in the same
138     //       basic block as the return was issued from!
139     //
140     const TerminatorInst *TI = BB->getTerminator();
141    
142     // Loop over all instructions copying them over...
143     Instruction *NewInst;
144     for (BasicBlock::const_iterator II = BB->begin();
145          II != --BB->end(); ++II) {
146       IBB->getInstList().push_back((NewInst = II->clone()));
147       ValueMap[II] = NewInst;                  // Add instruction map to value.
148       if (II->hasName())
149         NewInst->setName(II->getName()+".i");  // .i = inlined once
150     }
151
152     // Copy over the terminator now...
153     switch (TI->getOpcode()) {
154     case Instruction::Ret: {
155       const ReturnInst *RI = cast<ReturnInst>(TI);
156
157       if (PHI) {   // The PHI node should include this value!
158         assert(RI->getReturnValue() && "Ret should have value!");
159         assert(RI->getReturnValue()->getType() == PHI->getType() && 
160                "Ret value not consistent in function!");
161         PHI->addIncoming((Value*)RI->getReturnValue(),
162                          (BasicBlock*)cast<BasicBlock>(&*BB));
163       }
164
165       // Add a branch to the code that was after the original Call.
166       IBB->getInstList().push_back(new BranchInst(NewBB));
167       break;
168     }
169     case Instruction::Br:
170       IBB->getInstList().push_back(TI->clone());
171       break;
172
173     default:
174       cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
175       abort();
176     }
177   }
178
179
180   // Loop over all of the instructions in the function, fixing up operand 
181   // references as we go.  This uses ValueMap to do all the hard work.
182   //
183   for (Function::const_iterator BB = CalledFunc->begin(); 
184        BB != CalledFunc->end(); ++BB) {
185     BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
186
187     // Loop over all instructions, fixing each one as we find it...
188     //
189     for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); ++II)
190       RemapInstruction(II, ValueMap);
191   }
192
193   if (PHI) {
194     RemapInstruction(PHI, ValueMap);  // Fix the PHI node also...
195
196     // Check to see if the PHI node only has one argument.  This is a common
197     // case resulting from there only being a single return instruction in the
198     // function call.  Because this is so common, eliminate the PHI node.
199     //
200     if (PHI->getNumIncomingValues() == 1) {
201       PHI->replaceAllUsesWith(PHI->getIncomingValue(0));
202       PHI->getParent()->getInstList().erase(PHI);
203     }
204   }
205
206   // Change the branch that used to go to NewBB to branch to the first basic 
207   // block of the inlined function.
208   //
209   TerminatorInst *Br = OrigBB->getTerminator();
210   assert(Br && Br->getOpcode() == Instruction::Br && 
211          "splitBasicBlock broken!");
212   Br->setOperand(0, ValueMap[&CalledFunc->front()]);
213
214   // Since we are now done with the CallInst, we can finally delete it.
215   delete CI;
216   return true;
217 }
218
219 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
220   assert(CI->getParent() && CI->getParent()->getParent() && 
221          "Call not embedded into a function!");
222
223   // Don't inline a recursive call.
224   if (CI->getParent()->getParent() == F) return false;
225
226   // Don't inline something too big.  This is a really crappy heuristic
227   if (F->size() > 3) return false;
228
229   // Don't inline into something too big. This is a **really** crappy heuristic
230   if (CI->getParent()->getParent()->size() > 10) return false;
231
232   // Go ahead and try just about anything else.
233   return true;
234 }
235
236
237 static inline bool DoFunctionInlining(BasicBlock *BB) {
238   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
239     if (CallInst *CI = dyn_cast<CallInst>(&*I)) {
240       // Check to see if we should inline this function
241       Function *F = CI->getCalledFunction();
242       if (F && ShouldInlineFunction(CI, F)) {
243         return InlineFunction(CI);
244       }
245     }
246   }
247   return false;
248 }
249
250 // doFunctionInlining - Use a heuristic based approach to inline functions that
251 // seem to look good.
252 //
253 static bool doFunctionInlining(Function &F) {
254   bool Changed = false;
255
256   // Loop through now and inline instructions a basic block at a time...
257   for (Function::iterator I = F.begin(); I != F.end(); )
258     if (DoFunctionInlining(I)) {
259       ++NumInlined;
260       Changed = true;
261     } else {
262       ++I;
263     }
264
265   return Changed;
266 }
267
268 namespace {
269   struct FunctionInlining : public FunctionPass {
270     virtual bool runOnFunction(Function &F) {
271       return doFunctionInlining(F);
272     }
273   };
274   RegisterOpt<FunctionInlining> X("inline", "Function Integration/Inlining");
275 }
276
277 Pass *createFunctionInliningPass() { return new FunctionInlining(); }