Re-commit r124462 with fixes. Tail recursion elim will now dup ret into unconditional...
[oota-llvm.git] / lib / Transforms / Scalar / TailRecursionElimination.cpp
1 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
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 transforms calls of the current function (self recursion) followed
11 // by a return instruction with a branch to the entry of the function, creating
12 // a loop.  This pass also implements the following extensions to the basic
13 // algorithm:
14 //
15 //  1. Trivial instructions between the call and return do not prevent the
16 //     transformation from taking place, though currently the analysis cannot
17 //     support moving any really useful instructions (only dead ones).
18 //  2. This pass transforms functions that are prevented from being tail
19 //     recursive by an associative and commutative expression to use an
20 //     accumulator variable, thus compiling the typical naive factorial or
21 //     'fib' implementation into efficient code.
22 //  3. TRE is performed if the function returns void, if the return
23 //     returns the result returned by the call, or if the function returns a
24 //     run-time constant on all exits from the function.  It is possible, though
25 //     unlikely, that the return returns something else (like constant 0), and
26 //     can still be TRE'd.  It can be TRE'd if ALL OTHER return instructions in
27 //     the function return the exact same value.
28 //  4. If it can prove that callees do not access their caller stack frame,
29 //     they are marked as eligible for tail call elimination (by the code
30 //     generator).
31 //
32 // There are several improvements that could be made:
33 //
34 //  1. If the function has any alloca instructions, these instructions will be
35 //     moved out of the entry block of the function, causing them to be
36 //     evaluated each time through the tail recursion.  Safely keeping allocas
37 //     in the entry block requires analysis to proves that the tail-called
38 //     function does not read or write the stack object.
39 //  2. Tail recursion is only performed if the call immediately preceeds the
40 //     return instruction.  It's possible that there could be a jump between
41 //     the call and the return.
42 //  3. There can be intervening operations between the call and the return that
43 //     prevent the TRE from occurring.  For example, there could be GEP's and
44 //     stores to memory that will not be read or written by the call.  This
45 //     requires some substantial analysis (such as with DSA) to prove safe to
46 //     move ahead of the call, but doing so could allow many more TREs to be
47 //     performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
48 //  4. The algorithm we use to detect if callees access their caller stack
49 //     frames is very primitive.
50 //
51 //===----------------------------------------------------------------------===//
52
53 #define DEBUG_TYPE "tailcallelim"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Constants.h"
58 #include "llvm/DerivedTypes.h"
59 #include "llvm/Function.h"
60 #include "llvm/Instructions.h"
61 #include "llvm/IntrinsicInst.h"
62 #include "llvm/Pass.h"
63 #include "llvm/Analysis/CaptureTracking.h"
64 #include "llvm/Analysis/InlineCost.h"
65 #include "llvm/Analysis/InstructionSimplify.h"
66 #include "llvm/Analysis/Loads.h"
67 #include "llvm/Support/CallSite.h"
68 #include "llvm/Support/CFG.h"
69 #include "llvm/Support/Debug.h"
70 #include "llvm/ADT/Statistic.h"
71 #include "llvm/ADT/STLExtras.h"
72 using namespace llvm;
73
74 STATISTIC(NumEliminated, "Number of tail calls removed");
75 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
76
77 namespace {
78   struct TailCallElim : public FunctionPass {
79     static char ID; // Pass identification, replacement for typeid
80     TailCallElim() : FunctionPass(ID) {
81       initializeTailCallElimPass(*PassRegistry::getPassRegistry());
82     }
83
84     virtual bool runOnFunction(Function &F);
85
86   private:
87     CallInst *FindTRECandidate(Instruction *I,
88                                bool CannotTailCallElimCallsMarkedTail);
89     bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
90                                     BasicBlock *&OldEntry,
91                                     bool &TailCallsAreMarkedTail,
92                                     SmallVector<PHINode*, 8> &ArgumentPHIs,
93                                     bool CannotTailCallElimCallsMarkedTail);
94     bool FoldReturnAndProcessPred(BasicBlock *BB,
95                                   ReturnInst *Ret, BasicBlock *&OldEntry,
96                                   bool &TailCallsAreMarkedTail,
97                                   SmallVector<PHINode*, 8> &ArgumentPHIs,
98                                   bool CannotTailCallElimCallsMarkedTail);
99     bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
100                                bool &TailCallsAreMarkedTail,
101                                SmallVector<PHINode*, 8> &ArgumentPHIs,
102                                bool CannotTailCallElimCallsMarkedTail);
103     bool CanMoveAboveCall(Instruction *I, CallInst *CI);
104     Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
105   };
106 }
107
108 char TailCallElim::ID = 0;
109 INITIALIZE_PASS(TailCallElim, "tailcallelim",
110                 "Tail Call Elimination", false, false)
111
112 // Public interface to the TailCallElimination pass
113 FunctionPass *llvm::createTailCallEliminationPass() {
114   return new TailCallElim();
115 }
116
117 /// AllocaMightEscapeToCalls - Return true if this alloca may be accessed by
118 /// callees of this function.  We only do very simple analysis right now, this
119 /// could be expanded in the future to use mod/ref information for particular
120 /// call sites if desired.
121 static bool AllocaMightEscapeToCalls(AllocaInst *AI) {
122   // FIXME: do simple 'address taken' analysis.
123   return true;
124 }
125
126 /// CheckForEscapingAllocas - Scan the specified basic block for alloca
127 /// instructions.  If it contains any that might be accessed by calls, return
128 /// true.
129 static bool CheckForEscapingAllocas(BasicBlock *BB,
130                                     bool &CannotTCETailMarkedCall) {
131   bool RetVal = false;
132   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
133     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
134       RetVal |= AllocaMightEscapeToCalls(AI);
135
136       // If this alloca is in the body of the function, or if it is a variable
137       // sized allocation, we cannot tail call eliminate calls marked 'tail'
138       // with this mechanism.
139       if (BB != &BB->getParent()->getEntryBlock() ||
140           !isa<ConstantInt>(AI->getArraySize()))
141         CannotTCETailMarkedCall = true;
142     }
143   return RetVal;
144 }
145
146 bool TailCallElim::runOnFunction(Function &F) {
147   // If this function is a varargs function, we won't be able to PHI the args
148   // right, so don't even try to convert it...
149   if (F.getFunctionType()->isVarArg()) return false;
150
151   BasicBlock *OldEntry = 0;
152   bool TailCallsAreMarkedTail = false;
153   SmallVector<PHINode*, 8> ArgumentPHIs;
154   bool MadeChange = false;
155   bool FunctionContainsEscapingAllocas = false;
156
157   // CannotTCETailMarkedCall - If true, we cannot perform TCE on tail calls
158   // marked with the 'tail' attribute, because doing so would cause the stack
159   // size to increase (real TCE would deallocate variable sized allocas, TCE
160   // doesn't).
161   bool CannotTCETailMarkedCall = false;
162
163   // Loop over the function, looking for any returning blocks, and keeping track
164   // of whether this function has any non-trivially used allocas.
165   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
166     if (FunctionContainsEscapingAllocas && CannotTCETailMarkedCall)
167       break;
168
169     FunctionContainsEscapingAllocas |=
170       CheckForEscapingAllocas(BB, CannotTCETailMarkedCall);
171   }
172   
173   /// FIXME: The code generator produces really bad code when an 'escaping
174   /// alloca' is changed from being a static alloca to being a dynamic alloca.
175   /// Until this is resolved, disable this transformation if that would ever
176   /// happen.  This bug is PR962.
177   if (FunctionContainsEscapingAllocas)
178     return false;
179
180   // Second pass, change any tail calls to loops.
181   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
182     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
183       bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
184                                           ArgumentPHIs,CannotTCETailMarkedCall);
185       if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
186         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
187                                           TailCallsAreMarkedTail, ArgumentPHIs,
188                                           CannotTCETailMarkedCall);
189       MadeChange |= Change;
190     }
191   }
192
193   // If we eliminated any tail recursions, it's possible that we inserted some
194   // silly PHI nodes which just merge an initial value (the incoming operand)
195   // with themselves.  Check to see if we did and clean up our mess if so.  This
196   // occurs when a function passes an argument straight through to its tail
197   // call.
198   if (!ArgumentPHIs.empty()) {
199     for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
200       PHINode *PN = ArgumentPHIs[i];
201
202       // If the PHI Node is a dynamic constant, replace it with the value it is.
203       if (Value *PNV = SimplifyInstruction(PN)) {
204         PN->replaceAllUsesWith(PNV);
205         PN->eraseFromParent();
206       }
207     }
208   }
209
210   // Finally, if this function contains no non-escaping allocas, mark all calls
211   // in the function as eligible for tail calls (there is no stack memory for
212   // them to access).
213   if (!FunctionContainsEscapingAllocas)
214     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
215       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
216         if (CallInst *CI = dyn_cast<CallInst>(I)) {
217           CI->setTailCall();
218           MadeChange = true;
219         }
220
221   return MadeChange;
222 }
223
224
225 /// CanMoveAboveCall - Return true if it is safe to move the specified
226 /// instruction from after the call to before the call, assuming that all
227 /// instructions between the call and this instruction are movable.
228 ///
229 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
230   // FIXME: We can move load/store/call/free instructions above the call if the
231   // call does not mod/ref the memory location being processed.
232   if (I->mayHaveSideEffects())  // This also handles volatile loads.
233     return false;
234   
235   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
236     // Loads may always be moved above calls without side effects.
237     if (CI->mayHaveSideEffects()) {
238       // Non-volatile loads may be moved above a call with side effects if it
239       // does not write to memory and the load provably won't trap.
240       // FIXME: Writes to memory only matter if they may alias the pointer
241       // being loaded from.
242       if (CI->mayWriteToMemory() ||
243           !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
244                                        L->getAlignment()))
245         return false;
246     }
247   }
248
249   // Otherwise, if this is a side-effect free instruction, check to make sure
250   // that it does not use the return value of the call.  If it doesn't use the
251   // return value of the call, it must only use things that are defined before
252   // the call, or movable instructions between the call and the instruction
253   // itself.
254   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
255     if (I->getOperand(i) == CI)
256       return false;
257   return true;
258 }
259
260 // isDynamicConstant - Return true if the specified value is the same when the
261 // return would exit as it was when the initial iteration of the recursive
262 // function was executed.
263 //
264 // We currently handle static constants and arguments that are not modified as
265 // part of the recursion.
266 //
267 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
268   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
269
270   // Check to see if this is an immutable argument, if so, the value
271   // will be available to initialize the accumulator.
272   if (Argument *Arg = dyn_cast<Argument>(V)) {
273     // Figure out which argument number this is...
274     unsigned ArgNo = 0;
275     Function *F = CI->getParent()->getParent();
276     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
277       ++ArgNo;
278
279     // If we are passing this argument into call as the corresponding
280     // argument operand, then the argument is dynamically constant.
281     // Otherwise, we cannot transform this function safely.
282     if (CI->getArgOperand(ArgNo) == Arg)
283       return true;
284   }
285
286   // Switch cases are always constant integers. If the value is being switched
287   // on and the return is only reachable from one of its cases, it's
288   // effectively constant.
289   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
290     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
291       if (SI->getCondition() == V)
292         return SI->getDefaultDest() != RI->getParent();
293
294   // Not a constant or immutable argument, we can't safely transform.
295   return false;
296 }
297
298 // getCommonReturnValue - Check to see if the function containing the specified
299 // tail call consistently returns the same runtime-constant value at all exit
300 // points except for IgnoreRI.  If so, return the returned value.
301 //
302 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
303   Function *F = CI->getParent()->getParent();
304   Value *ReturnedValue = 0;
305
306   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
307     ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
308     if (RI == 0 || RI == IgnoreRI) continue;
309
310     // We can only perform this transformation if the value returned is
311     // evaluatable at the start of the initial invocation of the function,
312     // instead of at the end of the evaluation.
313     //
314     Value *RetOp = RI->getOperand(0);
315     if (!isDynamicConstant(RetOp, CI, RI))
316       return 0;
317
318     if (ReturnedValue && RetOp != ReturnedValue)
319       return 0;     // Cannot transform if differing values are returned.
320     ReturnedValue = RetOp;
321   }
322   return ReturnedValue;
323 }
324
325 /// CanTransformAccumulatorRecursion - If the specified instruction can be
326 /// transformed using accumulator recursion elimination, return the constant
327 /// which is the start of the accumulator value.  Otherwise return null.
328 ///
329 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
330                                                       CallInst *CI) {
331   if (!I->isAssociative() || !I->isCommutative()) return 0;
332   assert(I->getNumOperands() == 2 &&
333          "Associative/commutative operations should have 2 args!");
334
335   // Exactly one operand should be the result of the call instruction.
336   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
337       (I->getOperand(0) != CI && I->getOperand(1) != CI))
338     return 0;
339
340   // The only user of this instruction we allow is a single return instruction.
341   if (!I->hasOneUse() || !isa<ReturnInst>(I->use_back()))
342     return 0;
343
344   // Ok, now we have to check all of the other return instructions in this
345   // function.  If they return non-constants or differing values, then we cannot
346   // transform the function safely.
347   return getCommonReturnValue(cast<ReturnInst>(I->use_back()), CI);
348 }
349
350 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
351   while (isa<DbgInfoIntrinsic>(I))
352     ++I;
353   return &*I;
354 }
355
356 CallInst*
357 TailCallElim::FindTRECandidate(Instruction *TI,
358                                bool CannotTailCallElimCallsMarkedTail) {
359   BasicBlock *BB = TI->getParent();
360   Function *F = BB->getParent();
361
362   if (&BB->front() == TI) // Make sure there is something before the terminator.
363     return 0;
364   
365   // Scan backwards from the return, checking to see if there is a tail call in
366   // this block.  If so, set CI to it.
367   CallInst *CI = 0;
368   BasicBlock::iterator BBI = TI;
369   while (true) {
370     CI = dyn_cast<CallInst>(BBI);
371     if (CI && CI->getCalledFunction() == F)
372       break;
373
374     if (BBI == BB->begin())
375       return 0;          // Didn't find a potential tail call.
376     --BBI;
377   }
378
379   // If this call is marked as a tail call, and if there are dynamic allocas in
380   // the function, we cannot perform this optimization.
381   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
382     return 0;
383
384   // As a special case, detect code like this:
385   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
386   // and disable this xform in this case, because the code generator will
387   // lower the call to fabs into inline code.
388   if (BB == &F->getEntryBlock() && 
389       FirstNonDbg(BB->front()) == CI &&
390       FirstNonDbg(llvm::next(BB->begin())) == TI &&
391       callIsSmall(F)) {
392     // A single-block function with just a call and a return. Check that
393     // the arguments match.
394     CallSite::arg_iterator I = CallSite(CI).arg_begin(),
395                            E = CallSite(CI).arg_end();
396     Function::arg_iterator FI = F->arg_begin(),
397                            FE = F->arg_end();
398     for (; I != E && FI != FE; ++I, ++FI)
399       if (*I != &*FI) break;
400     if (I == E && FI == FE)
401       return 0;
402   }
403
404   return CI;
405 }
406
407 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
408                                        BasicBlock *&OldEntry,
409                                        bool &TailCallsAreMarkedTail,
410                                        SmallVector<PHINode*, 8> &ArgumentPHIs,
411                                        bool CannotTailCallElimCallsMarkedTail) {
412   // If we are introducing accumulator recursion to eliminate operations after
413   // the call instruction that are both associative and commutative, the initial
414   // value for the accumulator is placed in this variable.  If this value is set
415   // then we actually perform accumulator recursion elimination instead of
416   // simple tail recursion elimination.  If the operation is an LLVM instruction
417   // (eg: "add") then it is recorded in AccumulatorRecursionInstr.  If not, then
418   // we are handling the case when the return instruction returns a constant C
419   // which is different to the constant returned by other return instructions
420   // (which is recorded in AccumulatorRecursionEliminationInitVal).  This is a
421   // special case of accumulator recursion, the operation being "return C".
422   Value *AccumulatorRecursionEliminationInitVal = 0;
423   Instruction *AccumulatorRecursionInstr = 0;
424
425   // Ok, we found a potential tail call.  We can currently only transform the
426   // tail call if all of the instructions between the call and the return are
427   // movable to above the call itself, leaving the call next to the return.
428   // Check that this is the case now.
429   BasicBlock::iterator BBI = CI;
430   for (++BBI; &*BBI != Ret; ++BBI) {
431     if (CanMoveAboveCall(BBI, CI)) continue;
432     
433     // If we can't move the instruction above the call, it might be because it
434     // is an associative and commutative operation that could be tranformed
435     // using accumulator recursion elimination.  Check to see if this is the
436     // case, and if so, remember the initial accumulator value for later.
437     if ((AccumulatorRecursionEliminationInitVal =
438                            CanTransformAccumulatorRecursion(BBI, CI))) {
439       // Yes, this is accumulator recursion.  Remember which instruction
440       // accumulates.
441       AccumulatorRecursionInstr = BBI;
442     } else {
443       return false;   // Otherwise, we cannot eliminate the tail recursion!
444     }
445   }
446
447   // We can only transform call/return pairs that either ignore the return value
448   // of the call and return void, ignore the value of the call and return a
449   // constant, return the value returned by the tail call, or that are being
450   // accumulator recursion variable eliminated.
451   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
452       !isa<UndefValue>(Ret->getReturnValue()) &&
453       AccumulatorRecursionEliminationInitVal == 0 &&
454       !getCommonReturnValue(0, CI)) {
455     // One case remains that we are able to handle: the current return
456     // instruction returns a constant, and all other return instructions
457     // return a different constant.
458     if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
459       return false; // Current return instruction does not return a constant.
460     // Check that all other return instructions return a common constant.  If
461     // so, record it in AccumulatorRecursionEliminationInitVal.
462     AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
463     if (!AccumulatorRecursionEliminationInitVal)
464       return false;
465   }
466
467   BasicBlock *BB = Ret->getParent();
468   Function *F = BB->getParent();
469
470   // OK! We can transform this tail call.  If this is the first one found,
471   // create the new entry block, allowing us to branch back to the old entry.
472   if (OldEntry == 0) {
473     OldEntry = &F->getEntryBlock();
474     BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
475     NewEntry->takeName(OldEntry);
476     OldEntry->setName("tailrecurse");
477     BranchInst::Create(OldEntry, NewEntry);
478
479     // If this tail call is marked 'tail' and if there are any allocas in the
480     // entry block, move them up to the new entry block.
481     TailCallsAreMarkedTail = CI->isTailCall();
482     if (TailCallsAreMarkedTail)
483       // Move all fixed sized allocas from OldEntry to NewEntry.
484       for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
485              NEBI = NewEntry->begin(); OEBI != E; )
486         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
487           if (isa<ConstantInt>(AI->getArraySize()))
488             AI->moveBefore(NEBI);
489
490     // Now that we have created a new block, which jumps to the entry
491     // block, insert a PHI node for each argument of the function.
492     // For now, we initialize each PHI to only have the real arguments
493     // which are passed in.
494     Instruction *InsertPos = OldEntry->begin();
495     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
496          I != E; ++I) {
497       PHINode *PN = PHINode::Create(I->getType(),
498                                     I->getName() + ".tr", InsertPos);
499       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
500       PN->addIncoming(I, NewEntry);
501       ArgumentPHIs.push_back(PN);
502     }
503   }
504
505   // If this function has self recursive calls in the tail position where some
506   // are marked tail and some are not, only transform one flavor or another.  We
507   // have to choose whether we move allocas in the entry block to the new entry
508   // block or not, so we can't make a good choice for both.  NOTE: We could do
509   // slightly better here in the case that the function has no entry block
510   // allocas.
511   if (TailCallsAreMarkedTail && !CI->isTailCall())
512     return false;
513
514   // Ok, now that we know we have a pseudo-entry block WITH all of the
515   // required PHI nodes, add entries into the PHI node for the actual
516   // parameters passed into the tail-recursive call.
517   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
518     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
519
520   // If we are introducing an accumulator variable to eliminate the recursion,
521   // do so now.  Note that we _know_ that no subsequent tail recursion
522   // eliminations will happen on this function because of the way the
523   // accumulator recursion predicate is set up.
524   //
525   if (AccumulatorRecursionEliminationInitVal) {
526     Instruction *AccRecInstr = AccumulatorRecursionInstr;
527     // Start by inserting a new PHI node for the accumulator.
528     PHINode *AccPN =
529       PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
530                       "accumulator.tr", OldEntry->begin());
531
532     // Loop over all of the predecessors of the tail recursion block.  For the
533     // real entry into the function we seed the PHI with the initial value,
534     // computed earlier.  For any other existing branches to this block (due to
535     // other tail recursions eliminated) the accumulator is not modified.
536     // Because we haven't added the branch in the current block to OldEntry yet,
537     // it will not show up as a predecessor.
538     for (pred_iterator PI = pred_begin(OldEntry), PE = pred_end(OldEntry);
539          PI != PE; ++PI) {
540       BasicBlock *P = *PI;
541       if (P == &F->getEntryBlock())
542         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
543       else
544         AccPN->addIncoming(AccPN, P);
545     }
546
547     if (AccRecInstr) {
548       // Add an incoming argument for the current block, which is computed by
549       // our associative and commutative accumulator instruction.
550       AccPN->addIncoming(AccRecInstr, BB);
551
552       // Next, rewrite the accumulator recursion instruction so that it does not
553       // use the result of the call anymore, instead, use the PHI node we just
554       // inserted.
555       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
556     } else {
557       // Add an incoming argument for the current block, which is just the
558       // constant returned by the current return instruction.
559       AccPN->addIncoming(Ret->getReturnValue(), BB);
560     }
561
562     // Finally, rewrite any return instructions in the program to return the PHI
563     // node instead of the "initval" that they do currently.  This loop will
564     // actually rewrite the return value we are destroying, but that's ok.
565     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
566       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
567         RI->setOperand(0, AccPN);
568     ++NumAccumAdded;
569   }
570
571   // Now that all of the PHI nodes are in place, remove the call and
572   // ret instructions, replacing them with an unconditional branch.
573   BranchInst::Create(OldEntry, Ret);
574   BB->getInstList().erase(Ret);  // Remove return.
575   BB->getInstList().erase(CI);   // Remove call.
576   ++NumEliminated;
577   return true;
578 }
579
580 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
581                                        ReturnInst *Ret, BasicBlock *&OldEntry,
582                                        bool &TailCallsAreMarkedTail,
583                                        SmallVector<PHINode*, 8> &ArgumentPHIs,
584                                        bool CannotTailCallElimCallsMarkedTail) {
585   bool Change = false;
586
587   // If the return block contains nothing but the return and PHI's,
588   // there might be an opportunity to duplicate the return in its
589   // predecessors and perform TRC there. Look for predecessors that end
590   // in unconditional branch and recursive call(s).
591   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);
592        PI != E; ++PI) {
593     BasicBlock *Pred = *PI;
594     TerminatorInst *PTI = Pred->getTerminator();
595     if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
596       CallInst *CI = 0;
597       if (BI->isUnconditional() &&
598           (CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail))) {
599         DEBUG(dbgs() << "FOLDING: " << *BB
600               << "INTO UNCOND BRANCH PRED: " << *Pred);
601         EliminateRecursiveTailCall(CI,
602                                    FoldReturnIntoUncondBranch(Ret, BB, Pred),
603                                    OldEntry, TailCallsAreMarkedTail, ArgumentPHIs,
604                                    CannotTailCallElimCallsMarkedTail);
605         Change = true;
606       }
607     }
608   }
609
610   return Change;
611 }
612
613 bool TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
614                                          bool &TailCallsAreMarkedTail,
615                                          SmallVector<PHINode*, 8> &ArgumentPHIs,
616                                        bool CannotTailCallElimCallsMarkedTail) {
617   CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
618   if (!CI)
619     return false;
620
621   return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
622                                     ArgumentPHIs,
623                                     CannotTailCallElimCallsMarkedTail);
624 }