back out r101423 and r101397, they break llvm-gcc self-host on darwin10
[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 is distributed under the University of Illinois Open Source
6 // 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 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Attributes.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/Analysis/DebugInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Support/CallSite.h"
30 using namespace llvm;
31
32 bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD,
33                           SmallVectorImpl<AllocaInst*> *StaticAllocas) {
34   return InlineFunction(CallSite(CI), CG, TD, StaticAllocas);
35 }
36 bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD,
37                           SmallVectorImpl<AllocaInst*> *StaticAllocas) {
38   return InlineFunction(CallSite(II), CG, TD, StaticAllocas);
39 }
40
41
42 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
43 /// an invoke, we have to turn all of the calls that can throw into
44 /// invokes.  This function analyze BB to see if there are any calls, and if so,
45 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
46 /// nodes in that block with the values specified in InvokeDestPHIValues.
47 ///
48 static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
49                                                    BasicBlock *InvokeDest,
50                            const SmallVectorImpl<Value*> &InvokeDestPHIValues) {
51   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
52     Instruction *I = BBI++;
53     
54     // We only need to check for function calls: inlined invoke
55     // instructions require no special handling.
56     CallInst *CI = dyn_cast<CallInst>(I);
57     if (CI == 0) continue;
58     
59     // If this call cannot unwind, don't convert it to an invoke.
60     if (CI->doesNotThrow())
61       continue;
62     
63     // Convert this function call into an invoke instruction.
64     // First, split the basic block.
65     BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
66     
67     // Next, create the new invoke instruction, inserting it at the end
68     // of the old basic block.
69     SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
70     InvokeInst *II =
71       InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
72                          InvokeArgs.begin(), InvokeArgs.end(),
73                          CI->getName(), BB->getTerminator());
74     II->setCallingConv(CI->getCallingConv());
75     II->setAttributes(CI->getAttributes());
76     
77     // Make sure that anything using the call now uses the invoke!  This also
78     // updates the CallGraph if present.
79     CI->replaceAllUsesWith(II);
80     
81     // Delete the unconditional branch inserted by splitBasicBlock
82     BB->getInstList().pop_back();
83     Split->getInstList().pop_front();  // Delete the original call
84     
85     // Update any PHI nodes in the exceptional block to indicate that
86     // there is now a new entry in them.
87     unsigned i = 0;
88     for (BasicBlock::iterator I = InvokeDest->begin();
89          isa<PHINode>(I); ++I, ++i)
90       cast<PHINode>(I)->addIncoming(InvokeDestPHIValues[i], BB);
91     
92     // This basic block is now complete, the caller will continue scanning the
93     // next one.
94     return;
95   }
96 }
97   
98
99 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
100 /// in the body of the inlined function into invokes and turn unwind
101 /// instructions into branches to the invoke unwind dest.
102 ///
103 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
104 /// block of the inlined code (the last block is the end of the function),
105 /// and InlineCodeInfo is information about the code that got inlined.
106 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
107                                 ClonedCodeInfo &InlinedCodeInfo) {
108   BasicBlock *InvokeDest = II->getUnwindDest();
109   SmallVector<Value*, 8> InvokeDestPHIValues;
110
111   // If there are PHI nodes in the unwind destination block, we need to
112   // keep track of which values came into them from this invoke, then remove
113   // the entry for this block.
114   BasicBlock *InvokeBlock = II->getParent();
115   for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
116     PHINode *PN = cast<PHINode>(I);
117     // Save the value to use for this edge.
118     InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
119   }
120
121   Function *Caller = FirstNewBlock->getParent();
122
123   // The inlined code is currently at the end of the function, scan from the
124   // start of the inlined code to its end, checking for stuff we need to
125   // rewrite.  If the code doesn't have calls or unwinds, we know there is
126   // nothing to rewrite.
127   if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
128     // Now that everything is happy, we have one final detail.  The PHI nodes in
129     // the exception destination block still have entries due to the original
130     // invoke instruction.  Eliminate these entries (which might even delete the
131     // PHI node) now.
132     InvokeDest->removePredecessor(II->getParent());
133     return;
134   }
135   
136   for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
137     if (InlinedCodeInfo.ContainsCalls)
138       HandleCallsInBlockInlinedThroughInvoke(BB, InvokeDest,
139                                              InvokeDestPHIValues);
140
141     if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
142       // An UnwindInst requires special handling when it gets inlined into an
143       // invoke site.  Once this happens, we know that the unwind would cause
144       // a control transfer to the invoke exception destination, so we can
145       // transform it into a direct branch to the exception destination.
146       BranchInst::Create(InvokeDest, UI);
147
148       // Delete the unwind instruction!
149       UI->eraseFromParent();
150
151       // Update any PHI nodes in the exceptional block to indicate that
152       // there is now a new entry in them.
153       unsigned i = 0;
154       for (BasicBlock::iterator I = InvokeDest->begin();
155            isa<PHINode>(I); ++I, ++i) {
156         PHINode *PN = cast<PHINode>(I);
157         PN->addIncoming(InvokeDestPHIValues[i], BB);
158       }
159     }
160   }
161
162   // Now that everything is happy, we have one final detail.  The PHI nodes in
163   // the exception destination block still have entries due to the original
164   // invoke instruction.  Eliminate these entries (which might even delete the
165   // PHI node) now.
166   InvokeDest->removePredecessor(II->getParent());
167 }
168
169 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
170 /// into the caller, update the specified callgraph to reflect the changes we
171 /// made.  Note that it's possible that not all code was copied over, so only
172 /// some edges of the callgraph may remain.
173 static void UpdateCallGraphAfterInlining(CallSite CS,
174                                          Function::iterator FirstNewBlock,
175                                        DenseMap<const Value*, Value*> &ValueMap,
176                                          CallGraph &CG) {
177   const Function *Caller = CS.getInstruction()->getParent()->getParent();
178   const Function *Callee = CS.getCalledFunction();
179   CallGraphNode *CalleeNode = CG[Callee];
180   CallGraphNode *CallerNode = CG[Caller];
181
182   // Since we inlined some uninlined call sites in the callee into the caller,
183   // add edges from the caller to all of the callees of the callee.
184   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
185
186   // Consider the case where CalleeNode == CallerNode.
187   CallGraphNode::CalledFunctionsVector CallCache;
188   if (CalleeNode == CallerNode) {
189     CallCache.assign(I, E);
190     I = CallCache.begin();
191     E = CallCache.end();
192   }
193
194   for (; I != E; ++I) {
195     const Value *OrigCall = I->first;
196
197     DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
198     // Only copy the edge if the call was inlined!
199     if (VMI == ValueMap.end() || VMI->second == 0)
200       continue;
201     
202     // If the call was inlined, but then constant folded, there is no edge to
203     // add.  Check for this case.
204     if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
205       CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
206   }
207   
208   // Update the call graph by deleting the edge from Callee to Caller.  We must
209   // do this after the loop above in case Caller and Callee are the same.
210   CallerNode->removeCallEdgeFor(CS);
211 }
212
213 // InlineFunction - This function inlines the called function into the basic
214 // block of the caller.  This returns false if it is not possible to inline this
215 // call.  The program is still in a well defined state if this occurs though.
216 //
217 // Note that this only does one level of inlining.  For example, if the
218 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
219 // exists in the instruction stream.  Similiarly this will inline a recursive
220 // function by one level.
221 //
222 bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD,
223                           SmallVectorImpl<AllocaInst*> *StaticAllocas) {
224   Instruction *TheCall = CS.getInstruction();
225   LLVMContext &Context = TheCall->getContext();
226   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
227          "Instruction not in function!");
228
229   const Function *CalledFunc = CS.getCalledFunction();
230   if (CalledFunc == 0 ||          // Can't inline external function or indirect
231       CalledFunc->isDeclaration() || // call, or call to a vararg function!
232       CalledFunc->getFunctionType()->isVarArg()) return false;
233
234
235   // If the call to the callee is not a tail call, we must clear the 'tail'
236   // flags on any calls that we inline.
237   bool MustClearTailCallFlags =
238     !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
239
240   // If the call to the callee cannot throw, set the 'nounwind' flag on any
241   // calls that we inline.
242   bool MarkNoUnwind = CS.doesNotThrow();
243
244   BasicBlock *OrigBB = TheCall->getParent();
245   Function *Caller = OrigBB->getParent();
246
247   // GC poses two hazards to inlining, which only occur when the callee has GC:
248   //  1. If the caller has no GC, then the callee's GC must be propagated to the
249   //     caller.
250   //  2. If the caller has a differing GC, it is invalid to inline.
251   if (CalledFunc->hasGC()) {
252     if (!Caller->hasGC())
253       Caller->setGC(CalledFunc->getGC());
254     else if (CalledFunc->getGC() != Caller->getGC())
255       return false;
256   }
257
258   // Get an iterator to the last basic block in the function, which will have
259   // the new function inlined after it.
260   //
261   Function::iterator LastBlock = &Caller->back();
262
263   // Make sure to capture all of the return instructions from the cloned
264   // function.
265   SmallVector<ReturnInst*, 8> Returns;
266   ClonedCodeInfo InlinedFunctionInfo;
267   Function::iterator FirstNewBlock;
268
269   { // Scope to destroy ValueMap after cloning.
270     DenseMap<const Value*, Value*> ValueMap;
271
272     assert(CalledFunc->arg_size() == CS.arg_size() &&
273            "No varargs calls can be inlined!");
274
275     // Calculate the vector of arguments to pass into the function cloner, which
276     // matches up the formal to the actual argument values.
277     CallSite::arg_iterator AI = CS.arg_begin();
278     unsigned ArgNo = 0;
279     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
280          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
281       Value *ActualArg = *AI;
282
283       // When byval arguments actually inlined, we need to make the copy implied
284       // by them explicit.  However, we don't do this if the callee is readonly
285       // or readnone, because the copy would be unneeded: the callee doesn't
286       // modify the struct.
287       if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
288           !CalledFunc->onlyReadsMemory()) {
289         const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
290         const Type *VoidPtrTy = 
291             Type::getInt8PtrTy(Context);
292
293         // Create the alloca.  If we have TargetData, use nice alignment.
294         unsigned Align = 1;
295         if (TD) Align = TD->getPrefTypeAlignment(AggTy);
296         Value *NewAlloca = new AllocaInst(AggTy, 0, Align, 
297                                           I->getName(), 
298                                           &*Caller->begin()->begin());
299         // Emit a memcpy.
300         const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
301         Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
302                                                        Intrinsic::memcpy, 
303                                                        Tys, 3);
304         Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
305         Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
306
307         Value *Size;
308         if (TD == 0)
309           Size = ConstantExpr::getSizeOf(AggTy);
310         else
311           Size = ConstantInt::get(Type::getInt64Ty(Context),
312                                   TD->getTypeStoreSize(AggTy));
313
314         // Always generate a memcpy of alignment 1 here because we don't know
315         // the alignment of the src pointer.  Other optimizations can infer
316         // better alignment.
317         Value *CallArgs[] = {
318           DestCast, SrcCast, Size,
319           ConstantInt::get(Type::getInt32Ty(Context), 1),
320           ConstantInt::get(Type::getInt1Ty(Context), 0)
321         };
322         CallInst *TheMemCpy =
323           CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
324
325         // If we have a call graph, update it.
326         if (CG) {
327           CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
328           CallGraphNode *CallerNode = (*CG)[Caller];
329           CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
330         }
331
332         // Uses of the argument in the function should use our new alloca
333         // instead.
334         ActualArg = NewAlloca;
335       }
336
337       ValueMap[I] = ActualArg;
338     }
339
340     // We want the inliner to prune the code as it copies.  We would LOVE to
341     // have no dead or constant instructions leftover after inlining occurs
342     // (which can happen, e.g., because an argument was constant), but we'll be
343     // happy with whatever the cloner can do.
344     CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
345                               &InlinedFunctionInfo, TD, TheCall);
346
347     // Remember the first block that is newly cloned over.
348     FirstNewBlock = LastBlock; ++FirstNewBlock;
349
350     // Update the callgraph if requested.
351     if (CG)
352       UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
353   }
354
355   // If there are any alloca instructions in the block that used to be the entry
356   // block for the callee, move them to the entry block of the caller.  First
357   // calculate which instruction they should be inserted before.  We insert the
358   // instructions at the end of the current alloca list.
359   //
360   {
361     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
362     for (BasicBlock::iterator I = FirstNewBlock->begin(),
363          E = FirstNewBlock->end(); I != E; ) {
364       AllocaInst *AI = dyn_cast<AllocaInst>(I++);
365       if (AI == 0) continue;
366       
367       // If the alloca is now dead, remove it.  This often occurs due to code
368       // specialization.
369       if (AI->use_empty()) {
370         AI->eraseFromParent();
371         continue;
372       }
373
374       if (!isa<Constant>(AI->getArraySize()))
375         continue;
376       
377       // Keep track of the static allocas that we inline into the caller if the
378       // StaticAllocas pointer is non-null.
379       if (StaticAllocas) StaticAllocas->push_back(AI);
380       
381       // Scan for the block of allocas that we can move over, and move them
382       // all at once.
383       while (isa<AllocaInst>(I) &&
384              isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
385         if (StaticAllocas) StaticAllocas->push_back(cast<AllocaInst>(I));
386         ++I;
387       }
388
389       // Transfer all of the allocas over in a block.  Using splice means
390       // that the instructions aren't removed from the symbol table, then
391       // reinserted.
392       Caller->getEntryBlock().getInstList().splice(InsertPoint,
393                                                    FirstNewBlock->getInstList(),
394                                                    AI, I);
395     }
396   }
397
398   // If the inlined code contained dynamic alloca instructions, wrap the inlined
399   // code with llvm.stacksave/llvm.stackrestore intrinsics.
400   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
401     Module *M = Caller->getParent();
402     // Get the two intrinsics we care about.
403     Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
404     Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
405
406     // If we are preserving the callgraph, add edges to the stacksave/restore
407     // functions for the calls we insert.
408     CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
409     if (CG) {
410       StackSaveCGN    = CG->getOrInsertFunction(StackSave);
411       StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
412       CallerNode = (*CG)[Caller];
413     }
414
415     // Insert the llvm.stacksave.
416     CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
417                                           FirstNewBlock->begin());
418     if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
419
420     // Insert a call to llvm.stackrestore before any return instructions in the
421     // inlined function.
422     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
423       CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
424       if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
425     }
426
427     // Count the number of StackRestore calls we insert.
428     unsigned NumStackRestores = Returns.size();
429
430     // If we are inlining an invoke instruction, insert restores before each
431     // unwind.  These unwinds will be rewritten into branches later.
432     if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
433       for (Function::iterator BB = FirstNewBlock, E = Caller->end();
434            BB != E; ++BB)
435         if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
436           CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
437           if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
438           ++NumStackRestores;
439         }
440     }
441   }
442
443   // If we are inlining tail call instruction through a call site that isn't
444   // marked 'tail', we must remove the tail marker for any calls in the inlined
445   // code.  Also, calls inlined through a 'nounwind' call site should be marked
446   // 'nounwind'.
447   if (InlinedFunctionInfo.ContainsCalls &&
448       (MustClearTailCallFlags || MarkNoUnwind)) {
449     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
450          BB != E; ++BB)
451       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
452         if (CallInst *CI = dyn_cast<CallInst>(I)) {
453           if (MustClearTailCallFlags)
454             CI->setTailCall(false);
455           if (MarkNoUnwind)
456             CI->setDoesNotThrow();
457         }
458   }
459
460   // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
461   // instructions are unreachable.
462   if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
463     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
464          BB != E; ++BB) {
465       TerminatorInst *Term = BB->getTerminator();
466       if (isa<UnwindInst>(Term)) {
467         new UnreachableInst(Context, Term);
468         BB->getInstList().erase(Term);
469       }
470     }
471
472   // If we are inlining for an invoke instruction, we must make sure to rewrite
473   // any inlined 'unwind' instructions into branches to the invoke exception
474   // destination, and call instructions into invoke instructions.
475   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
476     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
477
478   // If we cloned in _exactly one_ basic block, and if that block ends in a
479   // return instruction, we splice the body of the inlined callee directly into
480   // the calling basic block.
481   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
482     // Move all of the instructions right before the call.
483     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
484                                  FirstNewBlock->begin(), FirstNewBlock->end());
485     // Remove the cloned basic block.
486     Caller->getBasicBlockList().pop_back();
487
488     // If the call site was an invoke instruction, add a branch to the normal
489     // destination.
490     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
491       BranchInst::Create(II->getNormalDest(), TheCall);
492
493     // If the return instruction returned a value, replace uses of the call with
494     // uses of the returned value.
495     if (!TheCall->use_empty()) {
496       ReturnInst *R = Returns[0];
497       if (TheCall == R->getReturnValue())
498         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
499       else
500         TheCall->replaceAllUsesWith(R->getReturnValue());
501     }
502     // Since we are now done with the Call/Invoke, we can delete it.
503     TheCall->eraseFromParent();
504
505     // Since we are now done with the return instruction, delete it also.
506     Returns[0]->eraseFromParent();
507
508     // We are now done with the inlining.
509     return true;
510   }
511
512   // Otherwise, we have the normal case, of more than one block to inline or
513   // multiple return sites.
514
515   // We want to clone the entire callee function into the hole between the
516   // "starter" and "ender" blocks.  How we accomplish this depends on whether
517   // this is an invoke instruction or a call instruction.
518   BasicBlock *AfterCallBB;
519   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
520
521     // Add an unconditional branch to make this look like the CallInst case...
522     BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
523
524     // Split the basic block.  This guarantees that no PHI nodes will have to be
525     // updated due to new incoming edges, and make the invoke case more
526     // symmetric to the call case.
527     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
528                                           CalledFunc->getName()+".exit");
529
530   } else {  // It's a call
531     // If this is a call instruction, we need to split the basic block that
532     // the call lives in.
533     //
534     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
535                                           CalledFunc->getName()+".exit");
536   }
537
538   // Change the branch that used to go to AfterCallBB to branch to the first
539   // basic block of the inlined function.
540   //
541   TerminatorInst *Br = OrigBB->getTerminator();
542   assert(Br && Br->getOpcode() == Instruction::Br &&
543          "splitBasicBlock broken!");
544   Br->setOperand(0, FirstNewBlock);
545
546
547   // Now that the function is correct, make it a little bit nicer.  In
548   // particular, move the basic blocks inserted from the end of the function
549   // into the space made by splitting the source basic block.
550   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
551                                      FirstNewBlock, Caller->end());
552
553   // Handle all of the return instructions that we just cloned in, and eliminate
554   // any users of the original call/invoke instruction.
555   const Type *RTy = CalledFunc->getReturnType();
556
557   if (Returns.size() > 1) {
558     // The PHI node should go at the front of the new basic block to merge all
559     // possible incoming values.
560     PHINode *PHI = 0;
561     if (!TheCall->use_empty()) {
562       PHI = PHINode::Create(RTy, TheCall->getName(),
563                             AfterCallBB->begin());
564       // Anything that used the result of the function call should now use the
565       // PHI node as their operand.
566       TheCall->replaceAllUsesWith(PHI);
567     }
568
569     // Loop over all of the return instructions adding entries to the PHI node
570     // as appropriate.
571     if (PHI) {
572       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
573         ReturnInst *RI = Returns[i];
574         assert(RI->getReturnValue()->getType() == PHI->getType() &&
575                "Ret value not consistent in function!");
576         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
577       }
578     
579       // Now that we inserted the PHI, check to see if it has a single value
580       // (e.g. all the entries are the same or undef).  If so, remove the PHI so
581       // it doesn't block other optimizations.
582       if (Value *V = PHI->hasConstantValue()) {
583         PHI->replaceAllUsesWith(V);
584         PHI->eraseFromParent();
585       }
586     }
587
588
589     // Add a branch to the merge points and remove return instructions.
590     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
591       ReturnInst *RI = Returns[i];
592       BranchInst::Create(AfterCallBB, RI);
593       RI->eraseFromParent();
594     }
595   } else if (!Returns.empty()) {
596     // Otherwise, if there is exactly one return value, just replace anything
597     // using the return value of the call with the computed value.
598     if (!TheCall->use_empty()) {
599       if (TheCall == Returns[0]->getReturnValue())
600         TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
601       else
602         TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
603     }
604
605     // Splice the code from the return block into the block that it will return
606     // to, which contains the code that was after the call.
607     BasicBlock *ReturnBB = Returns[0]->getParent();
608     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
609                                       ReturnBB->getInstList());
610
611     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
612     ReturnBB->replaceAllUsesWith(AfterCallBB);
613
614     // Delete the return instruction now and empty ReturnBB now.
615     Returns[0]->eraseFromParent();
616     ReturnBB->eraseFromParent();
617   } else if (!TheCall->use_empty()) {
618     // No returns, but something is using the return value of the call.  Just
619     // nuke the result.
620     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
621   }
622
623   // Since we are now done with the Call/Invoke, we can delete it.
624   TheCall->eraseFromParent();
625
626   // We should always be able to fold the entry block of the function into the
627   // single predecessor of the block...
628   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
629   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
630
631   // Splice the code entry block into calling block, right before the
632   // unconditional branch.
633   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
634   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
635
636   // Remove the unconditional branch.
637   OrigBB->getInstList().erase(Br);
638
639   // Now we can remove the CalleeEntry block, which is now empty.
640   Caller->getBasicBlockList().erase(CalleeEntry);
641
642   return true;
643 }