Implement Transforms/Inline/inline-tail.ll
[oota-llvm.git] / lib / Transforms / Utils / InlineFunction.cpp
1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
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 // This file implements inlining of a function into a call site, resolving
11 // parameters and the return value as appropriate.
12 //
13 // FIXME: This pass should transform alloca instructions in the called function
14 // into alloca/dealloca pairs!  Or perhaps it should refuse to inline them!
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/Utils/Cloning.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Support/CallSite.h"
25 using namespace llvm;
26
27 bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
28 bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));}
29
30 // InlineFunction - This function inlines the called function into the basic
31 // block of the caller.  This returns false if it is not possible to inline this
32 // call.  The program is still in a well defined state if this occurs though.
33 //
34 // Note that this only does one level of inlining.  For example, if the
35 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
36 // exists in the instruction stream.  Similiarly this will inline a recursive
37 // function by one level.
38 //
39 bool llvm::InlineFunction(CallSite CS) {
40   Instruction *TheCall = CS.getInstruction();
41   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
42          "Instruction not in function!");
43
44   const Function *CalledFunc = CS.getCalledFunction();
45   if (CalledFunc == 0 ||          // Can't inline external function or indirect
46       CalledFunc->isExternal() || // call, or call to a vararg function!
47       CalledFunc->getFunctionType()->isVarArg()) return false;
48
49
50   // If the call to the callee is a non-tail call, we must clear the 'tail'
51   // flags on any calls that we inline.
52   bool MustClearTailCallFlags =
53     isa<CallInst>(TheCall) || !cast<CallInst>(TheCall)->isTailCall();
54
55   BasicBlock *OrigBB = TheCall->getParent();
56   Function *Caller = OrigBB->getParent();
57
58   // Get an iterator to the last basic block in the function, which will have
59   // the new function inlined after it.
60   //
61   Function::iterator LastBlock = &Caller->back();
62
63   // Make sure to capture all of the return instructions from the cloned
64   // function.
65   std::vector<ReturnInst*> Returns;
66   { // Scope to destroy ValueMap after cloning.
67     // Calculate the vector of arguments to pass into the function cloner...
68     std::map<const Value*, Value*> ValueMap;
69     assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
70            std::distance(CS.arg_begin(), CS.arg_end()) &&
71            "No varargs calls can be inlined!");
72
73     CallSite::arg_iterator AI = CS.arg_begin();
74     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
75            E = CalledFunc->arg_end(); I != E; ++I, ++AI)
76       ValueMap[I] = *AI;
77
78     // Clone the entire body of the callee into the caller.
79     CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
80   }
81
82   // Remember the first block that is newly cloned over.
83   Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
84
85   // If there are any alloca instructions in the block that used to be the entry
86   // block for the callee, move them to the entry block of the caller.  First
87   // calculate which instruction they should be inserted before.  We insert the
88   // instructions at the end of the current alloca list.
89   //
90   if (isa<AllocaInst>(FirstNewBlock->begin())) {
91     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
92     for (BasicBlock::iterator I = FirstNewBlock->begin(),
93            E = FirstNewBlock->end(); I != E; )
94       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
95         if (isa<Constant>(AI->getArraySize())) {
96           // Scan for the block of allocas that we can move over.
97           while (isa<AllocaInst>(I) &&
98                  isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
99             ++I;
100
101           // Transfer all of the allocas over in a block.  Using splice means
102           // that they instructions aren't removed from the symbol table, then
103           // reinserted.
104           Caller->front().getInstList().splice(InsertPoint,
105                                                FirstNewBlock->getInstList(),
106                                                AI, I);
107         }
108   }
109
110   // If we are inlining tail call instruction through an invoke or 
111   if (MustClearTailCallFlags) {
112     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
113          BB != E; ++BB)
114       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
115         if (CallInst *CI = dyn_cast<CallInst>(I))
116           CI->setTailCall(false);
117   }
118
119   // If we are inlining for an invoke instruction, we must make sure to rewrite
120   // any inlined 'unwind' instructions into branches to the invoke exception
121   // destination, and call instructions into invoke instructions.
122   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
123     BasicBlock *InvokeDest = II->getUnwindDest();
124     std::vector<Value*> InvokeDestPHIValues;
125
126     // If there are PHI nodes in the exceptional destination block, we need to
127     // keep track of which values came into them from this invoke, then remove
128     // the entry for this block.
129     for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
130       PHINode *PN = cast<PHINode>(I);
131       // Save the value to use for this edge...
132       InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
133     }
134
135     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
136          BB != E; ++BB) {
137       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
138         // We only need to check for function calls: inlined invoke instructions
139         // require no special handling...
140         if (CallInst *CI = dyn_cast<CallInst>(I)) {
141           // Convert this function call into an invoke instruction... if it's
142           // not an intrinsic function call (which are known to not unwind).
143           if (CI->getCalledFunction() &&
144               CI->getCalledFunction()->getIntrinsicID()) {
145             ++I;
146           } else {
147             // First, split the basic block...
148             BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
149
150             // Next, create the new invoke instruction, inserting it at the end
151             // of the old basic block.
152             InvokeInst *II =
153               new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
154                             std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
155                              CI->getName(), BB->getTerminator());
156
157             // Make sure that anything using the call now uses the invoke!
158             CI->replaceAllUsesWith(II);
159
160             // Delete the unconditional branch inserted by splitBasicBlock
161             BB->getInstList().pop_back();
162             Split->getInstList().pop_front();  // Delete the original call
163
164             // Update any PHI nodes in the exceptional block to indicate that
165             // there is now a new entry in them.
166             unsigned i = 0;
167             for (BasicBlock::iterator I = InvokeDest->begin();
168                  isa<PHINode>(I); ++I, ++i) {
169               PHINode *PN = cast<PHINode>(I);
170               PN->addIncoming(InvokeDestPHIValues[i], BB);
171             }
172
173             // This basic block is now complete, start scanning the next one.
174             break;
175           }
176         } else {
177           ++I;
178         }
179       }
180
181       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
182         // An UnwindInst requires special handling when it gets inlined into an
183         // invoke site.  Once this happens, we know that the unwind would cause
184         // a control transfer to the invoke exception destination, so we can
185         // transform it into a direct branch to the exception destination.
186         new BranchInst(InvokeDest, UI);
187
188         // Delete the unwind instruction!
189         UI->getParent()->getInstList().pop_back();
190
191         // Update any PHI nodes in the exceptional block to indicate that
192         // there is now a new entry in them.
193         unsigned i = 0;
194         for (BasicBlock::iterator I = InvokeDest->begin();
195              isa<PHINode>(I); ++I, ++i) {
196           PHINode *PN = cast<PHINode>(I);
197           PN->addIncoming(InvokeDestPHIValues[i], BB);
198         }
199       }
200     }
201
202     // Now that everything is happy, we have one final detail.  The PHI nodes in
203     // the exception destination block still have entries due to the original
204     // invoke instruction.  Eliminate these entries (which might even delete the
205     // PHI node) now.
206     InvokeDest->removePredecessor(II->getParent());
207   }
208
209   // If we cloned in _exactly one_ basic block, and if that block ends in a
210   // return instruction, we splice the body of the inlined callee directly into
211   // the calling basic block.
212   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
213     // Move all of the instructions right before the call.
214     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
215                                  FirstNewBlock->begin(), FirstNewBlock->end());
216     // Remove the cloned basic block.
217     Caller->getBasicBlockList().pop_back();
218
219     // If the call site was an invoke instruction, add a branch to the normal
220     // destination.
221     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
222       new BranchInst(II->getNormalDest(), TheCall);
223
224     // If the return instruction returned a value, replace uses of the call with
225     // uses of the returned value.
226     if (!TheCall->use_empty())
227       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
228
229     // Since we are now done with the Call/Invoke, we can delete it.
230     TheCall->getParent()->getInstList().erase(TheCall);
231
232     // Since we are now done with the return instruction, delete it also.
233     Returns[0]->getParent()->getInstList().erase(Returns[0]);
234
235     // We are now done with the inlining.
236     return true;
237   }
238
239   // Otherwise, we have the normal case, of more than one block to inline or
240   // multiple return sites.
241
242   // We want to clone the entire callee function into the hole between the
243   // "starter" and "ender" blocks.  How we accomplish this depends on whether
244   // this is an invoke instruction or a call instruction.
245   BasicBlock *AfterCallBB;
246   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
247
248     // Add an unconditional branch to make this look like the CallInst case...
249     BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
250
251     // Split the basic block.  This guarantees that no PHI nodes will have to be
252     // updated due to new incoming edges, and make the invoke case more
253     // symmetric to the call case.
254     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
255                                           CalledFunc->getName()+".exit");
256
257   } else {  // It's a call
258     // If this is a call instruction, we need to split the basic block that
259     // the call lives in.
260     //
261     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
262                                           CalledFunc->getName()+".exit");
263   }
264
265   // Change the branch that used to go to AfterCallBB to branch to the first
266   // basic block of the inlined function.
267   //
268   TerminatorInst *Br = OrigBB->getTerminator();
269   assert(Br && Br->getOpcode() == Instruction::Br &&
270          "splitBasicBlock broken!");
271   Br->setOperand(0, FirstNewBlock);
272
273
274   // Now that the function is correct, make it a little bit nicer.  In
275   // particular, move the basic blocks inserted from the end of the function
276   // into the space made by splitting the source basic block.
277   //
278   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
279                                      FirstNewBlock, Caller->end());
280
281   // Handle all of the return instructions that we just cloned in, and eliminate
282   // any users of the original call/invoke instruction.
283   if (Returns.size() > 1) {
284     // The PHI node should go at the front of the new basic block to merge all
285     // possible incoming values.
286     //
287     PHINode *PHI = 0;
288     if (!TheCall->use_empty()) {
289       PHI = new PHINode(CalledFunc->getReturnType(),
290                         TheCall->getName(), AfterCallBB->begin());
291
292       // Anything that used the result of the function call should now use the
293       // PHI node as their operand.
294       //
295       TheCall->replaceAllUsesWith(PHI);
296     }
297
298     // Loop over all of the return instructions, turning them into unconditional
299     // branches to the merge point now, and adding entries to the PHI node as
300     // appropriate.
301     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
302       ReturnInst *RI = Returns[i];
303
304       if (PHI) {
305         assert(RI->getReturnValue() && "Ret should have value!");
306         assert(RI->getReturnValue()->getType() == PHI->getType() &&
307                "Ret value not consistent in function!");
308         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
309       }
310
311       // Add a branch to the merge point where the PHI node lives if it exists.
312       new BranchInst(AfterCallBB, RI);
313
314       // Delete the return instruction now
315       RI->getParent()->getInstList().erase(RI);
316     }
317
318   } else if (!Returns.empty()) {
319     // Otherwise, if there is exactly one return value, just replace anything
320     // using the return value of the call with the computed value.
321     if (!TheCall->use_empty())
322       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
323
324     // Splice the code from the return block into the block that it will return
325     // to, which contains the code that was after the call.
326     BasicBlock *ReturnBB = Returns[0]->getParent();
327     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
328                                       ReturnBB->getInstList());
329
330     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
331     ReturnBB->replaceAllUsesWith(AfterCallBB);
332
333     // Delete the return instruction now and empty ReturnBB now.
334     Returns[0]->eraseFromParent();
335     ReturnBB->eraseFromParent();
336   } else if (!TheCall->use_empty()) {
337     // No returns, but something is using the return value of the call.  Just
338     // nuke the result.
339     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
340   }
341
342   // Since we are now done with the Call/Invoke, we can delete it.
343   TheCall->eraseFromParent();
344
345   // We should always be able to fold the entry block of the function into the
346   // single predecessor of the block...
347   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
348   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
349
350   // Splice the code entry block into calling block, right before the
351   // unconditional branch.
352   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
353   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
354
355   // Remove the unconditional branch.
356   OrigBB->getInstList().erase(Br);
357
358   // Now we can remove the CalleeEntry block, which is now empty.
359   Caller->getBasicBlockList().erase(CalleeEntry);
360   return true;
361 }