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