blob: 911bfe0a39a6640ebd2e16d3329ee6d85f1b906b [file] [log] [blame]
Chris Lattnerca398dc2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca398dc2003-05-29 15:11:31 +00009//
10// This file implements inlining of a function into a call site, resolving
11// parameters and the return value as appropriate.
12//
Chris Lattnerca398dc2003-05-29 15:11:31 +000013//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner3787e762004-10-17 23:21:07 +000016#include "llvm/Constants.h"
Chris Lattner7152c232003-08-24 04:06:56 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerca398dc2003-05-29 15:11:31 +000018#include "llvm/Module.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000019#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
Chris Lattner468fb1d2006-01-14 20:07:50 +000021#include "llvm/Analysis/CallGraph.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000022#include "llvm/Support/CallSite.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000023using namespace llvm;
Chris Lattnerca398dc2003-05-29 15:11:31 +000024
Chris Lattner1dfdf822007-01-30 23:22:39 +000025bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD) {
26 return InlineFunction(CallSite(CI), CG, TD);
Chris Lattner468fb1d2006-01-14 20:07:50 +000027}
Chris Lattner1dfdf822007-01-30 23:22:39 +000028bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD) {
29 return InlineFunction(CallSite(II), CG, TD);
Chris Lattner468fb1d2006-01-14 20:07:50 +000030}
Chris Lattner80a38d22003-08-24 06:59:16 +000031
Chris Lattnercd4d3392006-01-13 19:05:59 +000032/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
33/// in the body of the inlined function into invokes and turn unwind
34/// instructions into branches to the invoke unwind dest.
35///
36/// II is the invoke instruction begin inlined. FirstNewBlock is the first
37/// block of the inlined code (the last block is the end of the function),
38/// and InlineCodeInfo is information about the code that got inlined.
39static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
40 ClonedCodeInfo &InlinedCodeInfo) {
41 BasicBlock *InvokeDest = II->getUnwindDest();
42 std::vector<Value*> InvokeDestPHIValues;
43
44 // If there are PHI nodes in the unwind destination block, we need to
45 // keep track of which values came into them from this invoke, then remove
46 // the entry for this block.
47 BasicBlock *InvokeBlock = II->getParent();
48 for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
49 PHINode *PN = cast<PHINode>(I);
50 // Save the value to use for this edge.
51 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
52 }
53
54 Function *Caller = FirstNewBlock->getParent();
55
56 // The inlined code is currently at the end of the function, scan from the
57 // start of the inlined code to its end, checking for stuff we need to
58 // rewrite.
Chris Lattner727d1dd2006-01-13 19:15:15 +000059 if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
60 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
61 BB != E; ++BB) {
62 if (InlinedCodeInfo.ContainsCalls) {
63 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
64 Instruction *I = BBI++;
65
66 // We only need to check for function calls: inlined invoke
67 // instructions require no special handling.
68 if (!isa<CallInst>(I)) continue;
69 CallInst *CI = cast<CallInst>(I);
Chris Lattnercd4d3392006-01-13 19:05:59 +000070
Chris Lattner727d1dd2006-01-13 19:15:15 +000071 // If this is an intrinsic function call, don't convert it to an
72 // invoke.
73 if (CI->getCalledFunction() &&
74 CI->getCalledFunction()->getIntrinsicID())
75 continue;
76
77 // Convert this function call into an invoke instruction.
78 // First, split the basic block.
79 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
80
81 // Next, create the new invoke instruction, inserting it at the end
82 // of the old basic block.
83 InvokeInst *II =
84 new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
85 std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
86 CI->getName(), BB->getTerminator());
87 II->setCallingConv(CI->getCallingConv());
88
89 // Make sure that anything using the call now uses the invoke!
90 CI->replaceAllUsesWith(II);
91
92 // Delete the unconditional branch inserted by splitBasicBlock
93 BB->getInstList().pop_back();
94 Split->getInstList().pop_front(); // Delete the original call
95
96 // Update any PHI nodes in the exceptional block to indicate that
97 // there is now a new entry in them.
98 unsigned i = 0;
99 for (BasicBlock::iterator I = InvokeDest->begin();
100 isa<PHINode>(I); ++I, ++i) {
101 PHINode *PN = cast<PHINode>(I);
102 PN->addIncoming(InvokeDestPHIValues[i], BB);
103 }
104
105 // This basic block is now complete, start scanning the next one.
106 break;
107 }
Chris Lattnercd4d3392006-01-13 19:05:59 +0000108 }
Chris Lattner727d1dd2006-01-13 19:15:15 +0000109
110 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
111 // An UnwindInst requires special handling when it gets inlined into an
112 // invoke site. Once this happens, we know that the unwind would cause
113 // a control transfer to the invoke exception destination, so we can
114 // transform it into a direct branch to the exception destination.
115 new BranchInst(InvokeDest, UI);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000116
Chris Lattner727d1dd2006-01-13 19:15:15 +0000117 // Delete the unwind instruction!
118 UI->getParent()->getInstList().pop_back();
119
120 // Update any PHI nodes in the exceptional block to indicate that
121 // there is now a new entry in them.
122 unsigned i = 0;
123 for (BasicBlock::iterator I = InvokeDest->begin();
124 isa<PHINode>(I); ++I, ++i) {
125 PHINode *PN = cast<PHINode>(I);
126 PN->addIncoming(InvokeDestPHIValues[i], BB);
127 }
Chris Lattnercd4d3392006-01-13 19:05:59 +0000128 }
129 }
130 }
131
132 // Now that everything is happy, we have one final detail. The PHI nodes in
133 // the exception destination block still have entries due to the original
134 // invoke instruction. Eliminate these entries (which might even delete the
135 // PHI node) now.
136 InvokeDest->removePredecessor(II->getParent());
137}
138
Chris Lattnerd85340f2006-07-12 18:29:36 +0000139/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
140/// into the caller, update the specified callgraph to reflect the changes we
141/// made. Note that it's possible that not all code was copied over, so only
142/// some edges of the callgraph will be remain.
143static void UpdateCallGraphAfterInlining(const Function *Caller,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000144 const Function *Callee,
Chris Lattnerd85340f2006-07-12 18:29:36 +0000145 Function::iterator FirstNewBlock,
146 std::map<const Value*, Value*> &ValueMap,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000147 CallGraph &CG) {
148 // Update the call graph by deleting the edge from Callee to Caller
149 CallGraphNode *CalleeNode = CG[Callee];
150 CallGraphNode *CallerNode = CG[Caller];
151 CallerNode->removeCallEdgeTo(CalleeNode);
152
Chris Lattnerd85340f2006-07-12 18:29:36 +0000153 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000154 // add edges from the caller to all of the callees of the callee.
155 for (CallGraphNode::iterator I = CalleeNode->begin(),
Chris Lattnerd85340f2006-07-12 18:29:36 +0000156 E = CalleeNode->end(); I != E; ++I) {
157 const Instruction *OrigCall = I->first.getInstruction();
158
159 std::map<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
Chris Lattner981418b2006-07-12 21:37:11 +0000160 // Only copy the edge if the call was inlined!
161 if (VMI != ValueMap.end() && VMI->second) {
Chris Lattner1bb3a402006-07-12 18:37:18 +0000162 // If the call was inlined, but then constant folded, there is no edge to
163 // add. Check for this case.
164 if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
165 CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000166 }
167 }
Chris Lattner468fb1d2006-01-14 20:07:50 +0000168}
169
Chris Lattnercd4d3392006-01-13 19:05:59 +0000170
Chris Lattnerca398dc2003-05-29 15:11:31 +0000171// InlineFunction - This function inlines the called function into the basic
172// block of the caller. This returns false if it is not possible to inline this
173// call. The program is still in a well defined state if this occurs though.
174//
Misha Brukmanfd939082005-04-21 23:48:37 +0000175// Note that this only does one level of inlining. For example, if the
176// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
Chris Lattnerca398dc2003-05-29 15:11:31 +0000177// exists in the instruction stream. Similiarly this will inline a recursive
178// function by one level.
179//
Chris Lattner1dfdf822007-01-30 23:22:39 +0000180bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000181 Instruction *TheCall = CS.getInstruction();
182 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
183 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +0000184
Chris Lattner80a38d22003-08-24 06:59:16 +0000185 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000186 if (CalledFunc == 0 || // Can't inline external function or indirect
Reid Spencer5cbf9852007-01-30 20:08:39 +0000187 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Chris Lattnerca398dc2003-05-29 15:11:31 +0000188 CalledFunc->getFunctionType()->isVarArg()) return false;
189
Chris Lattner1b491412005-05-06 06:47:52 +0000190
191 // If the call to the callee is a non-tail call, we must clear the 'tail'
192 // flags on any calls that we inline.
193 bool MustClearTailCallFlags =
Chris Lattner3799ed82005-05-06 17:13:16 +0000194 isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
Chris Lattner1b491412005-05-06 06:47:52 +0000195
Chris Lattner80a38d22003-08-24 06:59:16 +0000196 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000197 Function *Caller = OrigBB->getParent();
198
Chris Lattner5052c912004-02-04 01:41:09 +0000199 // Get an iterator to the last basic block in the function, which will have
200 // the new function inlined after it.
201 //
202 Function::iterator LastBlock = &Caller->back();
203
Chris Lattner5e923de2004-02-04 02:51:48 +0000204 // Make sure to capture all of the return instructions from the cloned
Chris Lattnerca398dc2003-05-29 15:11:31 +0000205 // function.
Chris Lattner5e923de2004-02-04 02:51:48 +0000206 std::vector<ReturnInst*> Returns;
Chris Lattnercd4d3392006-01-13 19:05:59 +0000207 ClonedCodeInfo InlinedFunctionInfo;
Chris Lattnerd85340f2006-07-12 18:29:36 +0000208 Function::iterator FirstNewBlock;
209
Chris Lattner5e923de2004-02-04 02:51:48 +0000210 { // Scope to destroy ValueMap after cloning.
Chris Lattner5e923de2004-02-04 02:51:48 +0000211 std::map<const Value*, Value*> ValueMap;
Chris Lattner5b5bc302006-05-27 01:28:04 +0000212
213 // Calculate the vector of arguments to pass into the function cloner, which
214 // matches up the formal to the actual argument values.
Misha Brukmanfd939082005-04-21 23:48:37 +0000215 assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
Chris Lattner5e923de2004-02-04 02:51:48 +0000216 std::distance(CS.arg_begin(), CS.arg_end()) &&
217 "No varargs calls can be inlined!");
Chris Lattner5e923de2004-02-04 02:51:48 +0000218 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000219 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
220 E = CalledFunc->arg_end(); I != E; ++I, ++AI)
Chris Lattner5e923de2004-02-04 02:51:48 +0000221 ValueMap[I] = *AI;
Misha Brukmanfd939082005-04-21 23:48:37 +0000222
Chris Lattner5b5bc302006-05-27 01:28:04 +0000223 // We want the inliner to prune the code as it copies. We would LOVE to
224 // have no dead or constant instructions leftover after inlining occurs
225 // (which can happen, e.g., because an argument was constant), but we'll be
226 // happy with whatever the cloner can do.
227 CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
Chris Lattner1dfdf822007-01-30 23:22:39 +0000228 &InlinedFunctionInfo, TD);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000229
230 // Remember the first block that is newly cloned over.
231 FirstNewBlock = LastBlock; ++FirstNewBlock;
232
233 // Update the callgraph if requested.
234 if (CG)
235 UpdateCallGraphAfterInlining(Caller, CalledFunc, FirstNewBlock, ValueMap,
236 *CG);
Misha Brukmanfd939082005-04-21 23:48:37 +0000237 }
Chris Lattnerd85340f2006-07-12 18:29:36 +0000238
Chris Lattnerca398dc2003-05-29 15:11:31 +0000239 // If there are any alloca instructions in the block that used to be the entry
240 // block for the callee, move them to the entry block of the caller. First
241 // calculate which instruction they should be inserted before. We insert the
242 // instructions at the end of the current alloca list.
243 //
Chris Lattner21f20552006-01-13 18:16:48 +0000244 {
Chris Lattner80a38d22003-08-24 06:59:16 +0000245 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner5e923de2004-02-04 02:51:48 +0000246 for (BasicBlock::iterator I = FirstNewBlock->begin(),
247 E = FirstNewBlock->end(); I != E; )
Chris Lattner33bb3c82006-09-13 19:23:57 +0000248 if (AllocaInst *AI = dyn_cast<AllocaInst>(I++)) {
249 // If the alloca is now dead, remove it. This often occurs due to code
250 // specialization.
251 if (AI->use_empty()) {
252 AI->eraseFromParent();
253 continue;
254 }
255
Chris Lattnerf775f952003-10-14 01:11:07 +0000256 if (isa<Constant>(AI->getArraySize())) {
Chris Lattner21f20552006-01-13 18:16:48 +0000257 // Scan for the block of allocas that we can move over, and move them
258 // all at once.
Chris Lattnerc1df7e12004-02-04 21:33:42 +0000259 while (isa<AllocaInst>(I) &&
260 isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
261 ++I;
262
263 // Transfer all of the allocas over in a block. Using splice means
264 // that they instructions aren't removed from the symbol table, then
265 // reinserted.
266 Caller->front().getInstList().splice(InsertPoint,
267 FirstNewBlock->getInstList(),
268 AI, I);
Chris Lattnerf775f952003-10-14 01:11:07 +0000269 }
Chris Lattner33bb3c82006-09-13 19:23:57 +0000270 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000271 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000272
Chris Lattnerbf229f42006-01-13 19:34:14 +0000273 // If the inlined code contained dynamic alloca instructions, wrap the inlined
274 // code with llvm.stacksave/llvm.stackrestore intrinsics.
275 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
276 Module *M = Caller->getParent();
Chris Lattnera121fdd2007-01-07 07:54:34 +0000277 const Type *BytePtr = PointerType::get(Type::Int8Ty);
Chris Lattnerbf229f42006-01-13 19:34:14 +0000278 // Get the two intrinsics we care about.
Chris Lattnera121fdd2007-01-07 07:54:34 +0000279 Constant *StackSave, *StackRestore;
280 StackSave = M->getOrInsertFunction("llvm.stacksave", BytePtr, NULL);
Chris Lattnerbf229f42006-01-13 19:34:14 +0000281 StackRestore = M->getOrInsertFunction("llvm.stackrestore", Type::VoidTy,
Chris Lattnera121fdd2007-01-07 07:54:34 +0000282 BytePtr, NULL);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000283
284 // If we are preserving the callgraph, add edges to the stacksave/restore
285 // functions for the calls we insert.
Chris Lattner21ba23d2006-07-18 21:48:57 +0000286 CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
Chris Lattnerd85340f2006-07-12 18:29:36 +0000287 if (CG) {
Chris Lattnera121fdd2007-01-07 07:54:34 +0000288 // We know that StackSave/StackRestore are Function*'s, because they are
289 // intrinsics which must have the right types.
290 StackSaveCGN = CG->getOrInsertFunction(cast<Function>(StackSave));
291 StackRestoreCGN = CG->getOrInsertFunction(cast<Function>(StackRestore));
Chris Lattnerd85340f2006-07-12 18:29:36 +0000292 CallerNode = (*CG)[Caller];
293 }
294
Chris Lattnerbf229f42006-01-13 19:34:14 +0000295 // Insert the llvm.stacksave.
Chris Lattnerd85340f2006-07-12 18:29:36 +0000296 CallInst *SavedPtr = new CallInst(StackSave, "savedstack",
297 FirstNewBlock->begin());
298 if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
299
Chris Lattnerbf229f42006-01-13 19:34:14 +0000300 // Insert a call to llvm.stackrestore before any return instructions in the
301 // inlined function.
Chris Lattnerd85340f2006-07-12 18:29:36 +0000302 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
303 CallInst *CI = new CallInst(StackRestore, SavedPtr, "", Returns[i]);
304 if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
305 }
Chris Lattner468fb1d2006-01-14 20:07:50 +0000306
307 // Count the number of StackRestore calls we insert.
308 unsigned NumStackRestores = Returns.size();
Chris Lattnerbf229f42006-01-13 19:34:14 +0000309
310 // If we are inlining an invoke instruction, insert restores before each
311 // unwind. These unwinds will be rewritten into branches later.
312 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
313 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
314 BB != E; ++BB)
Chris Lattner468fb1d2006-01-14 20:07:50 +0000315 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattnerbf229f42006-01-13 19:34:14 +0000316 new CallInst(StackRestore, SavedPtr, "", UI);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000317 ++NumStackRestores;
318 }
319 }
Chris Lattnerbf229f42006-01-13 19:34:14 +0000320 }
321
Chris Lattner1fdf4a82006-01-13 19:18:11 +0000322 // If we are inlining tail call instruction through a call site that isn't
323 // marked 'tail', we must remove the tail marker for any calls in the inlined
324 // code.
325 if (MustClearTailCallFlags && InlinedFunctionInfo.ContainsCalls) {
Chris Lattner1b491412005-05-06 06:47:52 +0000326 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
327 BB != E; ++BB)
328 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
329 if (CallInst *CI = dyn_cast<CallInst>(I))
330 CI->setTailCall(false);
331 }
332
Chris Lattner5e923de2004-02-04 02:51:48 +0000333 // If we are inlining for an invoke instruction, we must make sure to rewrite
334 // any inlined 'unwind' instructions into branches to the invoke exception
335 // destination, and call instructions into invoke instructions.
Chris Lattnercd4d3392006-01-13 19:05:59 +0000336 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
337 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner5e923de2004-02-04 02:51:48 +0000338
Chris Lattner44a68072004-02-04 04:17:06 +0000339 // If we cloned in _exactly one_ basic block, and if that block ends in a
340 // return instruction, we splice the body of the inlined callee directly into
341 // the calling basic block.
342 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
343 // Move all of the instructions right before the call.
344 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
345 FirstNewBlock->begin(), FirstNewBlock->end());
346 // Remove the cloned basic block.
347 Caller->getBasicBlockList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000348
Chris Lattner44a68072004-02-04 04:17:06 +0000349 // If the call site was an invoke instruction, add a branch to the normal
350 // destination.
351 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
352 new BranchInst(II->getNormalDest(), TheCall);
353
354 // If the return instruction returned a value, replace uses of the call with
355 // uses of the returned value.
356 if (!TheCall->use_empty())
357 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
358
359 // Since we are now done with the Call/Invoke, we can delete it.
360 TheCall->getParent()->getInstList().erase(TheCall);
361
362 // Since we are now done with the return instruction, delete it also.
363 Returns[0]->getParent()->getInstList().erase(Returns[0]);
364
365 // We are now done with the inlining.
366 return true;
367 }
368
369 // Otherwise, we have the normal case, of more than one block to inline or
370 // multiple return sites.
371
Chris Lattner5e923de2004-02-04 02:51:48 +0000372 // We want to clone the entire callee function into the hole between the
373 // "starter" and "ender" blocks. How we accomplish this depends on whether
374 // this is an invoke instruction or a call instruction.
375 BasicBlock *AfterCallBB;
376 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000377
Chris Lattner5e923de2004-02-04 02:51:48 +0000378 // Add an unconditional branch to make this look like the CallInst case...
379 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000380
Chris Lattner5e923de2004-02-04 02:51:48 +0000381 // Split the basic block. This guarantees that no PHI nodes will have to be
382 // updated due to new incoming edges, and make the invoke case more
383 // symmetric to the call case.
384 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
Chris Lattner284d1b82004-12-11 16:59:54 +0000385 CalledFunc->getName()+".exit");
Misha Brukmanfd939082005-04-21 23:48:37 +0000386
Chris Lattner5e923de2004-02-04 02:51:48 +0000387 } else { // It's a call
Chris Lattner44a68072004-02-04 04:17:06 +0000388 // If this is a call instruction, we need to split the basic block that
389 // the call lives in.
Chris Lattner5e923de2004-02-04 02:51:48 +0000390 //
391 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattner284d1b82004-12-11 16:59:54 +0000392 CalledFunc->getName()+".exit");
Chris Lattner5e923de2004-02-04 02:51:48 +0000393 }
394
Chris Lattner44a68072004-02-04 04:17:06 +0000395 // Change the branch that used to go to AfterCallBB to branch to the first
396 // basic block of the inlined function.
397 //
398 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000399 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner44a68072004-02-04 04:17:06 +0000400 "splitBasicBlock broken!");
401 Br->setOperand(0, FirstNewBlock);
402
403
404 // Now that the function is correct, make it a little bit nicer. In
405 // particular, move the basic blocks inserted from the end of the function
406 // into the space made by splitting the source basic block.
407 //
408 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
409 FirstNewBlock, Caller->end());
410
Chris Lattner5e923de2004-02-04 02:51:48 +0000411 // Handle all of the return instructions that we just cloned in, and eliminate
412 // any users of the original call/invoke instruction.
413 if (Returns.size() > 1) {
414 // The PHI node should go at the front of the new basic block to merge all
415 // possible incoming values.
416 //
417 PHINode *PHI = 0;
418 if (!TheCall->use_empty()) {
419 PHI = new PHINode(CalledFunc->getReturnType(),
420 TheCall->getName(), AfterCallBB->begin());
Misha Brukmanfd939082005-04-21 23:48:37 +0000421
Chris Lattner5e923de2004-02-04 02:51:48 +0000422 // Anything that used the result of the function call should now use the
423 // PHI node as their operand.
424 //
425 TheCall->replaceAllUsesWith(PHI);
426 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000427
Chris Lattner5e923de2004-02-04 02:51:48 +0000428 // Loop over all of the return instructions, turning them into unconditional
429 // branches to the merge point now, and adding entries to the PHI node as
430 // appropriate.
431 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
432 ReturnInst *RI = Returns[i];
Misha Brukmanfd939082005-04-21 23:48:37 +0000433
Chris Lattner5e923de2004-02-04 02:51:48 +0000434 if (PHI) {
435 assert(RI->getReturnValue() && "Ret should have value!");
Misha Brukmanfd939082005-04-21 23:48:37 +0000436 assert(RI->getReturnValue()->getType() == PHI->getType() &&
Chris Lattner5e923de2004-02-04 02:51:48 +0000437 "Ret value not consistent in function!");
438 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
439 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000440
Chris Lattner5e923de2004-02-04 02:51:48 +0000441 // Add a branch to the merge point where the PHI node lives if it exists.
442 new BranchInst(AfterCallBB, RI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000443
Chris Lattner5e923de2004-02-04 02:51:48 +0000444 // Delete the return instruction now
445 RI->getParent()->getInstList().erase(RI);
446 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000447
Chris Lattner5e923de2004-02-04 02:51:48 +0000448 } else if (!Returns.empty()) {
449 // Otherwise, if there is exactly one return value, just replace anything
450 // using the return value of the call with the computed value.
451 if (!TheCall->use_empty())
452 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
Misha Brukmanfd939082005-04-21 23:48:37 +0000453
Chris Lattnercd01ae52004-04-16 05:17:59 +0000454 // Splice the code from the return block into the block that it will return
455 // to, which contains the code that was after the call.
456 BasicBlock *ReturnBB = Returns[0]->getParent();
Chris Lattneradfd32f2004-07-20 05:45:24 +0000457 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
458 ReturnBB->getInstList());
Chris Lattnercd01ae52004-04-16 05:17:59 +0000459
Chris Lattneradfd32f2004-07-20 05:45:24 +0000460 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
461 ReturnBB->replaceAllUsesWith(AfterCallBB);
Misha Brukmanfd939082005-04-21 23:48:37 +0000462
Chris Lattneradfd32f2004-07-20 05:45:24 +0000463 // Delete the return instruction now and empty ReturnBB now.
Chris Lattner3787e762004-10-17 23:21:07 +0000464 Returns[0]->eraseFromParent();
465 ReturnBB->eraseFromParent();
466 } else if (!TheCall->use_empty()) {
467 // No returns, but something is using the return value of the call. Just
468 // nuke the result.
469 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner5e923de2004-02-04 02:51:48 +0000470 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000471
Chris Lattner5e923de2004-02-04 02:51:48 +0000472 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner3787e762004-10-17 23:21:07 +0000473 TheCall->eraseFromParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000474
Chris Lattner7152c232003-08-24 04:06:56 +0000475 // We should always be able to fold the entry block of the function into the
476 // single predecessor of the block...
Chris Lattnercd01ae52004-04-16 05:17:59 +0000477 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattner7152c232003-08-24 04:06:56 +0000478 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner44a68072004-02-04 04:17:06 +0000479
Chris Lattnercd01ae52004-04-16 05:17:59 +0000480 // Splice the code entry block into calling block, right before the
481 // unconditional branch.
482 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
483 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
484
485 // Remove the unconditional branch.
486 OrigBB->getInstList().erase(Br);
487
488 // Now we can remove the CalleeEntry block, which is now empty.
489 Caller->getBasicBlockList().erase(CalleeEntry);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000490
Chris Lattnerca398dc2003-05-29 15:11:31 +0000491 return true;
492}