blob: 37ba3ba6d49f40ab814979b572c0c94bc226ae60 [file] [log] [blame]
Chris Lattner530d4bf2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner530d4bf2003-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 Lattner530d4bf2003-05-29 15:11:31 +000013//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner6e79e552004-10-17 23:21:07 +000016#include "llvm/Constants.h"
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +000017#include "llvm/DerivedTypes.h"
Chris Lattner530d4bf2003-05-29 15:11:31 +000018#include "llvm/Module.h"
Chris Lattner0cc265e2003-08-24 06:59:16 +000019#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
Chris Lattner0841fb12006-01-14 20:07:50 +000021#include "llvm/Analysis/CallGraph.h"
Chris Lattner0cc265e2003-08-24 06:59:16 +000022#include "llvm/Support/CallSite.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000023using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000024
Chris Lattner0841fb12006-01-14 20:07:50 +000025bool llvm::InlineFunction(CallInst *CI, CallGraph *CG) {
26 return InlineFunction(CallSite(CI), CG);
27}
28bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG) {
29 return InlineFunction(CallSite(II), CG);
30}
Chris Lattner0cc265e2003-08-24 06:59:16 +000031
Chris Lattner908d7952006-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 Lattner19e6a082006-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 Lattner908d7952006-01-13 19:05:59 +000070
Chris Lattner19e6a082006-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 Lattner908d7952006-01-13 19:05:59 +0000108 }
Chris Lattner19e6a082006-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 Lattner908d7952006-01-13 19:05:59 +0000116
Chris Lattner19e6a082006-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 Lattner908d7952006-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 Lattner0841fb12006-01-14 20:07:50 +0000139/// UpdateCallGraphAfterInlining - Once we have finished inlining a call from
140/// caller to callee, update the specified callgraph to reflect the changes we
141/// made.
142static void UpdateCallGraphAfterInlining(const Function *Caller,
143 const Function *Callee,
144 CallGraph &CG) {
145 // Update the call graph by deleting the edge from Callee to Caller
146 CallGraphNode *CalleeNode = CG[Callee];
147 CallGraphNode *CallerNode = CG[Caller];
148 CallerNode->removeCallEdgeTo(CalleeNode);
149
150 // Since we inlined all uninlined call sites in the callee into the caller,
151 // add edges from the caller to all of the callees of the callee.
152 for (CallGraphNode::iterator I = CalleeNode->begin(),
153 E = CalleeNode->end(); I != E; ++I)
154 CallerNode->addCalledFunction(*I);
155}
156
Chris Lattner908d7952006-01-13 19:05:59 +0000157
Chris Lattner530d4bf2003-05-29 15:11:31 +0000158// InlineFunction - This function inlines the called function into the basic
159// block of the caller. This returns false if it is not possible to inline this
160// call. The program is still in a well defined state if this occurs though.
161//
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162// Note that this only does one level of inlining. For example, if the
163// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
Chris Lattner530d4bf2003-05-29 15:11:31 +0000164// exists in the instruction stream. Similiarly this will inline a recursive
165// function by one level.
166//
Chris Lattner0841fb12006-01-14 20:07:50 +0000167bool llvm::InlineFunction(CallSite CS, CallGraph *CG) {
Chris Lattner0cc265e2003-08-24 06:59:16 +0000168 Instruction *TheCall = CS.getInstruction();
169 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
170 "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +0000171
Chris Lattner0cc265e2003-08-24 06:59:16 +0000172 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattner530d4bf2003-05-29 15:11:31 +0000173 if (CalledFunc == 0 || // Can't inline external function or indirect
174 CalledFunc->isExternal() || // call, or call to a vararg function!
175 CalledFunc->getFunctionType()->isVarArg()) return false;
176
Chris Lattner9f3dced2005-05-06 06:47:52 +0000177
178 // If the call to the callee is a non-tail call, we must clear the 'tail'
179 // flags on any calls that we inline.
180 bool MustClearTailCallFlags =
Chris Lattner7effa0e2005-05-06 17:13:16 +0000181 isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
Chris Lattner9f3dced2005-05-06 06:47:52 +0000182
Chris Lattner0cc265e2003-08-24 06:59:16 +0000183 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +0000184 Function *Caller = OrigBB->getParent();
185
Chris Lattner9fc977e2004-02-04 01:41:09 +0000186 // Get an iterator to the last basic block in the function, which will have
187 // the new function inlined after it.
188 //
189 Function::iterator LastBlock = &Caller->back();
190
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000191 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +0000192 // function.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000193 std::vector<ReturnInst*> Returns;
Chris Lattner908d7952006-01-13 19:05:59 +0000194 ClonedCodeInfo InlinedFunctionInfo;
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000195 { // Scope to destroy ValueMap after cloning.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000196 std::map<const Value*, Value*> ValueMap;
Chris Lattnerbe853d72006-05-27 01:28:04 +0000197
198 // Calculate the vector of arguments to pass into the function cloner, which
199 // matches up the formal to the actual argument values.
Misha Brukmanb1c93172005-04-21 23:48:37 +0000200 assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000201 std::distance(CS.arg_begin(), CS.arg_end()) &&
202 "No varargs calls can be inlined!");
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000203 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattner531f9e92005-03-15 04:54:21 +0000204 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
205 E = CalledFunc->arg_end(); I != E; ++I, ++AI)
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000206 ValueMap[I] = *AI;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000207
Chris Lattnerbe853d72006-05-27 01:28:04 +0000208 // We want the inliner to prune the code as it copies. We would LOVE to
209 // have no dead or constant instructions leftover after inlining occurs
210 // (which can happen, e.g., because an argument was constant), but we'll be
211 // happy with whatever the cloner can do.
212 CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
213 &InlinedFunctionInfo);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000214 }
Chris Lattner6f8865b2004-02-04 21:33:42 +0000215
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000216 // Remember the first block that is newly cloned over.
217 Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
Chris Lattner530d4bf2003-05-29 15:11:31 +0000218
219 // If there are any alloca instructions in the block that used to be the entry
220 // block for the callee, move them to the entry block of the caller. First
221 // calculate which instruction they should be inserted before. We insert the
222 // instructions at the end of the current alloca list.
223 //
Chris Lattner257492c2006-01-13 18:16:48 +0000224 {
Chris Lattner0cc265e2003-08-24 06:59:16 +0000225 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000226 for (BasicBlock::iterator I = FirstNewBlock->begin(),
227 E = FirstNewBlock->end(); I != E; )
Chris Lattnerb4778c72003-10-14 01:11:07 +0000228 if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
229 if (isa<Constant>(AI->getArraySize())) {
Chris Lattner257492c2006-01-13 18:16:48 +0000230 // Scan for the block of allocas that we can move over, and move them
231 // all at once.
Chris Lattner6f8865b2004-02-04 21:33:42 +0000232 while (isa<AllocaInst>(I) &&
233 isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
234 ++I;
235
236 // Transfer all of the allocas over in a block. Using splice means
237 // that they instructions aren't removed from the symbol table, then
238 // reinserted.
239 Caller->front().getInstList().splice(InsertPoint,
240 FirstNewBlock->getInstList(),
241 AI, I);
Chris Lattnerb4778c72003-10-14 01:11:07 +0000242 }
Chris Lattner0cc265e2003-08-24 06:59:16 +0000243 }
Chris Lattner530d4bf2003-05-29 15:11:31 +0000244
Chris Lattner2be06072006-01-13 19:34:14 +0000245 // If the inlined code contained dynamic alloca instructions, wrap the inlined
246 // code with llvm.stacksave/llvm.stackrestore intrinsics.
247 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
248 Module *M = Caller->getParent();
249 const Type *SBytePtr = PointerType::get(Type::SByteTy);
250 // Get the two intrinsics we care about.
251 Function *StackSave, *StackRestore;
252 StackSave = M->getOrInsertFunction("llvm.stacksave", SBytePtr, NULL);
253 StackRestore = M->getOrInsertFunction("llvm.stackrestore", Type::VoidTy,
254 SBytePtr, NULL);
255
256 // Insert the llvm.stacksave.
257 Value *SavedPtr = new CallInst(StackSave, "savedstack",
258 FirstNewBlock->begin());
259
260 // Insert a call to llvm.stackrestore before any return instructions in the
261 // inlined function.
262 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
263 new CallInst(StackRestore, SavedPtr, "", Returns[i]);
Chris Lattner0841fb12006-01-14 20:07:50 +0000264
265 // Count the number of StackRestore calls we insert.
266 unsigned NumStackRestores = Returns.size();
Chris Lattner2be06072006-01-13 19:34:14 +0000267
268 // If we are inlining an invoke instruction, insert restores before each
269 // unwind. These unwinds will be rewritten into branches later.
270 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
271 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
272 BB != E; ++BB)
Chris Lattner0841fb12006-01-14 20:07:50 +0000273 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner2be06072006-01-13 19:34:14 +0000274 new CallInst(StackRestore, SavedPtr, "", UI);
Chris Lattner0841fb12006-01-14 20:07:50 +0000275 ++NumStackRestores;
276 }
277 }
278
279 // If we are supposed to update the callgraph, do so now.
280 if (CG) {
281 CallGraphNode *StackSaveCGN = CG->getOrInsertFunction(StackSave);
282 CallGraphNode *StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
283 CallGraphNode *CallerNode = (*CG)[Caller];
284
285 // 'Caller' now calls llvm.stacksave one more time.
286 CallerNode->addCalledFunction(StackSaveCGN);
287
288 // 'Caller' now calls llvm.stackrestore the appropriate number of times.
289 for (unsigned i = 0; i != NumStackRestores; ++i)
290 CallerNode->addCalledFunction(StackRestoreCGN);
Chris Lattner2be06072006-01-13 19:34:14 +0000291 }
292 }
293
Chris Lattnere24f79a2006-01-13 19:18:11 +0000294 // If we are inlining tail call instruction through a call site that isn't
295 // marked 'tail', we must remove the tail marker for any calls in the inlined
296 // code.
297 if (MustClearTailCallFlags && InlinedFunctionInfo.ContainsCalls) {
Chris Lattner9f3dced2005-05-06 06:47:52 +0000298 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
299 BB != E; ++BB)
300 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
301 if (CallInst *CI = dyn_cast<CallInst>(I))
302 CI->setTailCall(false);
303 }
304
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000305 // If we are inlining for an invoke instruction, we must make sure to rewrite
306 // any inlined 'unwind' instructions into branches to the invoke exception
307 // destination, and call instructions into invoke instructions.
Chris Lattner908d7952006-01-13 19:05:59 +0000308 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
309 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000310
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000311 // If we cloned in _exactly one_ basic block, and if that block ends in a
312 // return instruction, we splice the body of the inlined callee directly into
313 // the calling basic block.
314 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
315 // Move all of the instructions right before the call.
316 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
317 FirstNewBlock->begin(), FirstNewBlock->end());
318 // Remove the cloned basic block.
319 Caller->getBasicBlockList().pop_back();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000320
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000321 // If the call site was an invoke instruction, add a branch to the normal
322 // destination.
323 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
324 new BranchInst(II->getNormalDest(), TheCall);
325
326 // If the return instruction returned a value, replace uses of the call with
327 // uses of the returned value.
328 if (!TheCall->use_empty())
329 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
330
331 // Since we are now done with the Call/Invoke, we can delete it.
332 TheCall->getParent()->getInstList().erase(TheCall);
333
334 // Since we are now done with the return instruction, delete it also.
335 Returns[0]->getParent()->getInstList().erase(Returns[0]);
336
Chris Lattner0841fb12006-01-14 20:07:50 +0000337 // Update the callgraph if requested.
338 if (CG) UpdateCallGraphAfterInlining(Caller, CalledFunc, *CG);
339
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000340 // We are now done with the inlining.
341 return true;
342 }
343
344 // Otherwise, we have the normal case, of more than one block to inline or
345 // multiple return sites.
346
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000347 // We want to clone the entire callee function into the hole between the
348 // "starter" and "ender" blocks. How we accomplish this depends on whether
349 // this is an invoke instruction or a call instruction.
350 BasicBlock *AfterCallBB;
351 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000352
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000353 // Add an unconditional branch to make this look like the CallInst case...
354 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000355
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000356 // Split the basic block. This guarantees that no PHI nodes will have to be
357 // updated due to new incoming edges, and make the invoke case more
358 // symmetric to the call case.
359 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
Chris Lattnerffefea02004-12-11 16:59:54 +0000360 CalledFunc->getName()+".exit");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000361
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000362 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000363 // If this is a call instruction, we need to split the basic block that
364 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000365 //
366 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattnerffefea02004-12-11 16:59:54 +0000367 CalledFunc->getName()+".exit");
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000368 }
369
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000370 // Change the branch that used to go to AfterCallBB to branch to the first
371 // basic block of the inlined function.
372 //
373 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000374 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000375 "splitBasicBlock broken!");
376 Br->setOperand(0, FirstNewBlock);
377
378
379 // Now that the function is correct, make it a little bit nicer. In
380 // particular, move the basic blocks inserted from the end of the function
381 // into the space made by splitting the source basic block.
382 //
383 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
384 FirstNewBlock, Caller->end());
385
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000386 // Handle all of the return instructions that we just cloned in, and eliminate
387 // any users of the original call/invoke instruction.
388 if (Returns.size() > 1) {
389 // The PHI node should go at the front of the new basic block to merge all
390 // possible incoming values.
391 //
392 PHINode *PHI = 0;
393 if (!TheCall->use_empty()) {
394 PHI = new PHINode(CalledFunc->getReturnType(),
395 TheCall->getName(), AfterCallBB->begin());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000396
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000397 // Anything that used the result of the function call should now use the
398 // PHI node as their operand.
399 //
400 TheCall->replaceAllUsesWith(PHI);
401 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000402
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000403 // Loop over all of the return instructions, turning them into unconditional
404 // branches to the merge point now, and adding entries to the PHI node as
405 // appropriate.
406 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
407 ReturnInst *RI = Returns[i];
Misha Brukmanb1c93172005-04-21 23:48:37 +0000408
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000409 if (PHI) {
410 assert(RI->getReturnValue() && "Ret should have value!");
Misha Brukmanb1c93172005-04-21 23:48:37 +0000411 assert(RI->getReturnValue()->getType() == PHI->getType() &&
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000412 "Ret value not consistent in function!");
413 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
414 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000415
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000416 // Add a branch to the merge point where the PHI node lives if it exists.
417 new BranchInst(AfterCallBB, RI);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000418
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000419 // Delete the return instruction now
420 RI->getParent()->getInstList().erase(RI);
421 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000422
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000423 } else if (!Returns.empty()) {
424 // Otherwise, if there is exactly one return value, just replace anything
425 // using the return value of the call with the computed value.
426 if (!TheCall->use_empty())
427 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000428
Chris Lattner0328d752004-04-16 05:17:59 +0000429 // Splice the code from the return block into the block that it will return
430 // to, which contains the code that was after the call.
431 BasicBlock *ReturnBB = Returns[0]->getParent();
Chris Lattner45b50d12004-07-20 05:45:24 +0000432 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
433 ReturnBB->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +0000434
Chris Lattner45b50d12004-07-20 05:45:24 +0000435 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
436 ReturnBB->replaceAllUsesWith(AfterCallBB);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000437
Chris Lattner45b50d12004-07-20 05:45:24 +0000438 // Delete the return instruction now and empty ReturnBB now.
Chris Lattner6e79e552004-10-17 23:21:07 +0000439 Returns[0]->eraseFromParent();
440 ReturnBB->eraseFromParent();
441 } else if (!TheCall->use_empty()) {
442 // No returns, but something is using the return value of the call. Just
443 // nuke the result.
444 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000445 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000446
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000447 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner6e79e552004-10-17 23:21:07 +0000448 TheCall->eraseFromParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +0000449
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +0000450 // We should always be able to fold the entry block of the function into the
451 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +0000452 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +0000453 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000454
Chris Lattner0328d752004-04-16 05:17:59 +0000455 // Splice the code entry block into calling block, right before the
456 // unconditional branch.
457 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
458 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
459
460 // Remove the unconditional branch.
461 OrigBB->getInstList().erase(Br);
462
463 // Now we can remove the CalleeEntry block, which is now empty.
464 Caller->getBasicBlockList().erase(CalleeEntry);
Chris Lattner0841fb12006-01-14 20:07:50 +0000465
466 // Update the callgraph if requested.
467 if (CG) UpdateCallGraphAfterInlining(Caller, CalledFunc, *CG);
468
Chris Lattner530d4bf2003-05-29 15:11:31 +0000469 return true;
470}