InlineFunction.cpp revision a3de16bc8f36638d5444e3e7b0112998af54f826
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// The code in this file for handling inlines through invoke
14// instructions preserves semantics only under some assumptions about
15// the behavior of unwinders which correspond to gcc-style libUnwind
16// exception personality functions.  Eventually the IR will be
17// improved to make this unnecessary, but until then, this code is
18// marked [LIBUNWIND].
19//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Utils/Cloning.h"
23#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Module.h"
26#include "llvm/Instructions.h"
27#include "llvm/IntrinsicInst.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/Attributes.h"
30#include "llvm/Analysis/CallGraph.h"
31#include "llvm/Analysis/DebugInfo.h"
32#include "llvm/Analysis/InstructionSimplify.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/Local.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/CallSite.h"
38#include "llvm/Support/IRBuilder.h"
39using namespace llvm;
40
41bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI) {
42  return InlineFunction(CallSite(CI), IFI);
43}
44bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI) {
45  return InlineFunction(CallSite(II), IFI);
46}
47
48namespace {
49  /// A class for recording information about inlining through an invoke.
50  class InvokeInliningInfo {
51    BasicBlock *UnwindDest;
52    SmallVector<Value*, 8> UnwindDestPHIValues;
53
54  public:
55    InvokeInliningInfo(InvokeInst *II) : UnwindDest(II->getUnwindDest()) {
56      // If there are PHI nodes in the unwind destination block, we
57      // need to keep track of which values came into them from the
58      // invoke before removing the edge from this block.
59      llvm::BasicBlock *InvokeBlock = II->getParent();
60      for (BasicBlock::iterator I = UnwindDest->begin(); isa<PHINode>(I); ++I) {
61        PHINode *PN = cast<PHINode>(I);
62        // Save the value to use for this edge.
63        llvm::Value *Incoming = PN->getIncomingValueForBlock(InvokeBlock);
64        UnwindDestPHIValues.push_back(Incoming);
65      }
66    }
67
68    BasicBlock *getUnwindDest() const {
69      return UnwindDest;
70    }
71
72    /// Add incoming-PHI values to the unwind destination block for
73    /// the given basic block, using the values for the original
74    /// invoke's source block.
75    void addIncomingPHIValuesFor(BasicBlock *BB) const {
76      BasicBlock::iterator I = UnwindDest->begin();
77      for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
78        PHINode *PN = cast<PHINode>(I);
79        PN->addIncoming(UnwindDestPHIValues[i], BB);
80      }
81    }
82  };
83}
84
85/// [LIBUNWIND] Check whether the given value is the _Unwind_Resume
86/// function specified by the Itanium EH ABI.
87static bool isUnwindResume(Value *value) {
88  Function *fn = dyn_cast<Function>(value);
89  if (!fn) return false;
90
91  // declare void @_Unwind_Resume(i8*)
92  if (fn->getName() != "_Unwind_Resume") return false;
93  const FunctionType *fnType = fn->getFunctionType();
94  if (!fnType->getReturnType()->isVoidTy()) return false;
95  if (fnType->isVarArg()) return false;
96  if (fnType->getNumParams() != 1) return false;
97  const PointerType *paramType = dyn_cast<PointerType>(fnType->getParamType(0));
98  return (paramType && paramType->getElementType()->isIntegerTy(8));
99}
100
101/// [LIBUNWIND] Find the (possibly absent) call to @llvm.eh.selector in
102/// the given landing pad.
103static EHSelectorInst *findSelectorForLandingPad(BasicBlock *lpad) {
104  for (BasicBlock::iterator i = lpad->begin(), e = lpad->end(); i != e; i++)
105    if (EHSelectorInst *selector = dyn_cast<EHSelectorInst>(i))
106      return selector;
107  return 0;
108}
109
110/// [LIBUNWIND] Check whether this selector is "only cleanups":
111///   call i32 @llvm.eh.selector(blah, blah, i32 0)
112static bool isCleanupOnlySelector(EHSelectorInst *selector) {
113  if (selector->getNumArgOperands() != 3) return false;
114  ConstantInt *val = dyn_cast<ConstantInt>(selector->getArgOperand(2));
115  return (val && val->isZero());
116}
117
118/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
119/// an invoke, we have to turn all of the calls that can throw into
120/// invokes.  This function analyze BB to see if there are any calls, and if so,
121/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
122/// nodes in that block with the values specified in InvokeDestPHIValues.
123///
124/// Returns true to indicate that the next block should be skipped.
125static bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
126                                                   InvokeInliningInfo &Invoke) {
127  for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
128    Instruction *I = BBI++;
129
130    // We only need to check for function calls: inlined invoke
131    // instructions require no special handling.
132    CallInst *CI = dyn_cast<CallInst>(I);
133    if (CI == 0) continue;
134
135    // LIBUNWIND: merge selector instructions.
136    if (EHSelectorInst *Inner = dyn_cast<EHSelectorInst>(CI)) {
137      EHSelectorInst *Outer = findSelectorForLandingPad(Invoke.getUnwindDest());
138      if (!Outer) continue;
139
140      bool innerIsOnlyCleanup = isCleanupOnlySelector(Inner);
141      bool outerIsOnlyCleanup = isCleanupOnlySelector(Outer);
142
143      // If both selectors contain only cleanups, we don't need to do
144      // anything.  TODO: this is really just a very specific instance
145      // of a much more general optimization.
146      if (innerIsOnlyCleanup && outerIsOnlyCleanup) continue;
147
148      // Otherwise, we just append the outer selector to the inner selector.
149      SmallVector<Value*, 16> NewSelector;
150      for (unsigned i = 0, e = Inner->getNumArgOperands(); i != e; ++i)
151        NewSelector.push_back(Inner->getArgOperand(i));
152      for (unsigned i = 2, e = Outer->getNumArgOperands(); i != e; ++i)
153        NewSelector.push_back(Outer->getArgOperand(i));
154
155      CallInst *NewInner = CallInst::Create(Inner->getCalledValue(),
156                                            NewSelector.begin(),
157                                            NewSelector.end(),
158                                            "",
159                                            Inner);
160      // No need to copy attributes, calling convention, etc.
161      NewInner->takeName(Inner);
162      Inner->replaceAllUsesWith(NewInner);
163      Inner->eraseFromParent();
164      continue;
165    }
166
167    // If this call cannot unwind, don't convert it to an invoke.
168    if (CI->doesNotThrow())
169      continue;
170
171    // Convert this function call into an invoke instruction.
172    // First, split the basic block.
173    BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
174
175    bool skipNextBlock = false;
176
177    // LIBUNWIND: If this is a call to @_Unwind_Resume, just branch
178    // directly to the new landing pad.
179    if (isUnwindResume(CI->getCalledValue())) {
180      BranchInst::Create(Invoke.getUnwindDest(), BB->getTerminator());
181
182      // TODO: 'Split' is now unreachable; clean it up.
183
184      // We want to leave the original call intact so that the call
185      // graph and other structures won't get misled.  We also have to
186      // avoid processing the next block, or we'll iterate here forever.
187      skipNextBlock = true;
188
189    // Otherwise, create the new invoke instruction.
190    } else {
191      ImmutableCallSite CS(CI);
192      SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
193      InvokeInst *II =
194        InvokeInst::Create(CI->getCalledValue(), Split, Invoke.getUnwindDest(),
195                           InvokeArgs.begin(), InvokeArgs.end(),
196                           CI->getName(), BB->getTerminator());
197      II->setCallingConv(CI->getCallingConv());
198      II->setAttributes(CI->getAttributes());
199
200      // Make sure that anything using the call now uses the invoke!  This also
201      // updates the CallGraph if present, because it uses a WeakVH.
202      CI->replaceAllUsesWith(II);
203
204      Split->getInstList().pop_front();  // Delete the original call
205    }
206
207    // Delete the unconditional branch inserted by splitBasicBlock
208    BB->getInstList().pop_back();
209
210    // Update any PHI nodes in the exceptional block to indicate that
211    // there is now a new entry in them.
212    Invoke.addIncomingPHIValuesFor(BB);
213
214    // This basic block is now complete, the caller will continue scanning the
215    // next one.
216    return skipNextBlock;
217  }
218
219  return false;
220}
221
222
223/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
224/// in the body of the inlined function into invokes and turn unwind
225/// instructions into branches to the invoke unwind dest.
226///
227/// II is the invoke instruction being inlined.  FirstNewBlock is the first
228/// block of the inlined code (the last block is the end of the function),
229/// and InlineCodeInfo is information about the code that got inlined.
230static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
231                                ClonedCodeInfo &InlinedCodeInfo) {
232  BasicBlock *InvokeDest = II->getUnwindDest();
233
234  Function *Caller = FirstNewBlock->getParent();
235
236  // The inlined code is currently at the end of the function, scan from the
237  // start of the inlined code to its end, checking for stuff we need to
238  // rewrite.  If the code doesn't have calls or unwinds, we know there is
239  // nothing to rewrite.
240  if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
241    // Now that everything is happy, we have one final detail.  The PHI nodes in
242    // the exception destination block still have entries due to the original
243    // invoke instruction.  Eliminate these entries (which might even delete the
244    // PHI node) now.
245    InvokeDest->removePredecessor(II->getParent());
246    return;
247  }
248
249  InvokeInliningInfo Invoke(II);
250
251  for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
252    if (InlinedCodeInfo.ContainsCalls)
253      if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
254        // Honor a request to skip the next block.  We don't need to
255        // consider UnwindInsts in this case either.
256        ++BB;
257        continue;
258      }
259
260    if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
261      // An UnwindInst requires special handling when it gets inlined into an
262      // invoke site.  Once this happens, we know that the unwind would cause
263      // a control transfer to the invoke exception destination, so we can
264      // transform it into a direct branch to the exception destination.
265      BranchInst::Create(InvokeDest, UI);
266
267      // Delete the unwind instruction!
268      UI->eraseFromParent();
269
270      // Update any PHI nodes in the exceptional block to indicate that
271      // there is now a new entry in them.
272      Invoke.addIncomingPHIValuesFor(BB);
273    }
274  }
275
276  // Now that everything is happy, we have one final detail.  The PHI nodes in
277  // the exception destination block still have entries due to the original
278  // invoke instruction.  Eliminate these entries (which might even delete the
279  // PHI node) now.
280  InvokeDest->removePredecessor(II->getParent());
281}
282
283/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
284/// into the caller, update the specified callgraph to reflect the changes we
285/// made.  Note that it's possible that not all code was copied over, so only
286/// some edges of the callgraph may remain.
287static void UpdateCallGraphAfterInlining(CallSite CS,
288                                         Function::iterator FirstNewBlock,
289                                         ValueToValueMapTy &VMap,
290                                         InlineFunctionInfo &IFI) {
291  CallGraph &CG = *IFI.CG;
292  const Function *Caller = CS.getInstruction()->getParent()->getParent();
293  const Function *Callee = CS.getCalledFunction();
294  CallGraphNode *CalleeNode = CG[Callee];
295  CallGraphNode *CallerNode = CG[Caller];
296
297  // Since we inlined some uninlined call sites in the callee into the caller,
298  // add edges from the caller to all of the callees of the callee.
299  CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
300
301  // Consider the case where CalleeNode == CallerNode.
302  CallGraphNode::CalledFunctionsVector CallCache;
303  if (CalleeNode == CallerNode) {
304    CallCache.assign(I, E);
305    I = CallCache.begin();
306    E = CallCache.end();
307  }
308
309  for (; I != E; ++I) {
310    const Value *OrigCall = I->first;
311
312    ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
313    // Only copy the edge if the call was inlined!
314    if (VMI == VMap.end() || VMI->second == 0)
315      continue;
316
317    // If the call was inlined, but then constant folded, there is no edge to
318    // add.  Check for this case.
319    Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
320    if (NewCall == 0) continue;
321
322    // Remember that this call site got inlined for the client of
323    // InlineFunction.
324    IFI.InlinedCalls.push_back(NewCall);
325
326    // It's possible that inlining the callsite will cause it to go from an
327    // indirect to a direct call by resolving a function pointer.  If this
328    // happens, set the callee of the new call site to a more precise
329    // destination.  This can also happen if the call graph node of the caller
330    // was just unnecessarily imprecise.
331    if (I->second->getFunction() == 0)
332      if (Function *F = CallSite(NewCall).getCalledFunction()) {
333        // Indirect call site resolved to direct call.
334        CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
335
336        continue;
337      }
338
339    CallerNode->addCalledFunction(CallSite(NewCall), I->second);
340  }
341
342  // Update the call graph by deleting the edge from Callee to Caller.  We must
343  // do this after the loop above in case Caller and Callee are the same.
344  CallerNode->removeCallEdgeFor(CS);
345}
346
347/// HandleByValArgument - When inlining a call site that has a byval argument,
348/// we have to make the implicit memcpy explicit by adding it.
349static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
350                                  const Function *CalledFunc,
351                                  InlineFunctionInfo &IFI,
352                                  unsigned ByValAlignment) {
353  const Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
354
355  // If the called function is readonly, then it could not mutate the caller's
356  // copy of the byval'd memory.  In this case, it is safe to elide the copy and
357  // temporary.
358  if (CalledFunc->onlyReadsMemory()) {
359    // If the byval argument has a specified alignment that is greater than the
360    // passed in pointer, then we either have to round up the input pointer or
361    // give up on this transformation.
362    if (ByValAlignment <= 1)  // 0 = unspecified, 1 = no particular alignment.
363      return Arg;
364
365    // If the pointer is already known to be sufficiently aligned, or if we can
366    // round it up to a larger alignment, then we don't need a temporary.
367    if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
368                                   IFI.TD) >= ByValAlignment)
369      return Arg;
370
371    // Otherwise, we have to make a memcpy to get a safe alignment.  This is bad
372    // for code quality, but rarely happens and is required for correctness.
373  }
374
375  LLVMContext &Context = Arg->getContext();
376
377  const Type *VoidPtrTy = Type::getInt8PtrTy(Context);
378
379  // Create the alloca.  If we have TargetData, use nice alignment.
380  unsigned Align = 1;
381  if (IFI.TD)
382    Align = IFI.TD->getPrefTypeAlignment(AggTy);
383
384  // If the byval had an alignment specified, we *must* use at least that
385  // alignment, as it is required by the byval argument (and uses of the
386  // pointer inside the callee).
387  Align = std::max(Align, ByValAlignment);
388
389  Function *Caller = TheCall->getParent()->getParent();
390
391  Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
392                                    &*Caller->begin()->begin());
393  // Emit a memcpy.
394  const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
395  Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
396                                                 Intrinsic::memcpy,
397                                                 Tys, 3);
398  Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
399  Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
400
401  Value *Size;
402  if (IFI.TD == 0)
403    Size = ConstantExpr::getSizeOf(AggTy);
404  else
405    Size = ConstantInt::get(Type::getInt64Ty(Context),
406                            IFI.TD->getTypeStoreSize(AggTy));
407
408  // Always generate a memcpy of alignment 1 here because we don't know
409  // the alignment of the src pointer.  Other optimizations can infer
410  // better alignment.
411  Value *CallArgs[] = {
412    DestCast, SrcCast, Size,
413    ConstantInt::get(Type::getInt32Ty(Context), 1),
414    ConstantInt::getFalse(Context) // isVolatile
415  };
416  CallInst *TheMemCpy =
417    CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
418
419  // If we have a call graph, update it.
420  if (CallGraph *CG = IFI.CG) {
421    CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
422    CallGraphNode *CallerNode = (*CG)[Caller];
423    CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
424  }
425
426  // Uses of the argument in the function should use our new alloca
427  // instead.
428  return NewAlloca;
429}
430
431// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
432// intrinsic.
433static bool isUsedByLifetimeMarker(Value *V) {
434  for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
435       ++UI) {
436    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
437      switch (II->getIntrinsicID()) {
438      default: break;
439      case Intrinsic::lifetime_start:
440      case Intrinsic::lifetime_end:
441        return true;
442      }
443    }
444  }
445  return false;
446}
447
448// hasLifetimeMarkers - Check whether the given alloca already has
449// lifetime.start or lifetime.end intrinsics.
450static bool hasLifetimeMarkers(AllocaInst *AI) {
451  const Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
452  if (AI->getType() == Int8PtrTy)
453    return isUsedByLifetimeMarker(AI);
454
455  // Do a scan to find all the bitcasts to i8*.
456  for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E;
457       ++I) {
458    if (I->getType() != Int8PtrTy) continue;
459    if (!isa<BitCastInst>(*I)) continue;
460    if (isUsedByLifetimeMarker(*I))
461      return true;
462  }
463  return false;
464}
465
466// InlineFunction - This function inlines the called function into the basic
467// block of the caller.  This returns false if it is not possible to inline this
468// call.  The program is still in a well defined state if this occurs though.
469//
470// Note that this only does one level of inlining.  For example, if the
471// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
472// exists in the instruction stream.  Similarly this will inline a recursive
473// function by one level.
474//
475bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
476  Instruction *TheCall = CS.getInstruction();
477  LLVMContext &Context = TheCall->getContext();
478  assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
479         "Instruction not in function!");
480
481  // If IFI has any state in it, zap it before we fill it in.
482  IFI.reset();
483
484  const Function *CalledFunc = CS.getCalledFunction();
485  if (CalledFunc == 0 ||          // Can't inline external function or indirect
486      CalledFunc->isDeclaration() || // call, or call to a vararg function!
487      CalledFunc->getFunctionType()->isVarArg()) return false;
488
489  // If the call to the callee is not a tail call, we must clear the 'tail'
490  // flags on any calls that we inline.
491  bool MustClearTailCallFlags =
492    !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
493
494  // If the call to the callee cannot throw, set the 'nounwind' flag on any
495  // calls that we inline.
496  bool MarkNoUnwind = CS.doesNotThrow();
497
498  BasicBlock *OrigBB = TheCall->getParent();
499  Function *Caller = OrigBB->getParent();
500
501  // GC poses two hazards to inlining, which only occur when the callee has GC:
502  //  1. If the caller has no GC, then the callee's GC must be propagated to the
503  //     caller.
504  //  2. If the caller has a differing GC, it is invalid to inline.
505  if (CalledFunc->hasGC()) {
506    if (!Caller->hasGC())
507      Caller->setGC(CalledFunc->getGC());
508    else if (CalledFunc->getGC() != Caller->getGC())
509      return false;
510  }
511
512  // Get an iterator to the last basic block in the function, which will have
513  // the new function inlined after it.
514  //
515  Function::iterator LastBlock = &Caller->back();
516
517  // Make sure to capture all of the return instructions from the cloned
518  // function.
519  SmallVector<ReturnInst*, 8> Returns;
520  ClonedCodeInfo InlinedFunctionInfo;
521  Function::iterator FirstNewBlock;
522
523  { // Scope to destroy VMap after cloning.
524    ValueToValueMapTy VMap;
525
526    assert(CalledFunc->arg_size() == CS.arg_size() &&
527           "No varargs calls can be inlined!");
528
529    // Calculate the vector of arguments to pass into the function cloner, which
530    // matches up the formal to the actual argument values.
531    CallSite::arg_iterator AI = CS.arg_begin();
532    unsigned ArgNo = 0;
533    for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
534         E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
535      Value *ActualArg = *AI;
536
537      // When byval arguments actually inlined, we need to make the copy implied
538      // by them explicit.  However, we don't do this if the callee is readonly
539      // or readnone, because the copy would be unneeded: the callee doesn't
540      // modify the struct.
541      if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
542        ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
543                                        CalledFunc->getParamAlignment(ArgNo+1));
544
545        // Calls that we inline may use the new alloca, so we need to clear
546        // their 'tail' flags if HandleByValArgument introduced a new alloca and
547        // the callee has calls.
548        MustClearTailCallFlags |= ActualArg != *AI;
549      }
550
551      VMap[I] = ActualArg;
552    }
553
554    // We want the inliner to prune the code as it copies.  We would LOVE to
555    // have no dead or constant instructions leftover after inlining occurs
556    // (which can happen, e.g., because an argument was constant), but we'll be
557    // happy with whatever the cloner can do.
558    CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
559                              /*ModuleLevelChanges=*/false, Returns, ".i",
560                              &InlinedFunctionInfo, IFI.TD, TheCall);
561
562    // Remember the first block that is newly cloned over.
563    FirstNewBlock = LastBlock; ++FirstNewBlock;
564
565    // Update the callgraph if requested.
566    if (IFI.CG)
567      UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
568  }
569
570  // If there are any alloca instructions in the block that used to be the entry
571  // block for the callee, move them to the entry block of the caller.  First
572  // calculate which instruction they should be inserted before.  We insert the
573  // instructions at the end of the current alloca list.
574  //
575  {
576    BasicBlock::iterator InsertPoint = Caller->begin()->begin();
577    for (BasicBlock::iterator I = FirstNewBlock->begin(),
578         E = FirstNewBlock->end(); I != E; ) {
579      AllocaInst *AI = dyn_cast<AllocaInst>(I++);
580      if (AI == 0) continue;
581
582      // If the alloca is now dead, remove it.  This often occurs due to code
583      // specialization.
584      if (AI->use_empty()) {
585        AI->eraseFromParent();
586        continue;
587      }
588
589      if (!isa<Constant>(AI->getArraySize()))
590        continue;
591
592      // Keep track of the static allocas that we inline into the caller.
593      IFI.StaticAllocas.push_back(AI);
594
595      // Scan for the block of allocas that we can move over, and move them
596      // all at once.
597      while (isa<AllocaInst>(I) &&
598             isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
599        IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
600        ++I;
601      }
602
603      // Transfer all of the allocas over in a block.  Using splice means
604      // that the instructions aren't removed from the symbol table, then
605      // reinserted.
606      Caller->getEntryBlock().getInstList().splice(InsertPoint,
607                                                   FirstNewBlock->getInstList(),
608                                                   AI, I);
609    }
610  }
611
612  // Leave lifetime markers for the static alloca's, scoping them to the
613  // function we just inlined.
614  if (!IFI.StaticAllocas.empty()) {
615    // Also preserve the call graph, if applicable.
616    CallGraphNode *StartCGN = 0, *EndCGN = 0, *CallerNode = 0;
617    if (CallGraph *CG = IFI.CG) {
618      Function *Start = Intrinsic::getDeclaration(Caller->getParent(),
619                                                  Intrinsic::lifetime_start);
620      Function *End = Intrinsic::getDeclaration(Caller->getParent(),
621                                                Intrinsic::lifetime_end);
622      StartCGN = CG->getOrInsertFunction(Start);
623      EndCGN = CG->getOrInsertFunction(End);
624      CallerNode = (*CG)[Caller];
625    }
626
627    IRBuilder<> builder(FirstNewBlock->begin());
628    for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
629      AllocaInst *AI = IFI.StaticAllocas[ai];
630
631      // If the alloca is already scoped to something smaller than the whole
632      // function then there's no need to add redundant, less accurate markers.
633      if (hasLifetimeMarkers(AI))
634        continue;
635
636      CallInst *StartCall = builder.CreateLifetimeStart(AI);
637      if (IFI.CG) CallerNode->addCalledFunction(StartCall, StartCGN);
638      for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
639        IRBuilder<> builder(Returns[ri]);
640        CallInst *EndCall = builder.CreateLifetimeEnd(AI);
641        if (IFI.CG) CallerNode->addCalledFunction(EndCall, EndCGN);
642      }
643    }
644  }
645
646  // If the inlined code contained dynamic alloca instructions, wrap the inlined
647  // code with llvm.stacksave/llvm.stackrestore intrinsics.
648  if (InlinedFunctionInfo.ContainsDynamicAllocas) {
649    Module *M = Caller->getParent();
650    // Get the two intrinsics we care about.
651    Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
652    Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
653
654    // If we are preserving the callgraph, add edges to the stacksave/restore
655    // functions for the calls we insert.
656    CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
657    if (CallGraph *CG = IFI.CG) {
658      StackSaveCGN    = CG->getOrInsertFunction(StackSave);
659      StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
660      CallerNode = (*CG)[Caller];
661    }
662
663    // Insert the llvm.stacksave.
664    CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
665                                          FirstNewBlock->begin());
666    if (IFI.CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
667
668    // Insert a call to llvm.stackrestore before any return instructions in the
669    // inlined function.
670    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
671      CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
672      if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
673    }
674
675    // Count the number of StackRestore calls we insert.
676    unsigned NumStackRestores = Returns.size();
677
678    // If we are inlining an invoke instruction, insert restores before each
679    // unwind.  These unwinds will be rewritten into branches later.
680    if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
681      for (Function::iterator BB = FirstNewBlock, E = Caller->end();
682           BB != E; ++BB)
683        if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
684          CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
685          if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
686          ++NumStackRestores;
687        }
688    }
689  }
690
691  // If we are inlining tail call instruction through a call site that isn't
692  // marked 'tail', we must remove the tail marker for any calls in the inlined
693  // code.  Also, calls inlined through a 'nounwind' call site should be marked
694  // 'nounwind'.
695  if (InlinedFunctionInfo.ContainsCalls &&
696      (MustClearTailCallFlags || MarkNoUnwind)) {
697    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
698         BB != E; ++BB)
699      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
700        if (CallInst *CI = dyn_cast<CallInst>(I)) {
701          if (MustClearTailCallFlags)
702            CI->setTailCall(false);
703          if (MarkNoUnwind)
704            CI->setDoesNotThrow();
705        }
706  }
707
708  // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
709  // instructions are unreachable.
710  if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
711    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
712         BB != E; ++BB) {
713      TerminatorInst *Term = BB->getTerminator();
714      if (isa<UnwindInst>(Term)) {
715        new UnreachableInst(Context, Term);
716        BB->getInstList().erase(Term);
717      }
718    }
719
720  // If we are inlining for an invoke instruction, we must make sure to rewrite
721  // any inlined 'unwind' instructions into branches to the invoke exception
722  // destination, and call instructions into invoke instructions.
723  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
724    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
725
726  // If we cloned in _exactly one_ basic block, and if that block ends in a
727  // return instruction, we splice the body of the inlined callee directly into
728  // the calling basic block.
729  if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
730    // Move all of the instructions right before the call.
731    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
732                                 FirstNewBlock->begin(), FirstNewBlock->end());
733    // Remove the cloned basic block.
734    Caller->getBasicBlockList().pop_back();
735
736    // If the call site was an invoke instruction, add a branch to the normal
737    // destination.
738    if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
739      BranchInst::Create(II->getNormalDest(), TheCall);
740
741    // If the return instruction returned a value, replace uses of the call with
742    // uses of the returned value.
743    if (!TheCall->use_empty()) {
744      ReturnInst *R = Returns[0];
745      if (TheCall == R->getReturnValue())
746        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
747      else
748        TheCall->replaceAllUsesWith(R->getReturnValue());
749    }
750    // Since we are now done with the Call/Invoke, we can delete it.
751    TheCall->eraseFromParent();
752
753    // Since we are now done with the return instruction, delete it also.
754    Returns[0]->eraseFromParent();
755
756    // We are now done with the inlining.
757    return true;
758  }
759
760  // Otherwise, we have the normal case, of more than one block to inline or
761  // multiple return sites.
762
763  // We want to clone the entire callee function into the hole between the
764  // "starter" and "ender" blocks.  How we accomplish this depends on whether
765  // this is an invoke instruction or a call instruction.
766  BasicBlock *AfterCallBB;
767  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
768
769    // Add an unconditional branch to make this look like the CallInst case...
770    BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
771
772    // Split the basic block.  This guarantees that no PHI nodes will have to be
773    // updated due to new incoming edges, and make the invoke case more
774    // symmetric to the call case.
775    AfterCallBB = OrigBB->splitBasicBlock(NewBr,
776                                          CalledFunc->getName()+".exit");
777
778  } else {  // It's a call
779    // If this is a call instruction, we need to split the basic block that
780    // the call lives in.
781    //
782    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
783                                          CalledFunc->getName()+".exit");
784  }
785
786  // Change the branch that used to go to AfterCallBB to branch to the first
787  // basic block of the inlined function.
788  //
789  TerminatorInst *Br = OrigBB->getTerminator();
790  assert(Br && Br->getOpcode() == Instruction::Br &&
791         "splitBasicBlock broken!");
792  Br->setOperand(0, FirstNewBlock);
793
794
795  // Now that the function is correct, make it a little bit nicer.  In
796  // particular, move the basic blocks inserted from the end of the function
797  // into the space made by splitting the source basic block.
798  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
799                                     FirstNewBlock, Caller->end());
800
801  // Handle all of the return instructions that we just cloned in, and eliminate
802  // any users of the original call/invoke instruction.
803  const Type *RTy = CalledFunc->getReturnType();
804
805  PHINode *PHI = 0;
806  if (Returns.size() > 1) {
807    // The PHI node should go at the front of the new basic block to merge all
808    // possible incoming values.
809    if (!TheCall->use_empty()) {
810      PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
811                            AfterCallBB->begin());
812      // Anything that used the result of the function call should now use the
813      // PHI node as their operand.
814      TheCall->replaceAllUsesWith(PHI);
815    }
816
817    // Loop over all of the return instructions adding entries to the PHI node
818    // as appropriate.
819    if (PHI) {
820      for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
821        ReturnInst *RI = Returns[i];
822        assert(RI->getReturnValue()->getType() == PHI->getType() &&
823               "Ret value not consistent in function!");
824        PHI->addIncoming(RI->getReturnValue(), RI->getParent());
825      }
826    }
827
828
829    // Add a branch to the merge points and remove return instructions.
830    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
831      ReturnInst *RI = Returns[i];
832      BranchInst::Create(AfterCallBB, RI);
833      RI->eraseFromParent();
834    }
835  } else if (!Returns.empty()) {
836    // Otherwise, if there is exactly one return value, just replace anything
837    // using the return value of the call with the computed value.
838    if (!TheCall->use_empty()) {
839      if (TheCall == Returns[0]->getReturnValue())
840        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
841      else
842        TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
843    }
844
845    // Splice the code from the return block into the block that it will return
846    // to, which contains the code that was after the call.
847    BasicBlock *ReturnBB = Returns[0]->getParent();
848    AfterCallBB->getInstList().splice(AfterCallBB->begin(),
849                                      ReturnBB->getInstList());
850
851    // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
852    ReturnBB->replaceAllUsesWith(AfterCallBB);
853
854    // Delete the return instruction now and empty ReturnBB now.
855    Returns[0]->eraseFromParent();
856    ReturnBB->eraseFromParent();
857  } else if (!TheCall->use_empty()) {
858    // No returns, but something is using the return value of the call.  Just
859    // nuke the result.
860    TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
861  }
862
863  // Since we are now done with the Call/Invoke, we can delete it.
864  TheCall->eraseFromParent();
865
866  // We should always be able to fold the entry block of the function into the
867  // single predecessor of the block...
868  assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
869  BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
870
871  // Splice the code entry block into calling block, right before the
872  // unconditional branch.
873  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
874  CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
875
876  // Remove the unconditional branch.
877  OrigBB->getInstList().erase(Br);
878
879  // Now we can remove the CalleeEntry block, which is now empty.
880  Caller->getBasicBlockList().erase(CalleeEntry);
881
882  // If we inserted a phi node, check to see if it has a single value (e.g. all
883  // the entries are the same or undef).  If so, remove the PHI so it doesn't
884  // block other optimizations.
885  if (PHI)
886    if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
887      PHI->replaceAllUsesWith(V);
888      PHI->eraseFromParent();
889    }
890
891  return true;
892}
893