LLVM  mainline
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/GlobalsModRef.h"
00058 #include "llvm/Analysis/CFG.h"
00059 #include "llvm/Analysis/CaptureTracking.h"
00060 #include "llvm/Analysis/InlineCost.h"
00061 #include "llvm/Analysis/InstructionSimplify.h"
00062 #include "llvm/Analysis/Loads.h"
00063 #include "llvm/Analysis/TargetTransformInfo.h"
00064 #include "llvm/IR/CFG.h"
00065 #include "llvm/IR/CallSite.h"
00066 #include "llvm/IR/Constants.h"
00067 #include "llvm/IR/DataLayout.h"
00068 #include "llvm/IR/DerivedTypes.h"
00069 #include "llvm/IR/DiagnosticInfo.h"
00070 #include "llvm/IR/Function.h"
00071 #include "llvm/IR/Instructions.h"
00072 #include "llvm/IR/IntrinsicInst.h"
00073 #include "llvm/IR/Module.h"
00074 #include "llvm/IR/ValueHandle.h"
00075 #include "llvm/Pass.h"
00076 #include "llvm/Support/Debug.h"
00077 #include "llvm/Support/raw_ostream.h"
00078 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00079 #include "llvm/Transforms/Utils/Local.h"
00080 using namespace llvm;
00081 
00082 #define DEBUG_TYPE "tailcallelim"
00083 
00084 STATISTIC(NumEliminated, "Number of tail calls removed");
00085 STATISTIC(NumRetDuped,   "Number of return duplicated");
00086 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
00087 
00088 namespace {
00089   struct TailCallElim : public FunctionPass {
00090     const TargetTransformInfo *TTI;
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_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
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<TargetTransformInfoWrapperPass>();
00140   AU.addPreserved<GlobalsAAWrapperPass>();
00141 }
00142 
00143 /// \brief Scan the specified function for alloca instructions.
00144 /// If it contains any dynamic allocas, returns false.
00145 static bool CanTRE(Function &F) {
00146   // Because of PR962, we don't TRE dynamic allocas.
00147   for (auto &BB : F) {
00148     for (auto &I : BB) {
00149       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
00150         if (!AI->isStaticAlloca())
00151           return false;
00152       }
00153     }
00154   }
00155 
00156   return true;
00157 }
00158 
00159 bool TailCallElim::runOnFunction(Function &F) {
00160   if (skipOptnoneFunction(F))
00161     return false;
00162 
00163   if (F.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
00164     return false;
00165 
00166   bool AllCallsAreTailCalls = false;
00167   bool Modified = markTails(F, AllCallsAreTailCalls);
00168   if (AllCallsAreTailCalls)
00169     Modified |= runTRE(F);
00170   return Modified;
00171 }
00172 
00173 namespace {
00174 struct AllocaDerivedValueTracker {
00175   // Start at a root value and walk its use-def chain to mark calls that use the
00176   // value or a derived value in AllocaUsers, and places where it may escape in
00177   // EscapePoints.
00178   void walk(Value *Root) {
00179     SmallVector<Use *, 32> Worklist;
00180     SmallPtrSet<Use *, 32> Visited;
00181 
00182     auto AddUsesToWorklist = [&](Value *V) {
00183       for (auto &U : V->uses()) {
00184         if (!Visited.insert(&U).second)
00185           continue;
00186         Worklist.push_back(&U);
00187       }
00188     };
00189 
00190     AddUsesToWorklist(Root);
00191 
00192     while (!Worklist.empty()) {
00193       Use *U = Worklist.pop_back_val();
00194       Instruction *I = cast<Instruction>(U->getUser());
00195 
00196       switch (I->getOpcode()) {
00197       case Instruction::Call:
00198       case Instruction::Invoke: {
00199         CallSite CS(I);
00200         bool IsNocapture =
00201             CS.isDataOperand(U) && CS.doesNotCapture(CS.getDataOperandNo(U));
00202         callUsesLocalStack(CS, IsNocapture);
00203         if (IsNocapture) {
00204           // If the alloca-derived argument is passed in as nocapture, then it
00205           // can't propagate to the call's return. That would be capturing.
00206           continue;
00207         }
00208         break;
00209       }
00210       case Instruction::Load: {
00211         // The result of a load is not alloca-derived (unless an alloca has
00212         // otherwise escaped, but this is a local analysis).
00213         continue;
00214       }
00215       case Instruction::Store: {
00216         if (U->getOperandNo() == 0)
00217           EscapePoints.insert(I);
00218         continue;  // Stores have no users to analyze.
00219       }
00220       case Instruction::BitCast:
00221       case Instruction::GetElementPtr:
00222       case Instruction::PHI:
00223       case Instruction::Select:
00224       case Instruction::AddrSpaceCast:
00225         break;
00226       default:
00227         EscapePoints.insert(I);
00228         break;
00229       }
00230 
00231       AddUsesToWorklist(I);
00232     }
00233   }
00234 
00235   void callUsesLocalStack(CallSite CS, bool IsNocapture) {
00236     // Add it to the list of alloca users.
00237     AllocaUsers.insert(CS.getInstruction());
00238 
00239     // If it's nocapture then it can't capture this alloca.
00240     if (IsNocapture)
00241       return;
00242 
00243     // If it can write to memory, it can leak the alloca value.
00244     if (!CS.onlyReadsMemory())
00245       EscapePoints.insert(CS.getInstruction());
00246   }
00247 
00248   SmallPtrSet<Instruction *, 32> AllocaUsers;
00249   SmallPtrSet<Instruction *, 32> EscapePoints;
00250 };
00251 }
00252 
00253 bool TailCallElim::markTails(Function &F, bool &AllCallsAreTailCalls) {
00254   if (F.callsFunctionThatReturnsTwice())
00255     return false;
00256   AllCallsAreTailCalls = true;
00257 
00258   // The local stack holds all alloca instructions and all byval arguments.
00259   AllocaDerivedValueTracker Tracker;
00260   for (Argument &Arg : F.args()) {
00261     if (Arg.hasByValAttr())
00262       Tracker.walk(&Arg);
00263   }
00264   for (auto &BB : F) {
00265     for (auto &I : BB)
00266       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
00267         Tracker.walk(AI);
00268   }
00269 
00270   bool Modified = false;
00271 
00272   // Track whether a block is reachable after an alloca has escaped. Blocks that
00273   // contain the escaping instruction will be marked as being visited without an
00274   // escaped alloca, since that is how the block began.
00275   enum VisitType {
00276     UNVISITED,
00277     UNESCAPED,
00278     ESCAPED
00279   };
00280   DenseMap<BasicBlock *, VisitType> Visited;
00281 
00282   // We propagate the fact that an alloca has escaped from block to successor.
00283   // Visit the blocks that are propagating the escapedness first. To do this, we
00284   // maintain two worklists.
00285   SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
00286 
00287   // We may enter a block and visit it thinking that no alloca has escaped yet,
00288   // then see an escape point and go back around a loop edge and come back to
00289   // the same block twice. Because of this, we defer setting tail on calls when
00290   // we first encounter them in a block. Every entry in this list does not
00291   // statically use an alloca via use-def chain analysis, but may find an alloca
00292   // through other means if the block turns out to be reachable after an escape
00293   // point.
00294   SmallVector<CallInst *, 32> DeferredTails;
00295 
00296   BasicBlock *BB = &F.getEntryBlock();
00297   VisitType Escaped = UNESCAPED;
00298   do {
00299     for (auto &I : *BB) {
00300       if (Tracker.EscapePoints.count(&I))
00301         Escaped = ESCAPED;
00302 
00303       CallInst *CI = dyn_cast<CallInst>(&I);
00304       if (!CI || CI->isTailCall())
00305         continue;
00306 
00307       bool IsNoTail = CI->isNoTailCall();
00308 
00309       if (!IsNoTail && CI->doesNotAccessMemory()) {
00310         // A call to a readnone function whose arguments are all things computed
00311         // outside this function can be marked tail. Even if you stored the
00312         // alloca address into a global, a readnone function can't load the
00313         // global anyhow.
00314         //
00315         // Note that this runs whether we know an alloca has escaped or not. If
00316         // it has, then we can't trust Tracker.AllocaUsers to be accurate.
00317         bool SafeToTail = true;
00318         for (auto &Arg : CI->arg_operands()) {
00319           if (isa<Constant>(Arg.getUser()))
00320             continue;
00321           if (Argument *A = dyn_cast<Argument>(Arg.getUser()))
00322             if (!A->hasByValAttr())
00323               continue;
00324           SafeToTail = false;
00325           break;
00326         }
00327         if (SafeToTail) {
00328           emitOptimizationRemark(
00329               F.getContext(), "tailcallelim", F, CI->getDebugLoc(),
00330               "marked this readnone call a tail call candidate");
00331           CI->setTailCall();
00332           Modified = true;
00333           continue;
00334         }
00335       }
00336 
00337       if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) {
00338         DeferredTails.push_back(CI);
00339       } else {
00340         AllCallsAreTailCalls = false;
00341       }
00342     }
00343 
00344     for (auto *SuccBB : make_range(succ_begin(BB), succ_end(BB))) {
00345       auto &State = Visited[SuccBB];
00346       if (State < Escaped) {
00347         State = Escaped;
00348         if (State == ESCAPED)
00349           WorklistEscaped.push_back(SuccBB);
00350         else
00351           WorklistUnescaped.push_back(SuccBB);
00352       }
00353     }
00354 
00355     if (!WorklistEscaped.empty()) {
00356       BB = WorklistEscaped.pop_back_val();
00357       Escaped = ESCAPED;
00358     } else {
00359       BB = nullptr;
00360       while (!WorklistUnescaped.empty()) {
00361         auto *NextBB = WorklistUnescaped.pop_back_val();
00362         if (Visited[NextBB] == UNESCAPED) {
00363           BB = NextBB;
00364           Escaped = UNESCAPED;
00365           break;
00366         }
00367       }
00368     }
00369   } while (BB);
00370 
00371   for (CallInst *CI : DeferredTails) {
00372     if (Visited[CI->getParent()] != ESCAPED) {
00373       // If the escape point was part way through the block, calls after the
00374       // escape point wouldn't have been put into DeferredTails.
00375       emitOptimizationRemark(F.getContext(), "tailcallelim", F,
00376                              CI->getDebugLoc(),
00377                              "marked this call a tail call candidate");
00378       CI->setTailCall();
00379       Modified = true;
00380     } else {
00381       AllCallsAreTailCalls = false;
00382     }
00383   }
00384 
00385   return Modified;
00386 }
00387 
00388 bool TailCallElim::runTRE(Function &F) {
00389   // If this function is a varargs function, we won't be able to PHI the args
00390   // right, so don't even try to convert it...
00391   if (F.getFunctionType()->isVarArg()) return false;
00392 
00393   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
00394   BasicBlock *OldEntry = nullptr;
00395   bool TailCallsAreMarkedTail = false;
00396   SmallVector<PHINode*, 8> ArgumentPHIs;
00397   bool MadeChange = false;
00398 
00399   // If false, we cannot perform TRE on tail calls marked with the 'tail'
00400   // attribute, because doing so would cause the stack size to increase (real
00401   // TRE would deallocate variable sized allocas, TRE doesn't).
00402   bool CanTRETailMarkedCall = CanTRE(F);
00403 
00404   // Change any tail recursive calls to loops.
00405   //
00406   // FIXME: The code generator produces really bad code when an 'escaping
00407   // alloca' is changed from being a static alloca to being a dynamic alloca.
00408   // Until this is resolved, disable this transformation if that would ever
00409   // happen.  This bug is PR962.
00410   for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; /*in loop*/) {
00411     BasicBlock *BB = &*BBI++; // FoldReturnAndProcessPred may delete BB.
00412     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
00413       bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
00414                                           ArgumentPHIs, !CanTRETailMarkedCall);
00415       if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
00416         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
00417                                           TailCallsAreMarkedTail, ArgumentPHIs,
00418                                           !CanTRETailMarkedCall);
00419       MadeChange |= Change;
00420     }
00421   }
00422 
00423   // If we eliminated any tail recursions, it's possible that we inserted some
00424   // silly PHI nodes which just merge an initial value (the incoming operand)
00425   // with themselves.  Check to see if we did and clean up our mess if so.  This
00426   // occurs when a function passes an argument straight through to its tail
00427   // call.
00428   for (PHINode *PN : ArgumentPHIs) {
00429     // If the PHI Node is a dynamic constant, replace it with the value it is.
00430     if (Value *PNV = SimplifyInstruction(PN, F.getParent()->getDataLayout())) {
00431       PN->replaceAllUsesWith(PNV);
00432       PN->eraseFromParent();
00433     }
00434   }
00435 
00436   return MadeChange;
00437 }
00438 
00439 
00440 /// Return true if it is safe to move the specified
00441 /// instruction from after the call to before the call, assuming that all
00442 /// instructions between the call and this instruction are movable.
00443 ///
00444 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
00445   // FIXME: We can move load/store/call/free instructions above the call if the
00446   // call does not mod/ref the memory location being processed.
00447   if (I->mayHaveSideEffects())  // This also handles volatile loads.
00448     return false;
00449 
00450   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00451     // Loads may always be moved above calls without side effects.
00452     if (CI->mayHaveSideEffects()) {
00453       // Non-volatile loads may be moved above a call with side effects if it
00454       // does not write to memory and the load provably won't trap.
00455       // FIXME: Writes to memory only matter if they may alias the pointer
00456       // being loaded from.
00457       if (CI->mayWriteToMemory() ||
00458           !isSafeToLoadUnconditionally(L->getPointerOperand(),
00459                                        L->getAlignment(), L))
00460         return false;
00461     }
00462   }
00463 
00464   // Otherwise, if this is a side-effect free instruction, check to make sure
00465   // that it does not use the return value of the call.  If it doesn't use the
00466   // return value of the call, it must only use things that are defined before
00467   // the call, or movable instructions between the call and the instruction
00468   // itself.
00469   return std::find(I->op_begin(), I->op_end(), CI) == I->op_end();
00470 }
00471 
00472 /// Return true if the specified value is the same when the return would exit
00473 /// as it was when the initial iteration of the recursive function was executed.
00474 ///
00475 /// We currently handle static constants and arguments that are not modified as
00476 /// part of the recursion.
00477 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
00478   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
00479 
00480   // Check to see if this is an immutable argument, if so, the value
00481   // will be available to initialize the accumulator.
00482   if (Argument *Arg = dyn_cast<Argument>(V)) {
00483     // Figure out which argument number this is...
00484     unsigned ArgNo = 0;
00485     Function *F = CI->getParent()->getParent();
00486     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
00487       ++ArgNo;
00488 
00489     // If we are passing this argument into call as the corresponding
00490     // argument operand, then the argument is dynamically constant.
00491     // Otherwise, we cannot transform this function safely.
00492     if (CI->getArgOperand(ArgNo) == Arg)
00493       return true;
00494   }
00495 
00496   // Switch cases are always constant integers. If the value is being switched
00497   // on and the return is only reachable from one of its cases, it's
00498   // effectively constant.
00499   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
00500     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
00501       if (SI->getCondition() == V)
00502         return SI->getDefaultDest() != RI->getParent();
00503 
00504   // Not a constant or immutable argument, we can't safely transform.
00505   return false;
00506 }
00507 
00508 /// Check to see if the function containing the specified tail call consistently
00509 /// returns the same runtime-constant value at all exit points except for
00510 /// IgnoreRI. If so, return the returned value.
00511 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
00512   Function *F = CI->getParent()->getParent();
00513   Value *ReturnedValue = nullptr;
00514 
00515   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
00516     ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
00517     if (RI == nullptr || RI == IgnoreRI) continue;
00518 
00519     // We can only perform this transformation if the value returned is
00520     // evaluatable at the start of the initial invocation of the function,
00521     // instead of at the end of the evaluation.
00522     //
00523     Value *RetOp = RI->getOperand(0);
00524     if (!isDynamicConstant(RetOp, CI, RI))
00525       return nullptr;
00526 
00527     if (ReturnedValue && RetOp != ReturnedValue)
00528       return nullptr;     // Cannot transform if differing values are returned.
00529     ReturnedValue = RetOp;
00530   }
00531   return ReturnedValue;
00532 }
00533 
00534 /// If the specified instruction can be transformed using accumulator recursion
00535 /// elimination, return the constant which is the start of the accumulator
00536 /// value.  Otherwise return null.
00537 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
00538                                                       CallInst *CI) {
00539   if (!I->isAssociative() || !I->isCommutative()) return nullptr;
00540   assert(I->getNumOperands() == 2 &&
00541          "Associative/commutative operations should have 2 args!");
00542 
00543   // Exactly one operand should be the result of the call instruction.
00544   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
00545       (I->getOperand(0) != CI && I->getOperand(1) != CI))
00546     return nullptr;
00547 
00548   // The only user of this instruction we allow is a single return instruction.
00549   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
00550     return nullptr;
00551 
00552   // Ok, now we have to check all of the other return instructions in this
00553   // function.  If they return non-constants or differing values, then we cannot
00554   // transform the function safely.
00555   return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
00556 }
00557 
00558 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
00559   while (isa<DbgInfoIntrinsic>(I))
00560     ++I;
00561   return &*I;
00562 }
00563 
00564 CallInst*
00565 TailCallElim::FindTRECandidate(Instruction *TI,
00566                                bool CannotTailCallElimCallsMarkedTail) {
00567   BasicBlock *BB = TI->getParent();
00568   Function *F = BB->getParent();
00569 
00570   if (&BB->front() == TI) // Make sure there is something before the terminator.
00571     return nullptr;
00572 
00573   // Scan backwards from the return, checking to see if there is a tail call in
00574   // this block.  If so, set CI to it.
00575   CallInst *CI = nullptr;
00576   BasicBlock::iterator BBI(TI);
00577   while (true) {
00578     CI = dyn_cast<CallInst>(BBI);
00579     if (CI && CI->getCalledFunction() == F)
00580       break;
00581 
00582     if (BBI == BB->begin())
00583       return nullptr;          // Didn't find a potential tail call.
00584     --BBI;
00585   }
00586 
00587   // If this call is marked as a tail call, and if there are dynamic allocas in
00588   // the function, we cannot perform this optimization.
00589   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
00590     return nullptr;
00591 
00592   // As a special case, detect code like this:
00593   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
00594   // and disable this xform in this case, because the code generator will
00595   // lower the call to fabs into inline code.
00596   if (BB == &F->getEntryBlock() &&
00597       FirstNonDbg(BB->front().getIterator()) == CI &&
00598       FirstNonDbg(std::next(BB->begin())) == TI && 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->front();
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 = PHINode::Create(
00741         AccumulatorRecursionEliminationInitVal->getType(),
00742         std::distance(PB, PE) + 1, "accumulator.tr", &OldEntry->front());
00743 
00744     // Loop over all of the predecessors of the tail recursion block.  For the
00745     // real entry into the function we seed the PHI with the initial value,
00746     // computed earlier.  For any other existing branches to this block (due to
00747     // other tail recursions eliminated) the accumulator is not modified.
00748     // Because we haven't added the branch in the current block to OldEntry yet,
00749     // it will not show up as a predecessor.
00750     for (pred_iterator PI = PB; PI != PE; ++PI) {
00751       BasicBlock *P = *PI;
00752       if (P == &F->getEntryBlock())
00753         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
00754       else
00755         AccPN->addIncoming(AccPN, P);
00756     }
00757 
00758     if (AccRecInstr) {
00759       // Add an incoming argument for the current block, which is computed by
00760       // our associative and commutative accumulator instruction.
00761       AccPN->addIncoming(AccRecInstr, BB);
00762 
00763       // Next, rewrite the accumulator recursion instruction so that it does not
00764       // use the result of the call anymore, instead, use the PHI node we just
00765       // inserted.
00766       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
00767     } else {
00768       // Add an incoming argument for the current block, which is just the
00769       // constant returned by the current return instruction.
00770       AccPN->addIncoming(Ret->getReturnValue(), BB);
00771     }
00772 
00773     // Finally, rewrite any return instructions in the program to return the PHI
00774     // node instead of the "initval" that they do currently.  This loop will
00775     // actually rewrite the return value we are destroying, but that's ok.
00776     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00777       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00778         RI->setOperand(0, AccPN);
00779     ++NumAccumAdded;
00780   }
00781 
00782   // Now that all of the PHI nodes are in place, remove the call and
00783   // ret instructions, replacing them with an unconditional branch.
00784   BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
00785   NewBI->setDebugLoc(CI->getDebugLoc());
00786 
00787   BB->getInstList().erase(Ret);  // Remove return.
00788   BB->getInstList().erase(CI);   // Remove call.
00789   ++NumEliminated;
00790   return true;
00791 }
00792 
00793 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
00794                                        ReturnInst *Ret, BasicBlock *&OldEntry,
00795                                        bool &TailCallsAreMarkedTail,
00796                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00797                                        bool CannotTailCallElimCallsMarkedTail) {
00798   bool Change = false;
00799 
00800   // If the return block contains nothing but the return and PHI's,
00801   // there might be an opportunity to duplicate the return in its
00802   // predecessors and perform TRC there. Look for predecessors that end
00803   // in unconditional branch and recursive call(s).
00804   SmallVector<BranchInst*, 8> UncondBranchPreds;
00805   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00806     BasicBlock *Pred = *PI;
00807     TerminatorInst *PTI = Pred->getTerminator();
00808     if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
00809       if (BI->isUnconditional())
00810         UncondBranchPreds.push_back(BI);
00811   }
00812 
00813   while (!UncondBranchPreds.empty()) {
00814     BranchInst *BI = UncondBranchPreds.pop_back_val();
00815     BasicBlock *Pred = BI->getParent();
00816     if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
00817       DEBUG(dbgs() << "FOLDING: " << *BB
00818             << "INTO UNCOND BRANCH PRED: " << *Pred);
00819       ReturnInst *RI = FoldReturnIntoUncondBranch(Ret, BB, Pred);
00820 
00821       // Cleanup: if all predecessors of BB have been eliminated by
00822       // FoldReturnIntoUncondBranch, delete it.  It is important to empty it,
00823       // because the ret instruction in there is still using a value which
00824       // EliminateRecursiveTailCall will attempt to remove.
00825       if (!BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
00826         BB->eraseFromParent();
00827 
00828       EliminateRecursiveTailCall(CI, RI, OldEntry, TailCallsAreMarkedTail,
00829                                  ArgumentPHIs,
00830                                  CannotTailCallElimCallsMarkedTail);
00831       ++NumRetDuped;
00832       Change = true;
00833     }
00834   }
00835 
00836   return Change;
00837 }
00838 
00839 bool
00840 TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
00841                                     bool &TailCallsAreMarkedTail,
00842                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00843                                     bool CannotTailCallElimCallsMarkedTail) {
00844   CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
00845   if (!CI)
00846     return false;
00847 
00848   return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
00849                                     ArgumentPHIs,
00850                                     CannotTailCallElimCallsMarkedTail);
00851 }