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