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