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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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 expression to use an accumulator variable,
00020 //     thus compiling the typical naive factorial or 'fib' implementation into
00021 //     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 theier 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 preceeds 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/Constants.h"
00055 #include "llvm/DerivedTypes.h"
00056 #include "llvm/Function.h"
00057 #include "llvm/Instructions.h"
00058 #include "llvm/Pass.h"
00059 #include "llvm/Support/CFG.h"
00060 #include "llvm/ADT/Statistic.h"
00061 using namespace llvm;
00062 
00063 namespace {
00064   Statistic<> NumEliminated("tailcallelim", "Number of tail calls removed");
00065   Statistic<> NumAccumAdded("tailcallelim","Number of accumulators introduced");
00066 
00067   struct TailCallElim : public FunctionPass {
00068     virtual bool runOnFunction(Function &F);
00069 
00070   private:
00071     bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
00072                                bool &TailCallsAreMarkedTail,
00073                                std::vector<PHINode*> &ArgumentPHIs,
00074                                bool CannotTailCallElimCallsMarkedTail);
00075     bool CanMoveAboveCall(Instruction *I, CallInst *CI);
00076     Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
00077   };
00078   RegisterOpt<TailCallElim> X("tailcallelim", "Tail Call Elimination");
00079 }
00080 
00081 // Public interface to the TailCallElimination pass
00082 FunctionPass *llvm::createTailCallEliminationPass() {
00083   return new TailCallElim();
00084 }
00085 
00086 
00087 /// AllocaMightEscapeToCalls - Return true if this alloca may be accessed by
00088 /// callees of this function.  We only do very simple analysis right now, this
00089 /// could be expanded in the future to use mod/ref information for particular
00090 /// call sites if desired.
00091 static bool AllocaMightEscapeToCalls(AllocaInst *AI) {
00092   // FIXME: do simple 'address taken' analysis.
00093   return true;
00094 }
00095 
00096 /// FunctionContainsAllocas - Scan the specified basic block for alloca
00097 /// instructions.  If it contains any that might be accessed by calls, return
00098 /// true.
00099 static bool CheckForEscapingAllocas(BasicBlock *BB,
00100                                     bool &CannotTCETailMarkedCall) {
00101   bool RetVal = false;
00102   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00103     if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
00104       RetVal |= AllocaMightEscapeToCalls(AI);
00105 
00106       // If this alloca is in the body of the function, or if it is a variable
00107       // sized allocation, we cannot tail call eliminate calls marked 'tail'
00108       // with this mechanism.
00109       if (BB != &BB->getParent()->front() ||
00110           !isa<ConstantInt>(AI->getArraySize()))
00111         CannotTCETailMarkedCall = true;
00112     }
00113   return RetVal;
00114 }
00115 
00116 bool TailCallElim::runOnFunction(Function &F) {
00117   // If this function is a varargs function, we won't be able to PHI the args
00118   // right, so don't even try to convert it...
00119   if (F.getFunctionType()->isVarArg()) return false;
00120 
00121   BasicBlock *OldEntry = 0;
00122   bool TailCallsAreMarkedTail = false;
00123   std::vector<PHINode*> ArgumentPHIs;
00124   bool MadeChange = false;
00125 
00126   bool FunctionContainsEscapingAllocas = false;
00127 
00128   // CannotTCETailMarkedCall - If true, we cannot perform TCE on tail calls
00129   // marked with the 'tail' attribute, because doing so would cause the stack
00130   // size to increase (real TCE would deallocate variable sized allocas, TCE
00131   // doesn't).
00132   bool CannotTCETailMarkedCall = false;
00133 
00134   // Loop over the function, looking for any returning blocks, and keeping track
00135   // of whether this function has any non-trivially used allocas.
00136   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00137     if (FunctionContainsEscapingAllocas && CannotTCETailMarkedCall)
00138       break;
00139 
00140     FunctionContainsEscapingAllocas |=
00141       CheckForEscapingAllocas(BB, CannotTCETailMarkedCall);
00142   }
00143 
00144   // Second pass, change any tail calls to loops.
00145   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00146     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator()))
00147       MadeChange |= ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
00148                                           ArgumentPHIs,CannotTCETailMarkedCall);
00149 
00150   // If we eliminated any tail recursions, it's possible that we inserted some
00151   // silly PHI nodes which just merge an initial value (the incoming operand)
00152   // with themselves.  Check to see if we did and clean up our mess if so.  This
00153   // occurs when a function passes an argument straight through to its tail
00154   // call.
00155   if (!ArgumentPHIs.empty()) {
00156     unsigned NumIncoming = ArgumentPHIs[0]->getNumIncomingValues();
00157     for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
00158       PHINode *PN = ArgumentPHIs[i];
00159 
00160       // If the PHI Node is a dynamic constant, replace it with the value it is.
00161       if (Value *PNV = PN->hasConstantValue()) {
00162         PN->replaceAllUsesWith(PNV);
00163         PN->eraseFromParent();
00164       }
00165     }
00166   }
00167 
00168   // Finally, if this function contains no non-escaping allocas, mark all calls
00169   // in the function as eligible for tail calls (there is no stack memory for
00170   // them to access).
00171   if (!FunctionContainsEscapingAllocas)
00172     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00173       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00174         if (CallInst *CI = dyn_cast<CallInst>(I))
00175           CI->setTailCall();
00176 
00177   return MadeChange;
00178 }
00179 
00180 
00181 /// CanMoveAboveCall - Return true if it is safe to move the specified
00182 /// instruction from after the call to before the call, assuming that all
00183 /// instructions between the call and this instruction are movable.
00184 ///
00185 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
00186   // FIXME: We can move load/store/call/free instructions above the call if the
00187   // call does not mod/ref the memory location being processed.
00188   if (I->mayWriteToMemory() || isa<LoadInst>(I))
00189     return false;
00190 
00191   // Otherwise, if this is a side-effect free instruction, check to make sure
00192   // that it does not use the return value of the call.  If it doesn't use the
00193   // return value of the call, it must only use things that are defined before
00194   // the call, or movable instructions between the call and the instruction
00195   // itself.
00196   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00197     if (I->getOperand(i) == CI)
00198       return false;
00199   return true;
00200 }
00201 
00202 // isDynamicConstant - Return true if the specified value is the same when the
00203 // return would exit as it was when the initial iteration of the recursive
00204 // function was executed.
00205 //
00206 // We currently handle static constants and arguments that are not modified as
00207 // part of the recursion.
00208 //
00209 static bool isDynamicConstant(Value *V, CallInst *CI) {
00210   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
00211 
00212   // Check to see if this is an immutable argument, if so, the value
00213   // will be available to initialize the accumulator.
00214   if (Argument *Arg = dyn_cast<Argument>(V)) {
00215     // Figure out which argument number this is...
00216     unsigned ArgNo = 0;
00217     Function *F = CI->getParent()->getParent();
00218     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
00219       ++ArgNo;
00220 
00221     // If we are passing this argument into call as the corresponding
00222     // argument operand, then the argument is dynamically constant.
00223     // Otherwise, we cannot transform this function safely.
00224     if (CI->getOperand(ArgNo+1) == Arg)
00225       return true;
00226   }
00227   // Not a constant or immutable argument, we can't safely transform.
00228   return false;
00229 }
00230 
00231 // getCommonReturnValue - Check to see if the function containing the specified
00232 // return instruction and tail call consistently returns the same
00233 // runtime-constant value at all exit points.  If so, return the returned value.
00234 //
00235 static Value *getCommonReturnValue(ReturnInst *TheRI, CallInst *CI) {
00236   Function *F = TheRI->getParent()->getParent();
00237   Value *ReturnedValue = 0;
00238 
00239   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00240     if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00241       if (RI != TheRI) {
00242         Value *RetOp = RI->getOperand(0);
00243 
00244         // We can only perform this transformation if the value returned is
00245         // evaluatable at the start of the initial invocation of the function,
00246         // instead of at the end of the evaluation.
00247         //
00248         if (!isDynamicConstant(RetOp, CI))
00249           return 0;
00250 
00251         if (ReturnedValue && RetOp != ReturnedValue)
00252           return 0;     // Cannot transform if differing values are returned.
00253         ReturnedValue = RetOp;
00254       }
00255   return ReturnedValue;
00256 }
00257 
00258 /// CanTransformAccumulatorRecursion - If the specified instruction can be
00259 /// transformed using accumulator recursion elimination, return the constant
00260 /// which is the start of the accumulator value.  Otherwise return null.
00261 ///
00262 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
00263                                                       CallInst *CI) {
00264   if (!I->isAssociative()) return 0;
00265   assert(I->getNumOperands() == 2 &&
00266          "Associative operations should have 2 args!");
00267 
00268   // Exactly one operand should be the result of the call instruction...
00269   if (I->getOperand(0) == CI && I->getOperand(1) == CI ||
00270       I->getOperand(0) != CI && I->getOperand(1) != CI)
00271     return 0;
00272 
00273   // The only user of this instruction we allow is a single return instruction.
00274   if (!I->hasOneUse() || !isa<ReturnInst>(I->use_back()))
00275     return 0;
00276 
00277   // Ok, now we have to check all of the other return instructions in this
00278   // function.  If they return non-constants or differing values, then we cannot
00279   // transform the function safely.
00280   return getCommonReturnValue(cast<ReturnInst>(I->use_back()), CI);
00281 }
00282 
00283 bool TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
00284                                          bool &TailCallsAreMarkedTail,
00285                                          std::vector<PHINode*> &ArgumentPHIs,
00286                                        bool CannotTailCallElimCallsMarkedTail) {
00287   BasicBlock *BB = Ret->getParent();
00288   Function *F = BB->getParent();
00289 
00290   if (&BB->front() == Ret) // Make sure there is something before the ret...
00291     return false;
00292 
00293   // Scan backwards from the return, checking to see if there is a tail call in
00294   // this block.  If so, set CI to it.
00295   CallInst *CI;
00296   BasicBlock::iterator BBI = Ret;
00297   while (1) {
00298     CI = dyn_cast<CallInst>(BBI);
00299     if (CI && CI->getCalledFunction() == F)
00300       break;
00301 
00302     if (BBI == BB->begin())
00303       return false;          // Didn't find a potential tail call.
00304     --BBI;
00305   }
00306 
00307   // If this call is marked as a tail call, and if there are dynamic allocas in
00308   // the function, we cannot perform this optimization.
00309   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
00310     return false;
00311 
00312   // If we are introducing accumulator recursion to eliminate associative
00313   // operations after the call instruction, this variable contains the initial
00314   // value for the accumulator.  If this value is set, we actually perform
00315   // accumulator recursion elimination instead of simple tail recursion
00316   // elimination.
00317   Value *AccumulatorRecursionEliminationInitVal = 0;
00318   Instruction *AccumulatorRecursionInstr = 0;
00319 
00320   // Ok, we found a potential tail call.  We can currently only transform the
00321   // tail call if all of the instructions between the call and the return are
00322   // movable to above the call itself, leaving the call next to the return.
00323   // Check that this is the case now.
00324   for (BBI = CI, ++BBI; &*BBI != Ret; ++BBI)
00325     if (!CanMoveAboveCall(BBI, CI)) {
00326       // If we can't move the instruction above the call, it might be because it
00327       // is an associative operation that could be tranformed using accumulator
00328       // recursion elimination.  Check to see if this is the case, and if so,
00329       // remember the initial accumulator value for later.
00330       if ((AccumulatorRecursionEliminationInitVal =
00331                              CanTransformAccumulatorRecursion(BBI, CI))) {
00332         // Yes, this is accumulator recursion.  Remember which instruction
00333         // accumulates.
00334         AccumulatorRecursionInstr = BBI;
00335       } else {
00336         return false;   // Otherwise, we cannot eliminate the tail recursion!
00337       }
00338     }
00339 
00340   // We can only transform call/return pairs that either ignore the return value
00341   // of the call and return void, ignore the value of the call and return a
00342   // constant, return the value returned by the tail call, or that are being
00343   // accumulator recursion variable eliminated.
00344   if (Ret->getNumOperands() != 0 && Ret->getReturnValue() != CI &&
00345       !isa<UndefValue>(Ret->getReturnValue()) &&
00346       AccumulatorRecursionEliminationInitVal == 0 &&
00347       !getCommonReturnValue(Ret, CI))
00348     return false;
00349 
00350   // OK! We can transform this tail call.  If this is the first one found,
00351   // create the new entry block, allowing us to branch back to the old entry.
00352   if (OldEntry == 0) {
00353     OldEntry = &F->getEntryBlock();
00354     std::string OldName = OldEntry->getName(); OldEntry->setName("tailrecurse");
00355     BasicBlock *NewEntry = new BasicBlock(OldName, F, OldEntry);
00356     new BranchInst(OldEntry, NewEntry);
00357 
00358     // If this tail call is marked 'tail' and if there are any allocas in the
00359     // entry block, move them up to the new entry block.
00360     TailCallsAreMarkedTail = CI->isTailCall();
00361     if (TailCallsAreMarkedTail)
00362       // Move all fixed sized allocas from OldEntry to NewEntry.
00363       for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
00364              NEBI = NewEntry->begin(); OEBI != E; )
00365         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
00366           if (isa<ConstantInt>(AI->getArraySize()))
00367             AI->moveBefore(NEBI);
00368 
00369     // Now that we have created a new block, which jumps to the entry
00370     // block, insert a PHI node for each argument of the function.
00371     // For now, we initialize each PHI to only have the real arguments
00372     // which are passed in.
00373     Instruction *InsertPos = OldEntry->begin();
00374     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00375          I != E; ++I) {
00376       PHINode *PN = new PHINode(I->getType(), I->getName()+".tr", InsertPos);
00377       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
00378       PN->addIncoming(I, NewEntry);
00379       ArgumentPHIs.push_back(PN);
00380     }
00381   }
00382 
00383   // If this function has self recursive calls in the tail position where some
00384   // are marked tail and some are not, only transform one flavor or another.  We
00385   // have to choose whether we move allocas in the entry block to the new entry
00386   // block or not, so we can't make a good choice for both.  NOTE: We could do
00387   // slightly better here in the case that the function has no entry block
00388   // allocas.
00389   if (TailCallsAreMarkedTail && !CI->isTailCall())
00390     return false;
00391 
00392   // Ok, now that we know we have a pseudo-entry block WITH all of the
00393   // required PHI nodes, add entries into the PHI node for the actual
00394   // parameters passed into the tail-recursive call.
00395   for (unsigned i = 0, e = CI->getNumOperands()-1; i != e; ++i)
00396     ArgumentPHIs[i]->addIncoming(CI->getOperand(i+1), BB);
00397 
00398   // If we are introducing an accumulator variable to eliminate the recursion,
00399   // do so now.  Note that we _know_ that no subsequent tail recursion
00400   // eliminations will happen on this function because of the way the
00401   // accumulator recursion predicate is set up.
00402   //
00403   if (AccumulatorRecursionEliminationInitVal) {
00404     Instruction *AccRecInstr = AccumulatorRecursionInstr;
00405     // Start by inserting a new PHI node for the accumulator.
00406     PHINode *AccPN = new PHINode(AccRecInstr->getType(), "accumulator.tr",
00407                                  OldEntry->begin());
00408 
00409     // Loop over all of the predecessors of the tail recursion block.  For the
00410     // real entry into the function we seed the PHI with the initial value,
00411     // computed earlier.  For any other existing branches to this block (due to
00412     // other tail recursions eliminated) the accumulator is not modified.
00413     // Because we haven't added the branch in the current block to OldEntry yet,
00414     // it will not show up as a predecessor.
00415     for (pred_iterator PI = pred_begin(OldEntry), PE = pred_end(OldEntry);
00416          PI != PE; ++PI) {
00417       if (*PI == &F->getEntryBlock())
00418         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, *PI);
00419       else
00420         AccPN->addIncoming(AccPN, *PI);
00421     }
00422 
00423     // Add an incoming argument for the current block, which is computed by our
00424     // associative accumulator instruction.
00425     AccPN->addIncoming(AccRecInstr, BB);
00426 
00427     // Next, rewrite the accumulator recursion instruction so that it does not
00428     // use the result of the call anymore, instead, use the PHI node we just
00429     // inserted.
00430     AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
00431 
00432     // Finally, rewrite any return instructions in the program to return the PHI
00433     // node instead of the "initval" that they do currently.  This loop will
00434     // actually rewrite the return value we are destroying, but that's ok.
00435     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00436       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00437         RI->setOperand(0, AccPN);
00438     ++NumAccumAdded;
00439   }
00440 
00441   // Now that all of the PHI nodes are in place, remove the call and
00442   // ret instructions, replacing them with an unconditional branch.
00443   new BranchInst(OldEntry, Ret);
00444   BB->getInstList().erase(Ret);  // Remove return.
00445   BB->getInstList().erase(CI);   // Remove call.
00446   ++NumEliminated;
00447   return true;
00448 }