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