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/CFG.h"
00059 #include "llvm/Analysis/InlineCost.h"
00060 #include "llvm/Analysis/InstructionSimplify.h"
00061 #include "llvm/Analysis/Loads.h"
00062 #include "llvm/Analysis/TargetTransformInfo.h"
00063 #include "llvm/IR/CFG.h"
00064 #include "llvm/IR/CallSite.h"
00065 #include "llvm/IR/Constants.h"
00066 #include "llvm/IR/DataLayout.h"
00067 #include "llvm/IR/DerivedTypes.h"
00068 #include "llvm/IR/DiagnosticInfo.h"
00069 #include "llvm/IR/Function.h"
00070 #include "llvm/IR/Instructions.h"
00071 #include "llvm/IR/IntrinsicInst.h"
00072 #include "llvm/IR/Module.h"
00073 #include "llvm/IR/ValueHandle.h"
00074 #include "llvm/Pass.h"
00075 #include "llvm/Support/Debug.h"
00076 #include "llvm/Support/raw_ostream.h"
00077 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00078 #include "llvm/Transforms/Utils/Local.h"
00079 using namespace llvm;
00080 
00081 #define DEBUG_TYPE "tailcallelim"
00082 
00083 STATISTIC(NumEliminated, "Number of tail calls removed");
00084 STATISTIC(NumRetDuped,   "Number of return duplicated");
00085 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
00086 
00087 namespace {
00088   struct TailCallElim : public FunctionPass {
00089     const TargetTransformInfo *TTI;
00090     const DataLayout *DL;
00091 
00092     static char ID; // Pass identification, replacement for typeid
00093     TailCallElim() : FunctionPass(ID) {
00094       initializeTailCallElimPass(*PassRegistry::getPassRegistry());
00095     }
00096 
00097     void getAnalysisUsage(AnalysisUsage &AU) const override;
00098 
00099     bool runOnFunction(Function &F) override;
00100 
00101   private:
00102     bool runTRE(Function &F);
00103     bool markTails(Function &F, bool &AllCallsAreTailCalls);
00104 
00105     CallInst *FindTRECandidate(Instruction *I,
00106                                bool CannotTailCallElimCallsMarkedTail);
00107     bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00108                                     BasicBlock *&OldEntry,
00109                                     bool &TailCallsAreMarkedTail,
00110                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00111                                     bool CannotTailCallElimCallsMarkedTail);
00112     bool FoldReturnAndProcessPred(BasicBlock *BB,
00113                                   ReturnInst *Ret, BasicBlock *&OldEntry,
00114                                   bool &TailCallsAreMarkedTail,
00115                                   SmallVectorImpl<PHINode *> &ArgumentPHIs,
00116                                   bool CannotTailCallElimCallsMarkedTail);
00117     bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
00118                                bool &TailCallsAreMarkedTail,
00119                                SmallVectorImpl<PHINode *> &ArgumentPHIs,
00120                                bool CannotTailCallElimCallsMarkedTail);
00121     bool CanMoveAboveCall(Instruction *I, CallInst *CI);
00122     Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
00123   };
00124 }
00125 
00126 char TailCallElim::ID = 0;
00127 INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim",
00128                       "Tail Call Elimination", false, false)
00129 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
00130 INITIALIZE_PASS_END(TailCallElim, "tailcallelim",
00131                     "Tail Call Elimination", false, false)
00132 
00133 // Public interface to the TailCallElimination pass
00134 FunctionPass *llvm::createTailCallEliminationPass() {
00135   return new TailCallElim();
00136 }
00137 
00138 void TailCallElim::getAnalysisUsage(AnalysisUsage &AU) const {
00139   AU.addRequired<TargetTransformInfo>();
00140 }
00141 
00142 /// \brief Scan the specified function for alloca instructions.
00143 /// If it contains any dynamic allocas, returns false.
00144 static bool CanTRE(Function &F) {
00145   // Because of PR962, we don't TRE dynamic allocas.
00146   for (auto &BB : F) {
00147     for (auto &I : BB) {
00148       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
00149         if (!AI->isStaticAlloca())
00150           return false;
00151       }
00152     }
00153   }
00154 
00155   return true;
00156 }
00157 
00158 bool TailCallElim::runOnFunction(Function &F) {
00159   if (skipOptnoneFunction(F))
00160     return false;
00161 
00162   DL = F.getParent()->getDataLayout();
00163 
00164   bool AllCallsAreTailCalls = false;
00165   bool Modified = markTails(F, AllCallsAreTailCalls);
00166   if (AllCallsAreTailCalls)
00167     Modified |= runTRE(F);
00168   return Modified;
00169 }
00170 
00171 namespace {
00172 struct AllocaDerivedValueTracker {
00173   // Start at a root value and walk its use-def chain to mark calls that use the
00174   // value or a derived value in AllocaUsers, and places where it may escape in
00175   // EscapePoints.
00176   void walk(Value *Root) {
00177     SmallVector<Use *, 32> Worklist;
00178     SmallPtrSet<Use *, 32> Visited;
00179 
00180     auto AddUsesToWorklist = [&](Value *V) {
00181       for (auto &U : V->uses()) {
00182         if (!Visited.insert(&U))
00183           continue;
00184         Worklist.push_back(&U);
00185       }
00186     };
00187 
00188     AddUsesToWorklist(Root);
00189 
00190     while (!Worklist.empty()) {
00191       Use *U = Worklist.pop_back_val();
00192       Instruction *I = cast<Instruction>(U->getUser());
00193 
00194       switch (I->getOpcode()) {
00195       case Instruction::Call:
00196       case Instruction::Invoke: {
00197         CallSite CS(I);
00198         bool IsNocapture = !CS.isCallee(U) &&
00199                            CS.doesNotCapture(CS.getArgumentNo(U));
00200         callUsesLocalStack(CS, IsNocapture);
00201         if (IsNocapture) {
00202           // If the alloca-derived argument is passed in as nocapture, then it
00203           // can't propagate to the call's return. That would be capturing.
00204           continue;
00205         }
00206         break;
00207       }
00208       case Instruction::Load: {
00209         // The result of a load is not alloca-derived (unless an alloca has
00210         // otherwise escaped, but this is a local analysis).
00211         continue;
00212       }
00213       case Instruction::Store: {
00214         if (U->getOperandNo() == 0)
00215           EscapePoints.insert(I);
00216         continue;  // Stores have no users to analyze.
00217       }
00218       case Instruction::BitCast:
00219       case Instruction::GetElementPtr:
00220       case Instruction::PHI:
00221       case Instruction::Select:
00222       case Instruction::AddrSpaceCast:
00223         break;
00224       default:
00225         EscapePoints.insert(I);
00226         break;
00227       }
00228 
00229       AddUsesToWorklist(I);
00230     }
00231   }
00232 
00233   void callUsesLocalStack(CallSite CS, bool IsNocapture) {
00234     // Add it to the list of alloca users.
00235     AllocaUsers.insert(CS.getInstruction());
00236 
00237     // If it's nocapture then it can't capture this alloca.
00238     if (IsNocapture)
00239       return;
00240 
00241     // If it can write to memory, it can leak the alloca value.
00242     if (!CS.onlyReadsMemory())
00243       EscapePoints.insert(CS.getInstruction());
00244   }
00245 
00246   SmallPtrSet<Instruction *, 32> AllocaUsers;
00247   SmallPtrSet<Instruction *, 32> EscapePoints;
00248 };
00249 }
00250 
00251 bool TailCallElim::markTails(Function &F, bool &AllCallsAreTailCalls) {
00252   if (F.callsFunctionThatReturnsTwice())
00253     return false;
00254   AllCallsAreTailCalls = true;
00255 
00256   AllocaDerivedValueTracker Tracker;
00257   for (auto &BB : F) {
00258     for (auto &I : BB)
00259       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
00260         Tracker.walk(AI);
00261   }
00262 
00263   bool Modified = false;
00264 
00265   // Track whether a block is reachable after an alloca has escaped. Blocks that
00266   // contain the escaping instruction will be marked as being visited without an
00267   // escaped alloca, since that is how the block began.
00268   enum VisitType {
00269     UNVISITED,
00270     UNESCAPED,
00271     ESCAPED
00272   };
00273   DenseMap<BasicBlock *, VisitType> Visited;
00274 
00275   // We propagate the fact that an alloca has escaped from block to successor.
00276   // Visit the blocks that are propagating the escapedness first. To do this, we
00277   // maintain two worklists.
00278   SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
00279 
00280   // We may enter a block and visit it thinking that no alloca has escaped yet,
00281   // then see an escape point and go back around a loop edge and come back to
00282   // the same block twice. Because of this, we defer setting tail on calls when
00283   // we first encounter them in a block. Every entry in this list does not
00284   // statically use an alloca via use-def chain analysis, but may find an alloca
00285   // through other means if the block turns out to be reachable after an escape
00286   // point.
00287   SmallVector<CallInst *, 32> DeferredTails;
00288 
00289   BasicBlock *BB = &F.getEntryBlock();
00290   VisitType Escaped = UNESCAPED;
00291   do {
00292     for (auto &I : *BB) {
00293       if (Tracker.EscapePoints.count(&I))
00294         Escaped = ESCAPED;
00295 
00296       CallInst *CI = dyn_cast<CallInst>(&I);
00297       if (!CI || CI->isTailCall())
00298         continue;
00299 
00300       if (CI->doesNotAccessMemory()) {
00301         // A call to a readnone function whose arguments are all things computed
00302         // outside this function can be marked tail. Even if you stored the
00303         // alloca address into a global, a readnone function can't load the
00304         // global anyhow.
00305         //
00306         // Note that this runs whether we know an alloca has escaped or not. If
00307         // it has, then we can't trust Tracker.AllocaUsers to be accurate.
00308         bool SafeToTail = true;
00309         for (auto &Arg : CI->arg_operands()) {
00310           if (isa<Constant>(Arg.getUser()))
00311             continue;
00312           if (isa<Argument>(Arg.getUser()))
00313             continue;
00314           SafeToTail = false;
00315           break;
00316         }
00317         if (SafeToTail) {
00318           emitOptimizationRemark(
00319               F.getContext(), "tailcallelim", F, CI->getDebugLoc(),
00320               "marked this readnone call a tail call candidate");
00321           CI->setTailCall();
00322           Modified = true;
00323           continue;
00324         }
00325       }
00326 
00327       if (Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) {
00328         DeferredTails.push_back(CI);
00329       } else {
00330         AllCallsAreTailCalls = false;
00331       }
00332     }
00333 
00334     for (auto *SuccBB : make_range(succ_begin(BB), succ_end(BB))) {
00335       auto &State = Visited[SuccBB];
00336       if (State < Escaped) {
00337         State = Escaped;
00338         if (State == ESCAPED)
00339           WorklistEscaped.push_back(SuccBB);
00340         else
00341           WorklistUnescaped.push_back(SuccBB);
00342       }
00343     }
00344 
00345     if (!WorklistEscaped.empty()) {
00346       BB = WorklistEscaped.pop_back_val();
00347       Escaped = ESCAPED;
00348     } else {
00349       BB = nullptr;
00350       while (!WorklistUnescaped.empty()) {
00351         auto *NextBB = WorklistUnescaped.pop_back_val();
00352         if (Visited[NextBB] == UNESCAPED) {
00353           BB = NextBB;
00354           Escaped = UNESCAPED;
00355           break;
00356         }
00357       }
00358     }
00359   } while (BB);
00360 
00361   for (CallInst *CI : DeferredTails) {
00362     if (Visited[CI->getParent()] != ESCAPED) {
00363       // If the escape point was part way through the block, calls after the
00364       // escape point wouldn't have been put into DeferredTails.
00365       emitOptimizationRemark(F.getContext(), "tailcallelim", F,
00366                              CI->getDebugLoc(),
00367                              "marked this call a tail call candidate");
00368       CI->setTailCall();
00369       Modified = true;
00370     } else {
00371       AllCallsAreTailCalls = false;
00372     }
00373   }
00374 
00375   return Modified;
00376 }
00377 
00378 bool TailCallElim::runTRE(Function &F) {
00379   // If this function is a varargs function, we won't be able to PHI the args
00380   // right, so don't even try to convert it...
00381   if (F.getFunctionType()->isVarArg()) return false;
00382 
00383   TTI = &getAnalysis<TargetTransformInfo>();
00384   BasicBlock *OldEntry = nullptr;
00385   bool TailCallsAreMarkedTail = false;
00386   SmallVector<PHINode*, 8> ArgumentPHIs;
00387   bool MadeChange = false;
00388 
00389   // CanTRETailMarkedCall - If false, we cannot perform TRE on tail calls
00390   // marked with the 'tail' attribute, because doing so would cause the stack
00391   // size to increase (real TRE would deallocate variable sized allocas, TRE
00392   // doesn't).
00393   bool CanTRETailMarkedCall = CanTRE(F);
00394 
00395   // Change any tail recursive calls to loops.
00396   //
00397   // FIXME: The code generator produces really bad code when an 'escaping
00398   // alloca' is changed from being a static alloca to being a dynamic alloca.
00399   // Until this is resolved, disable this transformation if that would ever
00400   // happen.  This bug is PR962.
00401   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00402     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
00403       bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
00404                                           ArgumentPHIs, !CanTRETailMarkedCall);
00405       if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
00406         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
00407                                           TailCallsAreMarkedTail, ArgumentPHIs,
00408                                           !CanTRETailMarkedCall);
00409       MadeChange |= Change;
00410     }
00411   }
00412 
00413   // If we eliminated any tail recursions, it's possible that we inserted some
00414   // silly PHI nodes which just merge an initial value (the incoming operand)
00415   // with themselves.  Check to see if we did and clean up our mess if so.  This
00416   // occurs when a function passes an argument straight through to its tail
00417   // call.
00418   for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
00419     PHINode *PN = ArgumentPHIs[i];
00420 
00421     // If the PHI Node is a dynamic constant, replace it with the value it is.
00422     if (Value *PNV = SimplifyInstruction(PN)) {
00423       PN->replaceAllUsesWith(PNV);
00424       PN->eraseFromParent();
00425     }
00426   }
00427 
00428   return MadeChange;
00429 }
00430 
00431 
00432 /// CanMoveAboveCall - Return true if it is safe to move the specified
00433 /// instruction from after the call to before the call, assuming that all
00434 /// instructions between the call and this instruction are movable.
00435 ///
00436 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
00437   // FIXME: We can move load/store/call/free instructions above the call if the
00438   // call does not mod/ref the memory location being processed.
00439   if (I->mayHaveSideEffects())  // This also handles volatile loads.
00440     return false;
00441 
00442   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00443     // Loads may always be moved above calls without side effects.
00444     if (CI->mayHaveSideEffects()) {
00445       // Non-volatile loads may be moved above a call with side effects if it
00446       // does not write to memory and the load provably won't trap.
00447       // FIXME: Writes to memory only matter if they may alias the pointer
00448       // being loaded from.
00449       if (CI->mayWriteToMemory() ||
00450           !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
00451                                        L->getAlignment(), DL))
00452         return false;
00453     }
00454   }
00455 
00456   // Otherwise, if this is a side-effect free instruction, check to make sure
00457   // that it does not use the return value of the call.  If it doesn't use the
00458   // return value of the call, it must only use things that are defined before
00459   // the call, or movable instructions between the call and the instruction
00460   // itself.
00461   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00462     if (I->getOperand(i) == CI)
00463       return false;
00464   return true;
00465 }
00466 
00467 // isDynamicConstant - Return true if the specified value is the same when the
00468 // return would exit as it was when the initial iteration of the recursive
00469 // function was executed.
00470 //
00471 // We currently handle static constants and arguments that are not modified as
00472 // part of the recursion.
00473 //
00474 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
00475   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
00476 
00477   // Check to see if this is an immutable argument, if so, the value
00478   // will be available to initialize the accumulator.
00479   if (Argument *Arg = dyn_cast<Argument>(V)) {
00480     // Figure out which argument number this is...
00481     unsigned ArgNo = 0;
00482     Function *F = CI->getParent()->getParent();
00483     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
00484       ++ArgNo;
00485 
00486     // If we are passing this argument into call as the corresponding
00487     // argument operand, then the argument is dynamically constant.
00488     // Otherwise, we cannot transform this function safely.
00489     if (CI->getArgOperand(ArgNo) == Arg)
00490       return true;
00491   }
00492 
00493   // Switch cases are always constant integers. If the value is being switched
00494   // on and the return is only reachable from one of its cases, it's
00495   // effectively constant.
00496   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
00497     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
00498       if (SI->getCondition() == V)
00499         return SI->getDefaultDest() != RI->getParent();
00500 
00501   // Not a constant or immutable argument, we can't safely transform.
00502   return false;
00503 }
00504 
00505 // getCommonReturnValue - Check to see if the function containing the specified
00506 // tail call consistently returns the same runtime-constant value at all exit
00507 // points except for IgnoreRI.  If so, return the returned value.
00508 //
00509 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
00510   Function *F = CI->getParent()->getParent();
00511   Value *ReturnedValue = nullptr;
00512 
00513   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
00514     ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
00515     if (RI == nullptr || RI == IgnoreRI) continue;
00516 
00517     // We can only perform this transformation if the value returned is
00518     // evaluatable at the start of the initial invocation of the function,
00519     // instead of at the end of the evaluation.
00520     //
00521     Value *RetOp = RI->getOperand(0);
00522     if (!isDynamicConstant(RetOp, CI, RI))
00523       return nullptr;
00524 
00525     if (ReturnedValue && RetOp != ReturnedValue)
00526       return nullptr;     // Cannot transform if differing values are returned.
00527     ReturnedValue = RetOp;
00528   }
00529   return ReturnedValue;
00530 }
00531 
00532 /// CanTransformAccumulatorRecursion - If the specified instruction can be
00533 /// transformed using accumulator recursion elimination, return the constant
00534 /// which is the start of the accumulator value.  Otherwise return null.
00535 ///
00536 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
00537                                                       CallInst *CI) {
00538   if (!I->isAssociative() || !I->isCommutative()) return nullptr;
00539   assert(I->getNumOperands() == 2 &&
00540          "Associative/commutative operations should have 2 args!");
00541 
00542   // Exactly one operand should be the result of the call instruction.
00543   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
00544       (I->getOperand(0) != CI && I->getOperand(1) != CI))
00545     return nullptr;
00546 
00547   // The only user of this instruction we allow is a single return instruction.
00548   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
00549     return nullptr;
00550 
00551   // Ok, now we have to check all of the other return instructions in this
00552   // function.  If they return non-constants or differing values, then we cannot
00553   // transform the function safely.
00554   return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
00555 }
00556 
00557 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
00558   while (isa<DbgInfoIntrinsic>(I))
00559     ++I;
00560   return &*I;
00561 }
00562 
00563 CallInst*
00564 TailCallElim::FindTRECandidate(Instruction *TI,
00565                                bool CannotTailCallElimCallsMarkedTail) {
00566   BasicBlock *BB = TI->getParent();
00567   Function *F = BB->getParent();
00568 
00569   if (&BB->front() == TI) // Make sure there is something before the terminator.
00570     return nullptr;
00571 
00572   // Scan backwards from the return, checking to see if there is a tail call in
00573   // this block.  If so, set CI to it.
00574   CallInst *CI = nullptr;
00575   BasicBlock::iterator BBI = TI;
00576   while (true) {
00577     CI = dyn_cast<CallInst>(BBI);
00578     if (CI && CI->getCalledFunction() == F)
00579       break;
00580 
00581     if (BBI == BB->begin())
00582       return nullptr;          // Didn't find a potential tail call.
00583     --BBI;
00584   }
00585 
00586   // If this call is marked as a tail call, and if there are dynamic allocas in
00587   // the function, we cannot perform this optimization.
00588   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
00589     return nullptr;
00590 
00591   // As a special case, detect code like this:
00592   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
00593   // and disable this xform in this case, because the code generator will
00594   // lower the call to fabs into inline code.
00595   if (BB == &F->getEntryBlock() &&
00596       FirstNonDbg(BB->front()) == CI &&
00597       FirstNonDbg(std::next(BB->begin())) == TI &&
00598       CI->getCalledFunction() &&
00599       !TTI->isLoweredToCall(CI->getCalledFunction())) {
00600     // A single-block function with just a call and a return. Check that
00601     // the arguments match.
00602     CallSite::arg_iterator I = CallSite(CI).arg_begin(),
00603                            E = CallSite(CI).arg_end();
00604     Function::arg_iterator FI = F->arg_begin(),
00605                            FE = F->arg_end();
00606     for (; I != E && FI != FE; ++I, ++FI)
00607       if (*I != &*FI) break;
00608     if (I == E && FI == FE)
00609       return nullptr;
00610   }
00611 
00612   return CI;
00613 }
00614 
00615 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00616                                        BasicBlock *&OldEntry,
00617                                        bool &TailCallsAreMarkedTail,
00618                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00619                                        bool CannotTailCallElimCallsMarkedTail) {
00620   // If we are introducing accumulator recursion to eliminate operations after
00621   // the call instruction that are both associative and commutative, the initial
00622   // value for the accumulator is placed in this variable.  If this value is set
00623   // then we actually perform accumulator recursion elimination instead of
00624   // simple tail recursion elimination.  If the operation is an LLVM instruction
00625   // (eg: "add") then it is recorded in AccumulatorRecursionInstr.  If not, then
00626   // we are handling the case when the return instruction returns a constant C
00627   // which is different to the constant returned by other return instructions
00628   // (which is recorded in AccumulatorRecursionEliminationInitVal).  This is a
00629   // special case of accumulator recursion, the operation being "return C".
00630   Value *AccumulatorRecursionEliminationInitVal = nullptr;
00631   Instruction *AccumulatorRecursionInstr = nullptr;
00632 
00633   // Ok, we found a potential tail call.  We can currently only transform the
00634   // tail call if all of the instructions between the call and the return are
00635   // movable to above the call itself, leaving the call next to the return.
00636   // Check that this is the case now.
00637   BasicBlock::iterator BBI = CI;
00638   for (++BBI; &*BBI != Ret; ++BBI) {
00639     if (CanMoveAboveCall(BBI, CI)) continue;
00640 
00641     // If we can't move the instruction above the call, it might be because it
00642     // is an associative and commutative operation that could be transformed
00643     // using accumulator recursion elimination.  Check to see if this is the
00644     // case, and if so, remember the initial accumulator value for later.
00645     if ((AccumulatorRecursionEliminationInitVal =
00646                            CanTransformAccumulatorRecursion(BBI, CI))) {
00647       // Yes, this is accumulator recursion.  Remember which instruction
00648       // accumulates.
00649       AccumulatorRecursionInstr = BBI;
00650     } else {
00651       return false;   // Otherwise, we cannot eliminate the tail recursion!
00652     }
00653   }
00654 
00655   // We can only transform call/return pairs that either ignore the return value
00656   // of the call and return void, ignore the value of the call and return a
00657   // constant, return the value returned by the tail call, or that are being
00658   // accumulator recursion variable eliminated.
00659   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
00660       !isa<UndefValue>(Ret->getReturnValue()) &&
00661       AccumulatorRecursionEliminationInitVal == nullptr &&
00662       !getCommonReturnValue(nullptr, CI)) {
00663     // One case remains that we are able to handle: the current return
00664     // instruction returns a constant, and all other return instructions
00665     // return a different constant.
00666     if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
00667       return false; // Current return instruction does not return a constant.
00668     // Check that all other return instructions return a common constant.  If
00669     // so, record it in AccumulatorRecursionEliminationInitVal.
00670     AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
00671     if (!AccumulatorRecursionEliminationInitVal)
00672       return false;
00673   }
00674 
00675   BasicBlock *BB = Ret->getParent();
00676   Function *F = BB->getParent();
00677 
00678   emitOptimizationRemark(F->getContext(), "tailcallelim", *F, CI->getDebugLoc(),
00679                          "transforming tail recursion to loop");
00680 
00681   // OK! We can transform this tail call.  If this is the first one found,
00682   // create the new entry block, allowing us to branch back to the old entry.
00683   if (!OldEntry) {
00684     OldEntry = &F->getEntryBlock();
00685     BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
00686     NewEntry->takeName(OldEntry);
00687     OldEntry->setName("tailrecurse");
00688     BranchInst::Create(OldEntry, NewEntry);
00689 
00690     // If this tail call is marked 'tail' and if there are any allocas in the
00691     // entry block, move them up to the new entry block.
00692     TailCallsAreMarkedTail = CI->isTailCall();
00693     if (TailCallsAreMarkedTail)
00694       // Move all fixed sized allocas from OldEntry to NewEntry.
00695       for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
00696              NEBI = NewEntry->begin(); OEBI != E; )
00697         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
00698           if (isa<ConstantInt>(AI->getArraySize()))
00699             AI->moveBefore(NEBI);
00700 
00701     // Now that we have created a new block, which jumps to the entry
00702     // block, insert a PHI node for each argument of the function.
00703     // For now, we initialize each PHI to only have the real arguments
00704     // which are passed in.
00705     Instruction *InsertPos = OldEntry->begin();
00706     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00707          I != E; ++I) {
00708       PHINode *PN = PHINode::Create(I->getType(), 2,
00709                                     I->getName() + ".tr", InsertPos);
00710       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
00711       PN->addIncoming(I, NewEntry);
00712       ArgumentPHIs.push_back(PN);
00713     }
00714   }
00715 
00716   // If this function has self recursive calls in the tail position where some
00717   // are marked tail and some are not, only transform one flavor or another.  We
00718   // have to choose whether we move allocas in the entry block to the new entry
00719   // block or not, so we can't make a good choice for both.  NOTE: We could do
00720   // slightly better here in the case that the function has no entry block
00721   // allocas.
00722   if (TailCallsAreMarkedTail && !CI->isTailCall())
00723     return false;
00724 
00725   // Ok, now that we know we have a pseudo-entry block WITH all of the
00726   // required PHI nodes, add entries into the PHI node for the actual
00727   // parameters passed into the tail-recursive call.
00728   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
00729     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
00730 
00731   // If we are introducing an accumulator variable to eliminate the recursion,
00732   // do so now.  Note that we _know_ that no subsequent tail recursion
00733   // eliminations will happen on this function because of the way the
00734   // accumulator recursion predicate is set up.
00735   //
00736   if (AccumulatorRecursionEliminationInitVal) {
00737     Instruction *AccRecInstr = AccumulatorRecursionInstr;
00738     // Start by inserting a new PHI node for the accumulator.
00739     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
00740     PHINode *AccPN =
00741       PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
00742                       std::distance(PB, PE) + 1,
00743                       "accumulator.tr", OldEntry->begin());
00744 
00745     // Loop over all of the predecessors of the tail recursion block.  For the
00746     // real entry into the function we seed the PHI with the initial value,
00747     // computed earlier.  For any other existing branches to this block (due to
00748     // other tail recursions eliminated) the accumulator is not modified.
00749     // Because we haven't added the branch in the current block to OldEntry yet,
00750     // it will not show up as a predecessor.
00751     for (pred_iterator PI = PB; PI != PE; ++PI) {
00752       BasicBlock *P = *PI;
00753       if (P == &F->getEntryBlock())
00754         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
00755       else
00756         AccPN->addIncoming(AccPN, P);
00757     }
00758 
00759     if (AccRecInstr) {
00760       // Add an incoming argument for the current block, which is computed by
00761       // our associative and commutative accumulator instruction.
00762       AccPN->addIncoming(AccRecInstr, BB);
00763 
00764       // Next, rewrite the accumulator recursion instruction so that it does not
00765       // use the result of the call anymore, instead, use the PHI node we just
00766       // inserted.
00767       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
00768     } else {
00769       // Add an incoming argument for the current block, which is just the
00770       // constant returned by the current return instruction.
00771       AccPN->addIncoming(Ret->getReturnValue(), BB);
00772     }
00773 
00774     // Finally, rewrite any return instructions in the program to return the PHI
00775     // node instead of the "initval" that they do currently.  This loop will
00776     // actually rewrite the return value we are destroying, but that's ok.
00777     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00778       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00779         RI->setOperand(0, AccPN);
00780     ++NumAccumAdded;
00781   }
00782 
00783   // Now that all of the PHI nodes are in place, remove the call and
00784   // ret instructions, replacing them with an unconditional branch.
00785   BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
00786   NewBI->setDebugLoc(CI->getDebugLoc());
00787 
00788   BB->getInstList().erase(Ret);  // Remove return.
00789   BB->getInstList().erase(CI);   // Remove call.
00790   ++NumEliminated;
00791   return true;
00792 }
00793 
00794 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
00795                                        ReturnInst *Ret, BasicBlock *&OldEntry,
00796                                        bool &TailCallsAreMarkedTail,
00797                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00798                                        bool CannotTailCallElimCallsMarkedTail) {
00799   bool Change = false;
00800 
00801   // If the return block contains nothing but the return and PHI's,
00802   // there might be an opportunity to duplicate the return in its
00803   // predecessors and perform TRC there. Look for predecessors that end
00804   // in unconditional branch and recursive call(s).
00805   SmallVector<BranchInst*, 8> UncondBranchPreds;
00806   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00807     BasicBlock *Pred = *PI;
00808     TerminatorInst *PTI = Pred->getTerminator();
00809     if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
00810       if (BI->isUnconditional())
00811         UncondBranchPreds.push_back(BI);
00812   }
00813 
00814   while (!UncondBranchPreds.empty()) {
00815     BranchInst *BI = UncondBranchPreds.pop_back_val();
00816     BasicBlock *Pred = BI->getParent();
00817     if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
00818       DEBUG(dbgs() << "FOLDING: " << *BB
00819             << "INTO UNCOND BRANCH PRED: " << *Pred);
00820       EliminateRecursiveTailCall(CI, FoldReturnIntoUncondBranch(Ret, BB, Pred),
00821                                  OldEntry, TailCallsAreMarkedTail, ArgumentPHIs,
00822                                  CannotTailCallElimCallsMarkedTail);
00823       ++NumRetDuped;
00824       Change = true;
00825     }
00826   }
00827 
00828   return Change;
00829 }
00830 
00831 bool
00832 TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
00833                                     bool &TailCallsAreMarkedTail,
00834                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00835                                     bool CannotTailCallElimCallsMarkedTail) {
00836   CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
00837   if (!CI)
00838     return false;
00839 
00840   return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
00841                                     ArgumentPHIs,
00842                                     CannotTailCallElimCallsMarkedTail);
00843 }