* Add support for different "PassType's"
[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/FunctionInlining.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/iPHINode.h"
26 #include "llvm/iOther.h"
27 #include "llvm/Type.h"
28 #include "Support/StatisticReporter.h"
29 #include <algorithm>
30 #include <iostream>
31
32 static Statistic<> NumInlined("inline\t\t- 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     PHI = new PHINode(CalledFunc->getReturnType(), CI->getName());
97
98     // The PHI node should go at the front of the new basic block to merge all 
99     // possible incoming values.
100     //
101     NewBB->getInstList().push_front(PHI);
102
103     // Anything that used the result of the function call should now use the PHI
104     // node as their operand.
105     //
106     CI->replaceAllUsesWith(PHI);
107   }
108
109   // Keep a mapping between the original function's values and the new
110   // duplicated code's values.  This includes all of: Function arguments,
111   // instruction values, constant pool entries, and basic blocks.
112   //
113   std::map<const Value *, Value*> ValueMap;
114
115   // Add the function arguments to the mapping: (start counting at 1 to skip the
116   // function reference itself)
117   //
118   Function::const_aiterator PTI = CalledFunc->abegin();
119   for (unsigned a = 1, E = CI->getNumOperands(); a != E; ++a, ++PTI)
120     ValueMap[PTI] = CI->getOperand(a);
121   
122   ValueMap[NewBB] = NewBB;  // Returns get converted to reference NewBB
123
124   // Loop over all of the basic blocks in the function, inlining them as 
125   // appropriate.  Keep track of the first basic block of the function...
126   //
127   for (Function::const_iterator BB = CalledFunc->begin(); 
128        BB != CalledFunc->end(); ++BB) {
129     assert(BB->getTerminator() && "BasicBlock doesn't have terminator!?!?");
130     
131     // Create a new basic block to copy instructions into!
132     BasicBlock *IBB = new BasicBlock("", NewBB->getParent());
133     if (BB->hasName()) IBB->setName(BB->getName()+".i");  // .i = inlined once
134
135     ValueMap[BB] = IBB;                       // Add basic block mapping.
136
137     // Make sure to capture the mapping that a return will use...
138     // TODO: This assumes that the RET is returning a value computed in the same
139     //       basic block as the return was issued from!
140     //
141     const TerminatorInst *TI = BB->getTerminator();
142    
143     // Loop over all instructions copying them over...
144     Instruction *NewInst;
145     for (BasicBlock::const_iterator II = BB->begin();
146          II != --BB->end(); ++II) {
147       IBB->getInstList().push_back((NewInst = II->clone()));
148       ValueMap[II] = NewInst;                  // Add instruction map to value.
149       if (II->hasName())
150         NewInst->setName(II->getName()+".i");  // .i = inlined once
151     }
152
153     // Copy over the terminator now...
154     switch (TI->getOpcode()) {
155     case Instruction::Ret: {
156       const ReturnInst *RI = cast<ReturnInst>(TI);
157
158       if (PHI) {   // The PHI node should include this value!
159         assert(RI->getReturnValue() && "Ret should have value!");
160         assert(RI->getReturnValue()->getType() == PHI->getType() && 
161                "Ret value not consistent in function!");
162         PHI->addIncoming((Value*)RI->getReturnValue(),
163                          (BasicBlock*)cast<BasicBlock>(&*BB));
164       }
165
166       // Add a branch to the code that was after the original Call.
167       IBB->getInstList().push_back(new BranchInst(NewBB));
168       break;
169     }
170     case Instruction::Br:
171       IBB->getInstList().push_back(TI->clone());
172       break;
173
174     default:
175       cerr << "FunctionInlining: Don't know how to handle terminator: " << TI;
176       abort();
177     }
178   }
179
180
181   // Loop over all of the instructions in the function, fixing up operand 
182   // references as we go.  This uses ValueMap to do all the hard work.
183   //
184   for (Function::const_iterator BB = CalledFunc->begin(); 
185        BB != CalledFunc->end(); ++BB) {
186     BasicBlock *NBB = (BasicBlock*)ValueMap[BB];
187
188     // Loop over all instructions, fixing each one as we find it...
189     //
190     for (BasicBlock::iterator II = NBB->begin(); II != NBB->end(); ++II)
191       RemapInstruction(II, ValueMap);
192   }
193
194   if (PHI) RemapInstruction(PHI, ValueMap);  // Fix the PHI node also...
195
196   // Change the branch that used to go to NewBB to branch to the first basic 
197   // block of the inlined function.
198   //
199   TerminatorInst *Br = OrigBB->getTerminator();
200   assert(Br && Br->getOpcode() == Instruction::Br && 
201          "splitBasicBlock broken!");
202   Br->setOperand(0, ValueMap[&CalledFunc->front()]);
203
204   // Since we are now done with the CallInst, we can finally delete it.
205   delete CI;
206   return true;
207 }
208
209 static inline bool ShouldInlineFunction(const CallInst *CI, const Function *F) {
210   assert(CI->getParent() && CI->getParent()->getParent() && 
211          "Call not embedded into a function!");
212
213   // Don't inline a recursive call.
214   if (CI->getParent()->getParent() == F) return false;
215
216   // Don't inline something too big.  This is a really crappy heuristic
217   if (F->size() > 3) return false;
218
219   // Don't inline into something too big. This is a **really** crappy heuristic
220   if (CI->getParent()->getParent()->size() > 10) return false;
221
222   // Go ahead and try just about anything else.
223   return true;
224 }
225
226
227 static inline bool DoFunctionInlining(BasicBlock *BB) {
228   for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
229     if (CallInst *CI = dyn_cast<CallInst>(&*I)) {
230       // Check to see if we should inline this function
231       Function *F = CI->getCalledFunction();
232       if (F && ShouldInlineFunction(CI, F)) {
233         return InlineFunction(CI);
234       }
235     }
236   }
237   return false;
238 }
239
240 // doFunctionInlining - Use a heuristic based approach to inline functions that
241 // seem to look good.
242 //
243 static bool doFunctionInlining(Function &F) {
244   bool Changed = false;
245
246   // Loop through now and inline instructions a basic block at a time...
247   for (Function::iterator I = F.begin(); I != F.end(); )
248     if (DoFunctionInlining(I)) {
249       ++NumInlined;
250       Changed = true;
251     } else {
252       ++I;
253     }
254
255   return Changed;
256 }
257
258 namespace {
259   struct FunctionInlining : public FunctionPass {
260     virtual bool runOnFunction(Function &F) {
261       return doFunctionInlining(F);
262     }
263   };
264   RegisterOpt<FunctionInlining> X("inline", "Function Integration/Inlining");
265 }
266
267 Pass *createFunctionInliningPass() { return new FunctionInlining(); }