Various cleanups and efficiency improvements
[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 malloc/free pairs!  Or perhaps it should refuse to inline them!
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Transforms/Utils/Cloning.h"
19 #include "llvm/Constant.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 #include "llvm/Transforms/Utils/Local.h"
26
27 bool InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
28 bool 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 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   BasicBlock *OrigBB = TheCall->getParent();
50   Function *Caller = OrigBB->getParent();
51
52   // We want to clone the entire callee function into the whole between the
53   // "starter" and "ender" blocks.  How we accomplish this depends on whether
54   // this is an invoke instruction or a call instruction.
55
56   BasicBlock *InvokeDest = 0;     // Exception handling destination
57   std::vector<Value*> InvokeDestPHIValues; // Values for PHI nodes in InvokeDest
58   BasicBlock *AfterCallBB;
59
60   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
61     InvokeDest = II->getExceptionalDest();
62
63     // If there are PHI nodes in the exceptional destination block, we need to
64     // keep track of which values came into them from this invoke, then remove
65     // the entry for this block.
66     for (BasicBlock::iterator I = InvokeDest->begin();
67          PHINode *PN = dyn_cast<PHINode>(I); ++I) {
68       // Save the value to use for this edge...
69       InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
70     }
71
72     // Add an unconditional branch to make this look like the CallInst case...
73     BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
74
75     // Split the basic block.  This guarantees that no PHI nodes will have to be
76     // updated due to new incoming edges, and make the invoke case more
77     // symmetric to the call case.
78     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
79                                           CalledFunc->getName()+".entry");
80
81     // Remove (unlink) the InvokeInst from the function...
82     OrigBB->getInstList().remove(TheCall);
83
84   } else {  // It's a call
85     // If this is a call instruction, we need to split the basic block that the
86     // call lives in.
87     //
88     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
89                                           CalledFunc->getName()+".entry");
90     // Remove (unlink) the CallInst from the function...
91     AfterCallBB->getInstList().remove(TheCall);
92   }
93
94   // If we have a return value generated by this call, convert it into a PHI 
95   // node that gets values from each of the old RET instructions in the original
96   // function.
97   //
98   PHINode *PHI = 0;
99   if (!TheCall->use_empty()) {
100     // The PHI node should go at the front of the new basic block to merge all 
101     // possible incoming values.
102     //
103     PHI = new PHINode(CalledFunc->getReturnType(), TheCall->getName(),
104                       AfterCallBB->begin());
105
106     // Anything that used the result of the function call should now use the PHI
107     // node as their operand.
108     //
109     TheCall->replaceAllUsesWith(PHI);
110   }
111
112   // Get an iterator to the last basic block in the function, which will have
113   // the new function inlined after it.
114   //
115   Function::iterator LastBlock = &Caller->back();
116
117   // Calculate the vector of arguments to pass into the function cloner...
118   std::map<const Value*, Value*> ValueMap;
119   assert(std::distance(CalledFunc->abegin(), CalledFunc->aend()) == 
120          std::distance(CS.arg_begin(), CS.arg_end()) &&
121          "No varargs calls can be inlined!");
122
123   CallSite::arg_iterator AI = CS.arg_begin();
124   for (Function::const_aiterator I = CalledFunc->abegin(), E=CalledFunc->aend();
125        I != E; ++I, ++AI)
126     ValueMap[I] = *AI;
127
128   // Since we are now done with the Call/Invoke, we can delete it.
129   delete TheCall;
130
131   // Make a vector to capture the return instructions in the cloned function...
132   std::vector<ReturnInst*> Returns;
133
134   // Do all of the hard part of cloning the callee into the caller...
135   CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
136
137   // Loop over all of the return instructions, turning them into unconditional
138   // branches to the merge point now...
139   for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
140     ReturnInst *RI = Returns[i];
141     BasicBlock *BB = RI->getParent();
142
143     // Add a branch to the merge point where the PHI node lives if it exists.
144     new BranchInst(AfterCallBB, RI);
145
146     if (PHI) {   // The PHI node should include this value!
147       assert(RI->getReturnValue() && "Ret should have value!");
148       assert(RI->getReturnValue()->getType() == PHI->getType() && 
149              "Ret value not consistent in function!");
150       PHI->addIncoming(RI->getReturnValue(), BB);
151     }
152
153     // Delete the return instruction now
154     BB->getInstList().erase(RI);
155   }
156
157   // Check to see if the PHI node only has one argument.  This is a common
158   // case resulting from there only being a single return instruction in the
159   // function call.  Because this is so common, eliminate the PHI node.
160   //
161   if (PHI && PHI->getNumIncomingValues() == 1) {
162     PHI->replaceAllUsesWith(PHI->getIncomingValue(0));
163     PHI->getParent()->getInstList().erase(PHI);
164   }
165
166   // Change the branch that used to go to AfterCallBB to branch to the first
167   // basic block of the inlined function.
168   //
169   TerminatorInst *Br = OrigBB->getTerminator();
170   assert(Br && Br->getOpcode() == Instruction::Br && 
171          "splitBasicBlock broken!");
172   Br->setOperand(0, ++LastBlock);
173
174   // If there are any alloca instructions in the block that used to be the entry
175   // block for the callee, move them to the entry block of the caller.  First
176   // calculate which instruction they should be inserted before.  We insert the
177   // instructions at the end of the current alloca list.
178   //
179   if (isa<AllocaInst>(LastBlock->begin())) {
180     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
181     while (isa<AllocaInst>(InsertPoint)) ++InsertPoint;
182     
183     for (BasicBlock::iterator I = LastBlock->begin(), E = LastBlock->end();
184          I != E; )
185       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
186         if (isa<Constant>(AI->getArraySize())) {
187           LastBlock->getInstList().remove(AI);
188           Caller->front().getInstList().insert(InsertPoint, AI);      
189         }
190   }
191
192   // If we just inlined a call due to an invoke instruction, scan the inlined
193   // function checking for function calls that should now be made into invoke
194   // instructions, and for unwind's which should be turned into branches.
195   if (InvokeDest) {
196     for (Function::iterator BB = LastBlock, E = Caller->end(); BB != E; ++BB) {
197       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
198         // We only need to check for function calls: inlined invoke instructions
199         // require no special handling...
200         if (CallInst *CI = dyn_cast<CallInst>(I)) {
201           // Convert this function call into an invoke instruction...
202
203           // First, split the basic block...
204           BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
205           
206           // Next, create the new invoke instruction, inserting it at the end
207           // of the old basic block.
208           InvokeInst *II =
209             new InvokeInst(CI->getCalledValue(), Split, InvokeDest, 
210                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
211                            CI->getName(), BB->getTerminator());
212
213           // Make sure that anything using the call now uses the invoke!
214           CI->replaceAllUsesWith(II);
215
216           // Delete the unconditional branch inserted by splitBasicBlock
217           BB->getInstList().pop_back();
218           Split->getInstList().pop_front();  // Delete the original call
219           
220           // Update any PHI nodes in the exceptional block to indicate that
221           // there is now a new entry in them.
222           unsigned i = 0;
223           for (BasicBlock::iterator I = InvokeDest->begin();
224                PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
225             PN->addIncoming(InvokeDestPHIValues[i], BB);
226
227           // This basic block is now complete, start scanning the next one.
228           break;
229         } else {
230           ++I;
231         }
232       }
233
234       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
235         // An UnwindInst requires special handling when it gets inlined into an
236         // invoke site.  Once this happens, we know that the unwind would cause
237         // a control transfer to the invoke exception destination, so we can
238         // transform it into a direct branch to the exception destination.
239         BranchInst *BI = new BranchInst(InvokeDest, UI);
240
241         // Delete the unwind instruction!
242         UI->getParent()->getInstList().pop_back();
243
244         // Update any PHI nodes in the exceptional block to indicate that
245         // there is now a new entry in them.
246         unsigned i = 0;
247         for (BasicBlock::iterator I = InvokeDest->begin();
248              PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
249           PN->addIncoming(InvokeDestPHIValues[i], BB);
250       }
251     }
252
253     // Now that everything is happy, we have one final detail.  The PHI nodes in
254     // the exception destination block still have entries due to the original
255     // invoke instruction.  Eliminate these entries (which might even delete the
256     // PHI node) now.
257     for (BasicBlock::iterator I = InvokeDest->begin();
258          PHINode *PN = dyn_cast<PHINode>(I); ++I)
259       PN->removeIncomingValue(AfterCallBB);
260   }
261   // Now that the function is correct, make it a little bit nicer.  In
262   // particular, move the basic blocks inserted from the end of the function
263   // into the space made by splitting the source basic block.
264   //
265   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(), 
266                                      LastBlock, Caller->end());
267
268   // We should always be able to fold the entry block of the function into the
269   // single predecessor of the block...
270   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
271   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
272   SimplifyCFG(CalleeEntry);
273   
274   // Okay, continue the CFG cleanup.  It's often the case that there is only a
275   // single return instruction in the callee function.  If this is the case,
276   // then we have an unconditional branch from the return block to the
277   // 'AfterCallBB'.  Check for this case, and eliminate the branch is possible.
278   SimplifyCFG(AfterCallBB);
279   return true;
280 }