LLVM API Documentation

TailRecursionElimination.cpp
Go to the documentation of this file.
00001 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file transforms calls of the current function (self recursion) followed
00011 // by a return instruction with a branch to the entry of the function, creating
00012 // a loop.  This pass also implements the following extensions to the basic
00013 // algorithm:
00014 //
00015 //  1. Trivial instructions between the call and return do not prevent the
00016 //     transformation from taking place, though currently the analysis cannot
00017 //     support moving any really useful instructions (only dead ones).
00018 //  2. This pass transforms functions that are prevented from being tail
00019 //     recursive by an associative and commutative expression to use an
00020 //     accumulator variable, thus compiling the typical naive factorial or
00021 //     'fib' implementation into efficient code.
00022 //  3. TRE is performed if the function returns void, if the return
00023 //     returns the result returned by the call, or if the function returns a
00024 //     run-time constant on all exits from the function.  It is possible, though
00025 //     unlikely, that the return returns something else (like constant 0), and
00026 //     can still be TRE'd.  It can be TRE'd if ALL OTHER return instructions in
00027 //     the function return the exact same value.
00028 //  4. If it can prove that callees do not access their caller stack frame,
00029 //     they are marked as eligible for tail call elimination (by the code
00030 //     generator).
00031 //
00032 // There are several improvements that could be made:
00033 //
00034 //  1. If the function has any alloca instructions, these instructions will be
00035 //     moved out of the entry block of the function, causing them to be
00036 //     evaluated each time through the tail recursion.  Safely keeping allocas
00037 //     in the entry block requires analysis to proves that the tail-called
00038 //     function does not read or write the stack object.
00039 //  2. Tail recursion is only performed if the call immediately precedes the
00040 //     return instruction.  It's possible that there could be a jump between
00041 //     the call and the return.
00042 //  3. There can be intervening operations between the call and the return that
00043 //     prevent the TRE from occurring.  For example, there could be GEP's and
00044 //     stores to memory that will not be read or written by the call.  This
00045 //     requires some substantial analysis (such as with DSA) to prove safe to
00046 //     move ahead of the call, but doing so could allow many more TREs to be
00047 //     performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
00048 //  4. The algorithm we use to detect if callees access their caller stack
00049 //     frames is very primitive.
00050 //
00051 //===----------------------------------------------------------------------===//
00052 
00053 #include "llvm/Transforms/Scalar.h"
00054 #include "llvm/ADT/STLExtras.h"
00055 #include "llvm/ADT/SmallPtrSet.h"
00056 #include "llvm/ADT/Statistic.h"
00057 #include "llvm/Analysis/CaptureTracking.h"
00058 #include "llvm/Analysis/InlineCost.h"
00059 #include "llvm/Analysis/InstructionSimplify.h"
00060 #include "llvm/Analysis/Loads.h"
00061 #include "llvm/Analysis/TargetTransformInfo.h"
00062 #include "llvm/IR/CFG.h"
00063 #include "llvm/IR/CallSite.h"
00064 #include "llvm/IR/Constants.h"
00065 #include "llvm/IR/DerivedTypes.h"
00066 #include "llvm/IR/Function.h"
00067 #include "llvm/IR/Instructions.h"
00068 #include "llvm/IR/IntrinsicInst.h"
00069 #include "llvm/IR/Module.h"
00070 #include "llvm/IR/ValueHandle.h"
00071 #include "llvm/Pass.h"
00072 #include "llvm/Support/Debug.h"
00073 #include "llvm/Support/raw_ostream.h"
00074 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00075 #include "llvm/Transforms/Utils/Local.h"
00076 using namespace llvm;
00077 
00078 #define DEBUG_TYPE "tailcallelim"
00079 
00080 STATISTIC(NumEliminated, "Number of tail calls removed");
00081 STATISTIC(NumRetDuped,   "Number of return duplicated");
00082 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
00083 
00084 namespace {
00085   struct TailCallElim : public FunctionPass {
00086     const TargetTransformInfo *TTI;
00087 
00088     static char ID; // Pass identification, replacement for typeid
00089     TailCallElim() : FunctionPass(ID) {
00090       initializeTailCallElimPass(*PassRegistry::getPassRegistry());
00091     }
00092 
00093     void getAnalysisUsage(AnalysisUsage &AU) const override;
00094 
00095     bool runOnFunction(Function &F) override;
00096 
00097   private:
00098     CallInst *FindTRECandidate(Instruction *I,
00099                                bool CannotTailCallElimCallsMarkedTail);
00100     bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00101                                     BasicBlock *&OldEntry,
00102                                     bool &TailCallsAreMarkedTail,
00103                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00104                                     bool CannotTailCallElimCallsMarkedTail);
00105     bool FoldReturnAndProcessPred(BasicBlock *BB,
00106                                   ReturnInst *Ret, BasicBlock *&OldEntry,
00107                                   bool &TailCallsAreMarkedTail,
00108                                   SmallVectorImpl<PHINode *> &ArgumentPHIs,
00109                                   bool CannotTailCallElimCallsMarkedTail);
00110     bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
00111                                bool &TailCallsAreMarkedTail,
00112                                SmallVectorImpl<PHINode *> &ArgumentPHIs,
00113                                bool CannotTailCallElimCallsMarkedTail);
00114     bool CanMoveAboveCall(Instruction *I, CallInst *CI);
00115     Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
00116   };
00117 }
00118 
00119 char TailCallElim::ID = 0;
00120 INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim",
00121                       "Tail Call Elimination", false, false)
00122 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
00123 INITIALIZE_PASS_END(TailCallElim, "tailcallelim",
00124                     "Tail Call Elimination", false, false)
00125 
00126 // Public interface to the TailCallElimination pass
00127 FunctionPass *llvm::createTailCallEliminationPass() {
00128   return new TailCallElim();
00129 }
00130 
00131 void TailCallElim::getAnalysisUsage(AnalysisUsage &AU) const {
00132   AU.addRequired<TargetTransformInfo>();
00133 }
00134 
00135 /// CanTRE - Scan the specified basic block for alloca instructions.
00136 /// If it contains any that are variable-sized or not in the entry block,
00137 /// returns false.
00138 static bool CanTRE(AllocaInst *AI) {
00139   // Because of PR962, we don't TRE allocas outside the entry block.
00140 
00141   // If this alloca is in the body of the function, or if it is a variable
00142   // sized allocation, we cannot tail call eliminate calls marked 'tail'
00143   // with this mechanism.
00144   BasicBlock *BB = AI->getParent();
00145   return BB == &BB->getParent()->getEntryBlock() &&
00146          isa<ConstantInt>(AI->getArraySize());
00147 }
00148 
00149 namespace {
00150 struct AllocaCaptureTracker : public CaptureTracker {
00151   AllocaCaptureTracker() : Captured(false) {}
00152 
00153   void tooManyUses() override { Captured = true; }
00154 
00155   bool shouldExplore(const Use *U) override {
00156     Value *V = U->getUser();
00157     if (isa<CallInst>(V) || isa<InvokeInst>(V))
00158       UsesAlloca.insert(V);
00159     return true;
00160   }
00161 
00162   bool captured(const Use *U) override {
00163     if (isa<ReturnInst>(U->getUser()))
00164       return false;
00165     Captured = true;
00166     return true;
00167   }
00168 
00169   bool Captured;
00170   SmallPtrSet<const Value *, 16> UsesAlloca;
00171 };
00172 } // end anonymous namespace
00173 
00174 bool TailCallElim::runOnFunction(Function &F) {
00175   if (skipOptnoneFunction(F))
00176     return false;
00177 
00178   // If this function is a varargs function, we won't be able to PHI the args
00179   // right, so don't even try to convert it...
00180   if (F.getFunctionType()->isVarArg()) return false;
00181 
00182   TTI = &getAnalysis<TargetTransformInfo>();
00183   BasicBlock *OldEntry = 0;
00184   bool TailCallsAreMarkedTail = false;
00185   SmallVector<PHINode*, 8> ArgumentPHIs;
00186   bool MadeChange = false;
00187 
00188   // CanTRETailMarkedCall - If false, we cannot perform TRE on tail calls
00189   // marked with the 'tail' attribute, because doing so would cause the stack
00190   // size to increase (real TRE would deallocate variable sized allocas, TRE
00191   // doesn't).
00192   bool CanTRETailMarkedCall = true;
00193 
00194   // Find calls that can be marked tail.
00195   AllocaCaptureTracker ACT;
00196   for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB) {
00197     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00198       if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
00199         CanTRETailMarkedCall &= CanTRE(AI);
00200         PointerMayBeCaptured(AI, &ACT);
00201         // If any allocas are captured, exit.
00202         if (ACT.Captured)
00203           return false;
00204       }
00205     }
00206   }
00207 
00208   // If any byval or inalloca args are captured, exit. They are also allocated
00209   // in our stack frame.
00210   for (Argument &Arg : F.args()) {
00211     if (Arg.hasByValOrInAllocaAttr())
00212       PointerMayBeCaptured(&Arg, &ACT);
00213     if (ACT.Captured)
00214       return false;
00215   }
00216 
00217   // Second pass, change any tail recursive calls to loops.
00218   //
00219   // FIXME: The code generator produces really bad code when an 'escaping
00220   // alloca' is changed from being a static alloca to being a dynamic alloca.
00221   // Until this is resolved, disable this transformation if that would ever
00222   // happen.  This bug is PR962.
00223   if (ACT.UsesAlloca.empty()) {
00224     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00225       if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
00226         bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
00227                                             ArgumentPHIs, !CanTRETailMarkedCall);
00228         if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
00229           Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
00230                                             TailCallsAreMarkedTail, ArgumentPHIs,
00231                                             !CanTRETailMarkedCall);
00232         MadeChange |= Change;
00233       }
00234     }
00235   }
00236 
00237   // If we eliminated any tail recursions, it's possible that we inserted some
00238   // silly PHI nodes which just merge an initial value (the incoming operand)
00239   // with themselves.  Check to see if we did and clean up our mess if so.  This
00240   // occurs when a function passes an argument straight through to its tail
00241   // call.
00242   if (!ArgumentPHIs.empty()) {
00243     for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
00244       PHINode *PN = ArgumentPHIs[i];
00245 
00246       // If the PHI Node is a dynamic constant, replace it with the value it is.
00247       if (Value *PNV = SimplifyInstruction(PN)) {
00248         PN->replaceAllUsesWith(PNV);
00249         PN->eraseFromParent();
00250       }
00251     }
00252   }
00253 
00254   // At this point, we know that the function does not have any captured
00255   // allocas. If additionally the function does not call setjmp, mark all calls
00256   // in the function that do not access stack memory with the tail keyword. This
00257   // implies ensuring that there does not exist any path from a call that takes
00258   // in an alloca but does not capture it and the call which we wish to mark
00259   // with "tail".
00260   if (!F.callsFunctionThatReturnsTwice()) {
00261     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00262       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00263         if (CallInst *CI = dyn_cast<CallInst>(I)) {
00264           if (!ACT.UsesAlloca.count(CI)) {
00265             CI->setTailCall();
00266             MadeChange = true;
00267           }
00268         }
00269       }
00270     }
00271   }
00272 
00273   return MadeChange;
00274 }
00275 
00276 
00277 /// CanMoveAboveCall - Return true if it is safe to move the specified
00278 /// instruction from after the call to before the call, assuming that all
00279 /// instructions between the call and this instruction are movable.
00280 ///
00281 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
00282   // FIXME: We can move load/store/call/free instructions above the call if the
00283   // call does not mod/ref the memory location being processed.
00284   if (I->mayHaveSideEffects())  // This also handles volatile loads.
00285     return false;
00286 
00287   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00288     // Loads may always be moved above calls without side effects.
00289     if (CI->mayHaveSideEffects()) {
00290       // Non-volatile loads may be moved above a call with side effects if it
00291       // does not write to memory and the load provably won't trap.
00292       // FIXME: Writes to memory only matter if they may alias the pointer
00293       // being loaded from.
00294       if (CI->mayWriteToMemory() ||
00295           !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
00296                                        L->getAlignment()))
00297         return false;
00298     }
00299   }
00300 
00301   // Otherwise, if this is a side-effect free instruction, check to make sure
00302   // that it does not use the return value of the call.  If it doesn't use the
00303   // return value of the call, it must only use things that are defined before
00304   // the call, or movable instructions between the call and the instruction
00305   // itself.
00306   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00307     if (I->getOperand(i) == CI)
00308       return false;
00309   return true;
00310 }
00311 
00312 // isDynamicConstant - Return true if the specified value is the same when the
00313 // return would exit as it was when the initial iteration of the recursive
00314 // function was executed.
00315 //
00316 // We currently handle static constants and arguments that are not modified as
00317 // part of the recursion.
00318 //
00319 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
00320   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
00321 
00322   // Check to see if this is an immutable argument, if so, the value
00323   // will be available to initialize the accumulator.
00324   if (Argument *Arg = dyn_cast<Argument>(V)) {
00325     // Figure out which argument number this is...
00326     unsigned ArgNo = 0;
00327     Function *F = CI->getParent()->getParent();
00328     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
00329       ++ArgNo;
00330 
00331     // If we are passing this argument into call as the corresponding
00332     // argument operand, then the argument is dynamically constant.
00333     // Otherwise, we cannot transform this function safely.
00334     if (CI->getArgOperand(ArgNo) == Arg)
00335       return true;
00336   }
00337 
00338   // Switch cases are always constant integers. If the value is being switched
00339   // on and the return is only reachable from one of its cases, it's
00340   // effectively constant.
00341   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
00342     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
00343       if (SI->getCondition() == V)
00344         return SI->getDefaultDest() != RI->getParent();
00345 
00346   // Not a constant or immutable argument, we can't safely transform.
00347   return false;
00348 }
00349 
00350 // getCommonReturnValue - Check to see if the function containing the specified
00351 // tail call consistently returns the same runtime-constant value at all exit
00352 // points except for IgnoreRI.  If so, return the returned value.
00353 //
00354 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
00355   Function *F = CI->getParent()->getParent();
00356   Value *ReturnedValue = 0;
00357 
00358   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
00359     ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
00360     if (RI == 0 || RI == IgnoreRI) continue;
00361 
00362     // We can only perform this transformation if the value returned is
00363     // evaluatable at the start of the initial invocation of the function,
00364     // instead of at the end of the evaluation.
00365     //
00366     Value *RetOp = RI->getOperand(0);
00367     if (!isDynamicConstant(RetOp, CI, RI))
00368       return 0;
00369 
00370     if (ReturnedValue && RetOp != ReturnedValue)
00371       return 0;     // Cannot transform if differing values are returned.
00372     ReturnedValue = RetOp;
00373   }
00374   return ReturnedValue;
00375 }
00376 
00377 /// CanTransformAccumulatorRecursion - If the specified instruction can be
00378 /// transformed using accumulator recursion elimination, return the constant
00379 /// which is the start of the accumulator value.  Otherwise return null.
00380 ///
00381 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
00382                                                       CallInst *CI) {
00383   if (!I->isAssociative() || !I->isCommutative()) return 0;
00384   assert(I->getNumOperands() == 2 &&
00385          "Associative/commutative operations should have 2 args!");
00386 
00387   // Exactly one operand should be the result of the call instruction.
00388   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
00389       (I->getOperand(0) != CI && I->getOperand(1) != CI))
00390     return 0;
00391 
00392   // The only user of this instruction we allow is a single return instruction.
00393   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
00394     return 0;
00395 
00396   // Ok, now we have to check all of the other return instructions in this
00397   // function.  If they return non-constants or differing values, then we cannot
00398   // transform the function safely.
00399   return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
00400 }
00401 
00402 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
00403   while (isa<DbgInfoIntrinsic>(I))
00404     ++I;
00405   return &*I;
00406 }
00407 
00408 CallInst*
00409 TailCallElim::FindTRECandidate(Instruction *TI,
00410                                bool CannotTailCallElimCallsMarkedTail) {
00411   BasicBlock *BB = TI->getParent();
00412   Function *F = BB->getParent();
00413 
00414   if (&BB->front() == TI) // Make sure there is something before the terminator.
00415     return 0;
00416 
00417   // Scan backwards from the return, checking to see if there is a tail call in
00418   // this block.  If so, set CI to it.
00419   CallInst *CI = 0;
00420   BasicBlock::iterator BBI = TI;
00421   while (true) {
00422     CI = dyn_cast<CallInst>(BBI);
00423     if (CI && CI->getCalledFunction() == F)
00424       break;
00425 
00426     if (BBI == BB->begin())
00427       return 0;          // Didn't find a potential tail call.
00428     --BBI;
00429   }
00430 
00431   // If this call is marked as a tail call, and if there are dynamic allocas in
00432   // the function, we cannot perform this optimization.
00433   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
00434     return 0;
00435 
00436   // As a special case, detect code like this:
00437   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
00438   // and disable this xform in this case, because the code generator will
00439   // lower the call to fabs into inline code.
00440   if (BB == &F->getEntryBlock() &&
00441       FirstNonDbg(BB->front()) == CI &&
00442       FirstNonDbg(std::next(BB->begin())) == TI &&
00443       CI->getCalledFunction() &&
00444       !TTI->isLoweredToCall(CI->getCalledFunction())) {
00445     // A single-block function with just a call and a return. Check that
00446     // the arguments match.
00447     CallSite::arg_iterator I = CallSite(CI).arg_begin(),
00448                            E = CallSite(CI).arg_end();
00449     Function::arg_iterator FI = F->arg_begin(),
00450                            FE = F->arg_end();
00451     for (; I != E && FI != FE; ++I, ++FI)
00452       if (*I != &*FI) break;
00453     if (I == E && FI == FE)
00454       return 0;
00455   }
00456 
00457   return CI;
00458 }
00459 
00460 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00461                                        BasicBlock *&OldEntry,
00462                                        bool &TailCallsAreMarkedTail,
00463                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00464                                        bool CannotTailCallElimCallsMarkedTail) {
00465   // If we are introducing accumulator recursion to eliminate operations after
00466   // the call instruction that are both associative and commutative, the initial
00467   // value for the accumulator is placed in this variable.  If this value is set
00468   // then we actually perform accumulator recursion elimination instead of
00469   // simple tail recursion elimination.  If the operation is an LLVM instruction
00470   // (eg: "add") then it is recorded in AccumulatorRecursionInstr.  If not, then
00471   // we are handling the case when the return instruction returns a constant C
00472   // which is different to the constant returned by other return instructions
00473   // (which is recorded in AccumulatorRecursionEliminationInitVal).  This is a
00474   // special case of accumulator recursion, the operation being "return C".
00475   Value *AccumulatorRecursionEliminationInitVal = 0;
00476   Instruction *AccumulatorRecursionInstr = 0;
00477 
00478   // Ok, we found a potential tail call.  We can currently only transform the
00479   // tail call if all of the instructions between the call and the return are
00480   // movable to above the call itself, leaving the call next to the return.
00481   // Check that this is the case now.
00482   BasicBlock::iterator BBI = CI;
00483   for (++BBI; &*BBI != Ret; ++BBI) {
00484     if (CanMoveAboveCall(BBI, CI)) continue;
00485 
00486     // If we can't move the instruction above the call, it might be because it
00487     // is an associative and commutative operation that could be transformed
00488     // using accumulator recursion elimination.  Check to see if this is the
00489     // case, and if so, remember the initial accumulator value for later.
00490     if ((AccumulatorRecursionEliminationInitVal =
00491                            CanTransformAccumulatorRecursion(BBI, CI))) {
00492       // Yes, this is accumulator recursion.  Remember which instruction
00493       // accumulates.
00494       AccumulatorRecursionInstr = BBI;
00495     } else {
00496       return false;   // Otherwise, we cannot eliminate the tail recursion!
00497     }
00498   }
00499 
00500   // We can only transform call/return pairs that either ignore the return value
00501   // of the call and return void, ignore the value of the call and return a
00502   // constant, return the value returned by the tail call, or that are being
00503   // accumulator recursion variable eliminated.
00504   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
00505       !isa<UndefValue>(Ret->getReturnValue()) &&
00506       AccumulatorRecursionEliminationInitVal == 0 &&
00507       !getCommonReturnValue(0, CI)) {
00508     // One case remains that we are able to handle: the current return
00509     // instruction returns a constant, and all other return instructions
00510     // return a different constant.
00511     if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
00512       return false; // Current return instruction does not return a constant.
00513     // Check that all other return instructions return a common constant.  If
00514     // so, record it in AccumulatorRecursionEliminationInitVal.
00515     AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
00516     if (!AccumulatorRecursionEliminationInitVal)
00517       return false;
00518   }
00519 
00520   BasicBlock *BB = Ret->getParent();
00521   Function *F = BB->getParent();
00522 
00523   // OK! We can transform this tail call.  If this is the first one found,
00524   // create the new entry block, allowing us to branch back to the old entry.
00525   if (OldEntry == 0) {
00526     OldEntry = &F->getEntryBlock();
00527     BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
00528     NewEntry->takeName(OldEntry);
00529     OldEntry->setName("tailrecurse");
00530     BranchInst::Create(OldEntry, NewEntry);
00531 
00532     // If this tail call is marked 'tail' and if there are any allocas in the
00533     // entry block, move them up to the new entry block.
00534     TailCallsAreMarkedTail = CI->isTailCall();
00535     if (TailCallsAreMarkedTail)
00536       // Move all fixed sized allocas from OldEntry to NewEntry.
00537       for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
00538              NEBI = NewEntry->begin(); OEBI != E; )
00539         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
00540           if (isa<ConstantInt>(AI->getArraySize()))
00541             AI->moveBefore(NEBI);
00542 
00543     // Now that we have created a new block, which jumps to the entry
00544     // block, insert a PHI node for each argument of the function.
00545     // For now, we initialize each PHI to only have the real arguments
00546     // which are passed in.
00547     Instruction *InsertPos = OldEntry->begin();
00548     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00549          I != E; ++I) {
00550       PHINode *PN = PHINode::Create(I->getType(), 2,
00551                                     I->getName() + ".tr", InsertPos);
00552       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
00553       PN->addIncoming(I, NewEntry);
00554       ArgumentPHIs.push_back(PN);
00555     }
00556   }
00557 
00558   // If this function has self recursive calls in the tail position where some
00559   // are marked tail and some are not, only transform one flavor or another.  We
00560   // have to choose whether we move allocas in the entry block to the new entry
00561   // block or not, so we can't make a good choice for both.  NOTE: We could do
00562   // slightly better here in the case that the function has no entry block
00563   // allocas.
00564   if (TailCallsAreMarkedTail && !CI->isTailCall())
00565     return false;
00566 
00567   // Ok, now that we know we have a pseudo-entry block WITH all of the
00568   // required PHI nodes, add entries into the PHI node for the actual
00569   // parameters passed into the tail-recursive call.
00570   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
00571     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
00572 
00573   // If we are introducing an accumulator variable to eliminate the recursion,
00574   // do so now.  Note that we _know_ that no subsequent tail recursion
00575   // eliminations will happen on this function because of the way the
00576   // accumulator recursion predicate is set up.
00577   //
00578   if (AccumulatorRecursionEliminationInitVal) {
00579     Instruction *AccRecInstr = AccumulatorRecursionInstr;
00580     // Start by inserting a new PHI node for the accumulator.
00581     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
00582     PHINode *AccPN =
00583       PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
00584                       std::distance(PB, PE) + 1,
00585                       "accumulator.tr", OldEntry->begin());
00586 
00587     // Loop over all of the predecessors of the tail recursion block.  For the
00588     // real entry into the function we seed the PHI with the initial value,
00589     // computed earlier.  For any other existing branches to this block (due to
00590     // other tail recursions eliminated) the accumulator is not modified.
00591     // Because we haven't added the branch in the current block to OldEntry yet,
00592     // it will not show up as a predecessor.
00593     for (pred_iterator PI = PB; PI != PE; ++PI) {
00594       BasicBlock *P = *PI;
00595       if (P == &F->getEntryBlock())
00596         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
00597       else
00598         AccPN->addIncoming(AccPN, P);
00599     }
00600 
00601     if (AccRecInstr) {
00602       // Add an incoming argument for the current block, which is computed by
00603       // our associative and commutative accumulator instruction.
00604       AccPN->addIncoming(AccRecInstr, BB);
00605 
00606       // Next, rewrite the accumulator recursion instruction so that it does not
00607       // use the result of the call anymore, instead, use the PHI node we just
00608       // inserted.
00609       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
00610     } else {
00611       // Add an incoming argument for the current block, which is just the
00612       // constant returned by the current return instruction.
00613       AccPN->addIncoming(Ret->getReturnValue(), BB);
00614     }
00615 
00616     // Finally, rewrite any return instructions in the program to return the PHI
00617     // node instead of the "initval" that they do currently.  This loop will
00618     // actually rewrite the return value we are destroying, but that's ok.
00619     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00620       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00621         RI->setOperand(0, AccPN);
00622     ++NumAccumAdded;
00623   }
00624 
00625   // Now that all of the PHI nodes are in place, remove the call and
00626   // ret instructions, replacing them with an unconditional branch.
00627   BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
00628   NewBI->setDebugLoc(CI->getDebugLoc());
00629 
00630   BB->getInstList().erase(Ret);  // Remove return.
00631   BB->getInstList().erase(CI);   // Remove call.
00632   ++NumEliminated;
00633   return true;
00634 }
00635 
00636 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
00637                                        ReturnInst *Ret, BasicBlock *&OldEntry,
00638                                        bool &TailCallsAreMarkedTail,
00639                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00640                                        bool CannotTailCallElimCallsMarkedTail) {
00641   bool Change = false;
00642 
00643   // If the return block contains nothing but the return and PHI's,
00644   // there might be an opportunity to duplicate the return in its
00645   // predecessors and perform TRC there. Look for predecessors that end
00646   // in unconditional branch and recursive call(s).
00647   SmallVector<BranchInst*, 8> UncondBranchPreds;
00648   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00649     BasicBlock *Pred = *PI;
00650     TerminatorInst *PTI = Pred->getTerminator();
00651     if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
00652       if (BI->isUnconditional())
00653         UncondBranchPreds.push_back(BI);
00654   }
00655 
00656   while (!UncondBranchPreds.empty()) {
00657     BranchInst *BI = UncondBranchPreds.pop_back_val();
00658     BasicBlock *Pred = BI->getParent();
00659     if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
00660       DEBUG(dbgs() << "FOLDING: " << *BB
00661             << "INTO UNCOND BRANCH PRED: " << *Pred);
00662       EliminateRecursiveTailCall(CI, FoldReturnIntoUncondBranch(Ret, BB, Pred),
00663                                  OldEntry, TailCallsAreMarkedTail, ArgumentPHIs,
00664                                  CannotTailCallElimCallsMarkedTail);
00665       ++NumRetDuped;
00666       Change = true;
00667     }
00668   }
00669 
00670   return Change;
00671 }
00672 
00673 bool
00674 TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
00675                                     bool &TailCallsAreMarkedTail,
00676                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00677                                     bool CannotTailCallElimCallsMarkedTail) {
00678   CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
00679   if (!CI)
00680     return false;
00681 
00682   return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
00683                                     ArgumentPHIs,
00684                                     CannotTailCallElimCallsMarkedTail);
00685 }