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