1 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file transforms calls of the current function (self recursion) followed
10 // by a return instruction with a branch to the entry of the function, creating
11 // a loop.  This pass also implements the following extensions to the basic
12 // algorithm:
13 //
14 //  1. Trivial instructions between the call and return do not prevent the
15 //     transformation from taking place, though currently the analysis cannot
16 //     support moving any really useful instructions (only dead ones).
17 //  2. This pass transforms functions that are prevented from being tail
18 //     recursive by an associative and commutative expression to use an
19 //     accumulator variable, thus compiling the typical naive factorial or
20 //     'fib' implementation into efficient code.
21 //  3. TRE is performed if the function returns void, if the return
22 //     returns the result returned by the call, or if the function returns a
23 //     run-time constant on all exits from the function.  It is possible, though
24 //     unlikely, that the return returns something else (like constant 0), and
25 //     can still be TRE'd.  It can be TRE'd if ALL OTHER return instructions in
26 //     the function return the exact same value.
27 //  4. If it can prove that callees do not access their caller stack frame,
28 //     they are marked as eligible for tail call elimination (by the code
29 //     generator).
30 //
31 // There are several improvements that could be made:
32 //
33 //  1. If the function has any alloca instructions, these instructions will be
34 //     moved out of the entry block of the function, causing them to be
35 //     evaluated each time through the tail recursion.  Safely keeping allocas
36 //     in the entry block requires analysis to proves that the tail-called
37 //     function does not read or write the stack object.
38 //  2. Tail recursion is only performed if the call immediately precedes the
39 //     return instruction.  It's possible that there could be a jump between
40 //     the call and the return.
41 //  3. There can be intervening operations between the call and the return that
42 //     prevent the TRE from occurring.  For example, there could be GEP's and
43 //     stores to memory that will not be read or written by the call.  This
44 //     requires some substantial analysis (such as with DSA) to prove safe to
45 //     move ahead of the call, but doing so could allow many more TREs to be
46 //     performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
47 //  4. The algorithm we use to detect if callees access their caller stack
48 //     frames is very primitive.
49 //
50 //===----------------------------------------------------------------------===//
51 
52 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/Analysis/CFG.h"
57 #include "llvm/Analysis/CaptureTracking.h"
58 #include "llvm/Analysis/DomTreeUpdater.h"
59 #include "llvm/Analysis/GlobalsModRef.h"
60 #include "llvm/Analysis/InlineCost.h"
61 #include "llvm/Analysis/InstructionSimplify.h"
62 #include "llvm/Analysis/Loads.h"
63 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
64 #include "llvm/Analysis/PostDominators.h"
65 #include "llvm/Analysis/TargetTransformInfo.h"
66 #include "llvm/IR/CFG.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/InstIterator.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Module.h"
77 #include "llvm/IR/ValueHandle.h"
78 #include "llvm/InitializePasses.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "tailcallelim"
87 
88 STATISTIC(NumEliminated, "Number of tail calls removed");
89 STATISTIC(NumRetDuped,   "Number of return duplicated");
90 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
91 
92 /// Scan the specified function for alloca instructions.
93 /// If it contains any dynamic allocas, returns false.
94 static bool canTRE(Function &F) {
95   // FIXME: The code generator produces really bad code when an 'escaping
96   // alloca' is changed from being a static alloca to being a dynamic alloca.
97   // Until this is resolved, disable this transformation if that would ever
98   // happen.  This bug is PR962.
99   return llvm::all_of(instructions(F), [](Instruction &I) {
100     auto *AI = dyn_cast<AllocaInst>(&I);
101     return !AI || AI->isStaticAlloca();
102   });
103 }
104 
105 namespace {
106 struct AllocaDerivedValueTracker {
107   // Start at a root value and walk its use-def chain to mark calls that use the
108   // value or a derived value in AllocaUsers, and places where it may escape in
109   // EscapePoints.
110   void walk(Value *Root) {
111     SmallVector<Use *, 32> Worklist;
112     SmallPtrSet<Use *, 32> Visited;
113 
114     auto AddUsesToWorklist = [&](Value *V) {
115       for (auto &U : V->uses()) {
116         if (!Visited.insert(&U).second)
117           continue;
118         Worklist.push_back(&U);
119       }
120     };
121 
122     AddUsesToWorklist(Root);
123 
124     while (!Worklist.empty()) {
125       Use *U = Worklist.pop_back_val();
126       Instruction *I = cast<Instruction>(U->getUser());
127 
128       switch (I->getOpcode()) {
129       case Instruction::Call:
130       case Instruction::Invoke: {
131         auto &CB = cast<CallBase>(*I);
132         // If the alloca-derived argument is passed byval it is not an escape
133         // point, or a use of an alloca. Calling with byval copies the contents
134         // of the alloca into argument registers or stack slots, which exist
135         // beyond the lifetime of the current frame.
136         if (CB.isArgOperand(U) && CB.isByValArgument(CB.getArgOperandNo(U)))
137           continue;
138         bool IsNocapture =
139             CB.isDataOperand(U) && CB.doesNotCapture(CB.getDataOperandNo(U));
140         callUsesLocalStack(CB, IsNocapture);
141         if (IsNocapture) {
142           // If the alloca-derived argument is passed in as nocapture, then it
143           // can't propagate to the call's return. That would be capturing.
144           continue;
145         }
146         break;
147       }
148       case Instruction::Load: {
149         // The result of a load is not alloca-derived (unless an alloca has
150         // otherwise escaped, but this is a local analysis).
151         continue;
152       }
153       case Instruction::Store: {
154         if (U->getOperandNo() == 0)
155           EscapePoints.insert(I);
156         continue;  // Stores have no users to analyze.
157       }
158       case Instruction::BitCast:
159       case Instruction::GetElementPtr:
160       case Instruction::PHI:
161       case Instruction::Select:
162       case Instruction::AddrSpaceCast:
163         break;
164       default:
165         EscapePoints.insert(I);
166         break;
167       }
168 
169       AddUsesToWorklist(I);
170     }
171   }
172 
173   void callUsesLocalStack(CallBase &CB, bool IsNocapture) {
174     // Add it to the list of alloca users.
175     AllocaUsers.insert(&CB);
176 
177     // If it's nocapture then it can't capture this alloca.
178     if (IsNocapture)
179       return;
180 
181     // If it can write to memory, it can leak the alloca value.
182     if (!CB.onlyReadsMemory())
183       EscapePoints.insert(&CB);
184   }
185 
186   SmallPtrSet<Instruction *, 32> AllocaUsers;
187   SmallPtrSet<Instruction *, 32> EscapePoints;
188 };
189 }
190 
191 static bool markTails(Function &F, bool &AllCallsAreTailCalls,
192                       OptimizationRemarkEmitter *ORE) {
193   if (F.callsFunctionThatReturnsTwice())
194     return false;
195   AllCallsAreTailCalls = true;
196 
197   // The local stack holds all alloca instructions and all byval arguments.
198   AllocaDerivedValueTracker Tracker;
199   for (Argument &Arg : F.args()) {
200     if (Arg.hasByValAttr())
201       Tracker.walk(&Arg);
202   }
203   for (auto &BB : F) {
204     for (auto &I : BB)
205       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
206         Tracker.walk(AI);
207   }
208 
209   bool Modified = false;
210 
211   // Track whether a block is reachable after an alloca has escaped. Blocks that
212   // contain the escaping instruction will be marked as being visited without an
213   // escaped alloca, since that is how the block began.
214   enum VisitType {
215     UNVISITED,
216     UNESCAPED,
217     ESCAPED
218   };
219   DenseMap<BasicBlock *, VisitType> Visited;
220 
221   // We propagate the fact that an alloca has escaped from block to successor.
222   // Visit the blocks that are propagating the escapedness first. To do this, we
223   // maintain two worklists.
224   SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
225 
226   // We may enter a block and visit it thinking that no alloca has escaped yet,
227   // then see an escape point and go back around a loop edge and come back to
228   // the same block twice. Because of this, we defer setting tail on calls when
229   // we first encounter them in a block. Every entry in this list does not
230   // statically use an alloca via use-def chain analysis, but may find an alloca
231   // through other means if the block turns out to be reachable after an escape
232   // point.
233   SmallVector<CallInst *, 32> DeferredTails;
234 
235   BasicBlock *BB = &F.getEntryBlock();
236   VisitType Escaped = UNESCAPED;
237   do {
238     for (auto &I : *BB) {
239       if (Tracker.EscapePoints.count(&I))
240         Escaped = ESCAPED;
241 
242       CallInst *CI = dyn_cast<CallInst>(&I);
243       if (!CI || CI->isTailCall() || isa<DbgInfoIntrinsic>(&I))
244         continue;
245 
246       bool IsNoTail = CI->isNoTailCall() || CI->hasOperandBundles();
247 
248       if (!IsNoTail && CI->doesNotAccessMemory()) {
249         // A call to a readnone function whose arguments are all things computed
250         // outside this function can be marked tail. Even if you stored the
251         // alloca address into a global, a readnone function can't load the
252         // global anyhow.
253         //
254         // Note that this runs whether we know an alloca has escaped or not. If
255         // it has, then we can't trust Tracker.AllocaUsers to be accurate.
256         bool SafeToTail = true;
257         for (auto &Arg : CI->arg_operands()) {
258           if (isa<Constant>(Arg.getUser()))
259             continue;
260           if (Argument *A = dyn_cast<Argument>(Arg.getUser()))
261             if (!A->hasByValAttr())
262               continue;
263           SafeToTail = false;
264           break;
265         }
266         if (SafeToTail) {
267           using namespace ore;
268           ORE->emit([&]() {
269             return OptimizationRemark(DEBUG_TYPE, "tailcall-readnone", CI)
270                    << "marked as tail call candidate (readnone)";
271           });
272           CI->setTailCall();
273           Modified = true;
274           continue;
275         }
276       }
277 
278       if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) {
279         DeferredTails.push_back(CI);
280       } else {
281         AllCallsAreTailCalls = false;
282       }
283     }
284 
285     for (auto *SuccBB : make_range(succ_begin(BB), succ_end(BB))) {
286       auto &State = Visited[SuccBB];
287       if (State < Escaped) {
288         State = Escaped;
289         if (State == ESCAPED)
290           WorklistEscaped.push_back(SuccBB);
291         else
292           WorklistUnescaped.push_back(SuccBB);
293       }
294     }
295 
296     if (!WorklistEscaped.empty()) {
297       BB = WorklistEscaped.pop_back_val();
298       Escaped = ESCAPED;
299     } else {
300       BB = nullptr;
301       while (!WorklistUnescaped.empty()) {
302         auto *NextBB = WorklistUnescaped.pop_back_val();
303         if (Visited[NextBB] == UNESCAPED) {
304           BB = NextBB;
305           Escaped = UNESCAPED;
306           break;
307         }
308       }
309     }
310   } while (BB);
311 
312   for (CallInst *CI : DeferredTails) {
313     if (Visited[CI->getParent()] != ESCAPED) {
314       // If the escape point was part way through the block, calls after the
315       // escape point wouldn't have been put into DeferredTails.
316       LLVM_DEBUG(dbgs() << "Marked as tail call candidate: " << *CI << "\n");
317       CI->setTailCall();
318       Modified = true;
319     } else {
320       AllCallsAreTailCalls = false;
321     }
322   }
323 
324   return Modified;
325 }
326 
327 /// Return true if it is safe to move the specified
328 /// instruction from after the call to before the call, assuming that all
329 /// instructions between the call and this instruction are movable.
330 ///
331 static bool canMoveAboveCall(Instruction *I, CallInst *CI, AliasAnalysis *AA) {
332   // FIXME: We can move load/store/call/free instructions above the call if the
333   // call does not mod/ref the memory location being processed.
334   if (I->mayHaveSideEffects())  // This also handles volatile loads.
335     return false;
336 
337   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
338     // Loads may always be moved above calls without side effects.
339     if (CI->mayHaveSideEffects()) {
340       // Non-volatile loads may be moved above a call with side effects if it
341       // does not write to memory and the load provably won't trap.
342       // Writes to memory only matter if they may alias the pointer
343       // being loaded from.
344       const DataLayout &DL = L->getModule()->getDataLayout();
345       if (isModSet(AA->getModRefInfo(CI, MemoryLocation::get(L))) ||
346           !isSafeToLoadUnconditionally(L->getPointerOperand(), L->getType(),
347                                        L->getAlign(), DL, L))
348         return false;
349     }
350   }
351 
352   // Otherwise, if this is a side-effect free instruction, check to make sure
353   // that it does not use the return value of the call.  If it doesn't use the
354   // return value of the call, it must only use things that are defined before
355   // the call, or movable instructions between the call and the instruction
356   // itself.
357   return !is_contained(I->operands(), CI);
358 }
359 
360 static bool canTransformAccumulatorRecursion(Instruction *I, CallInst *CI) {
361   if (!I->isAssociative() || !I->isCommutative())
362     return false;
363 
364   assert(I->getNumOperands() == 2 &&
365          "Associative/commutative operations should have 2 args!");
366 
367   // Exactly one operand should be the result of the call instruction.
368   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
369       (I->getOperand(0) != CI && I->getOperand(1) != CI))
370     return false;
371 
372   // The only user of this instruction we allow is a single return instruction.
373   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
374     return false;
375 
376   return true;
377 }
378 
379 static Instruction *firstNonDbg(BasicBlock::iterator I) {
380   while (isa<DbgInfoIntrinsic>(I))
381     ++I;
382   return &*I;
383 }
384 
385 namespace {
386 class TailRecursionEliminator {
387   Function &F;
388   const TargetTransformInfo *TTI;
389   AliasAnalysis *AA;
390   OptimizationRemarkEmitter *ORE;
391   DomTreeUpdater &DTU;
392 
393   // The below are shared state we want to have available when eliminating any
394   // calls in the function. There values should be populated by
395   // createTailRecurseLoopHeader the first time we find a call we can eliminate.
396   BasicBlock *HeaderBB = nullptr;
397   SmallVector<PHINode *, 8> ArgumentPHIs;
398   bool RemovableCallsMustBeMarkedTail = false;
399 
400   // PHI node to store our return value.
401   PHINode *RetPN = nullptr;
402 
403   // i1 PHI node to track if we have a valid return value stored in RetPN.
404   PHINode *RetKnownPN = nullptr;
405 
406   // Vector of select instructions we insereted. These selects use RetKnownPN
407   // to either propagate RetPN or select a new return value.
408   SmallVector<SelectInst *, 8> RetSelects;
409 
410   // The below are shared state needed when performing accumulator recursion.
411   // There values should be populated by insertAccumulator the first time we
412   // find an elimination that requires an accumulator.
413 
414   // PHI node to store our current accumulated value.
415   PHINode *AccPN = nullptr;
416 
417   // The instruction doing the accumulating.
418   Instruction *AccumulatorRecursionInstr = nullptr;
419 
420   TailRecursionEliminator(Function &F, const TargetTransformInfo *TTI,
421                           AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
422                           DomTreeUpdater &DTU)
423       : F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU) {}
424 
425   CallInst *findTRECandidate(BasicBlock *BB,
426                              bool CannotTailCallElimCallsMarkedTail);
427 
428   void createTailRecurseLoopHeader(CallInst *CI);
429 
430   void insertAccumulator(Instruction *AccRecInstr);
431 
432   bool eliminateCall(CallInst *CI);
433 
434   void cleanupAndFinalize();
435 
436   bool processBlock(BasicBlock &BB, bool CannotTailCallElimCallsMarkedTail);
437 
438 public:
439   static bool eliminate(Function &F, const TargetTransformInfo *TTI,
440                         AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
441                         DomTreeUpdater &DTU);
442 };
443 } // namespace
444 
445 CallInst *TailRecursionEliminator::findTRECandidate(
446     BasicBlock *BB, bool CannotTailCallElimCallsMarkedTail) {
447   Instruction *TI = BB->getTerminator();
448 
449   if (&BB->front() == TI) // Make sure there is something before the terminator.
450     return nullptr;
451 
452   // Scan backwards from the return, checking to see if there is a tail call in
453   // this block.  If so, set CI to it.
454   CallInst *CI = nullptr;
455   BasicBlock::iterator BBI(TI);
456   while (true) {
457     CI = dyn_cast<CallInst>(BBI);
458     if (CI && CI->getCalledFunction() == &F)
459       break;
460 
461     if (BBI == BB->begin())
462       return nullptr;          // Didn't find a potential tail call.
463     --BBI;
464   }
465 
466   // If this call is marked as a tail call, and if there are dynamic allocas in
467   // the function, we cannot perform this optimization.
468   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
469     return nullptr;
470 
471   // As a special case, detect code like this:
472   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
473   // and disable this xform in this case, because the code generator will
474   // lower the call to fabs into inline code.
475   if (BB == &F.getEntryBlock() &&
476       firstNonDbg(BB->front().getIterator()) == CI &&
477       firstNonDbg(std::next(BB->begin())) == TI && CI->getCalledFunction() &&
478       !TTI->isLoweredToCall(CI->getCalledFunction())) {
479     // A single-block function with just a call and a return. Check that
480     // the arguments match.
481     auto I = CI->arg_begin(), E = CI->arg_end();
482     Function::arg_iterator FI = F.arg_begin(), FE = F.arg_end();
483     for (; I != E && FI != FE; ++I, ++FI)
484       if (*I != &*FI) break;
485     if (I == E && FI == FE)
486       return nullptr;
487   }
488 
489   return CI;
490 }
491 
492 void TailRecursionEliminator::createTailRecurseLoopHeader(CallInst *CI) {
493   HeaderBB = &F.getEntryBlock();
494   BasicBlock *NewEntry = BasicBlock::Create(F.getContext(), "", &F, HeaderBB);
495   NewEntry->takeName(HeaderBB);
496   HeaderBB->setName("tailrecurse");
497   BranchInst *BI = BranchInst::Create(HeaderBB, NewEntry);
498   BI->setDebugLoc(CI->getDebugLoc());
499 
500   // If this function has self recursive calls in the tail position where some
501   // are marked tail and some are not, only transform one flavor or another.
502   // We have to choose whether we move allocas in the entry block to the new
503   // entry block or not, so we can't make a good choice for both. We make this
504   // decision here based on whether the first call we found to remove is
505   // marked tail.
506   // NOTE: We could do slightly better here in the case that the function has
507   // no entry block allocas.
508   RemovableCallsMustBeMarkedTail = CI->isTailCall();
509 
510   // If this tail call is marked 'tail' and if there are any allocas in the
511   // entry block, move them up to the new entry block.
512   if (RemovableCallsMustBeMarkedTail)
513     // Move all fixed sized allocas from HeaderBB to NewEntry.
514     for (BasicBlock::iterator OEBI = HeaderBB->begin(), E = HeaderBB->end(),
515                               NEBI = NewEntry->begin();
516          OEBI != E;)
517       if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
518         if (isa<ConstantInt>(AI->getArraySize()))
519           AI->moveBefore(&*NEBI);
520 
521   // Now that we have created a new block, which jumps to the entry
522   // block, insert a PHI node for each argument of the function.
523   // For now, we initialize each PHI to only have the real arguments
524   // which are passed in.
525   Instruction *InsertPos = &HeaderBB->front();
526   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
527     PHINode *PN =
528         PHINode::Create(I->getType(), 2, I->getName() + ".tr", InsertPos);
529     I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
530     PN->addIncoming(&*I, NewEntry);
531     ArgumentPHIs.push_back(PN);
532   }
533 
534   // If the function doen't return void, create the RetPN and RetKnownPN PHI
535   // nodes to track our return value. We initialize RetPN with undef and
536   // RetKnownPN with false since we can't know our return value at function
537   // entry.
538   Type *RetType = F.getReturnType();
539   if (!RetType->isVoidTy()) {
540     Type *BoolType = Type::getInt1Ty(F.getContext());
541     RetPN = PHINode::Create(RetType, 2, "ret.tr", InsertPos);
542     RetKnownPN = PHINode::Create(BoolType, 2, "ret.known.tr", InsertPos);
543 
544     RetPN->addIncoming(UndefValue::get(RetType), NewEntry);
545     RetKnownPN->addIncoming(ConstantInt::getFalse(BoolType), NewEntry);
546   }
547 
548   // The entry block was changed from HeaderBB to NewEntry.
549   // The forward DominatorTree needs to be recalculated when the EntryBB is
550   // changed. In this corner-case we recalculate the entire tree.
551   DTU.recalculate(*NewEntry->getParent());
552 }
553 
554 void TailRecursionEliminator::insertAccumulator(Instruction *AccRecInstr) {
555   assert(!AccPN && "Trying to insert multiple accumulators");
556 
557   AccumulatorRecursionInstr = AccRecInstr;
558 
559   // Start by inserting a new PHI node for the accumulator.
560   pred_iterator PB = pred_begin(HeaderBB), PE = pred_end(HeaderBB);
561   AccPN = PHINode::Create(F.getReturnType(), std::distance(PB, PE) + 1,
562                           "accumulator.tr", &HeaderBB->front());
563 
564   // Loop over all of the predecessors of the tail recursion block.  For the
565   // real entry into the function we seed the PHI with the identity constant for
566   // the accumulation operation.  For any other existing branches to this block
567   // (due to other tail recursions eliminated) the accumulator is not modified.
568   // Because we haven't added the branch in the current block to HeaderBB yet,
569   // it will not show up as a predecessor.
570   for (pred_iterator PI = PB; PI != PE; ++PI) {
571     BasicBlock *P = *PI;
572     if (P == &F.getEntryBlock()) {
573       Constant *Identity = ConstantExpr::getBinOpIdentity(
574           AccRecInstr->getOpcode(), AccRecInstr->getType());
575       AccPN->addIncoming(Identity, P);
576     } else {
577       AccPN->addIncoming(AccPN, P);
578     }
579   }
580 
581   ++NumAccumAdded;
582 }
583 
584 bool TailRecursionEliminator::eliminateCall(CallInst *CI) {
585   ReturnInst *Ret = cast<ReturnInst>(CI->getParent()->getTerminator());
586 
587   // Ok, we found a potential tail call.  We can currently only transform the
588   // tail call if all of the instructions between the call and the return are
589   // movable to above the call itself, leaving the call next to the return.
590   // Check that this is the case now.
591   Instruction *AccRecInstr = nullptr;
592   BasicBlock::iterator BBI(CI);
593   for (++BBI; &*BBI != Ret; ++BBI) {
594     if (canMoveAboveCall(&*BBI, CI, AA))
595       continue;
596 
597     // If we can't move the instruction above the call, it might be because it
598     // is an associative and commutative operation that could be transformed
599     // using accumulator recursion elimination.  Check to see if this is the
600     // case, and if so, remember which instruction accumulates for later.
601     if (AccPN || !canTransformAccumulatorRecursion(&*BBI, CI))
602       return false; // We cannot eliminate the tail recursion!
603 
604     // Yes, this is accumulator recursion.  Remember which instruction
605     // accumulates.
606     AccRecInstr = &*BBI;
607   }
608 
609   BasicBlock *BB = Ret->getParent();
610 
611   using namespace ore;
612   ORE->emit([&]() {
613     return OptimizationRemark(DEBUG_TYPE, "tailcall-recursion", CI)
614            << "transforming tail recursion into loop";
615   });
616 
617   // OK! We can transform this tail call.  If this is the first one found,
618   // create the new entry block, allowing us to branch back to the old entry.
619   if (!HeaderBB)
620     createTailRecurseLoopHeader(CI);
621 
622   if (RemovableCallsMustBeMarkedTail && !CI->isTailCall())
623     return false;
624 
625   // Ok, now that we know we have a pseudo-entry block WITH all of the
626   // required PHI nodes, add entries into the PHI node for the actual
627   // parameters passed into the tail-recursive call.
628   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
629     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
630 
631   if (AccRecInstr) {
632     insertAccumulator(AccRecInstr);
633 
634     // Rewrite the accumulator recursion instruction so that it does not use
635     // the result of the call anymore, instead, use the PHI node we just
636     // inserted.
637     AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
638   }
639 
640   // Update our return value tracking
641   if (RetPN) {
642     if (Ret->getReturnValue() == CI || AccRecInstr) {
643       // Defer selecting a return value
644       RetPN->addIncoming(RetPN, BB);
645       RetKnownPN->addIncoming(RetKnownPN, BB);
646     } else {
647       // We found a return value we want to use, insert a select instruction to
648       // select it if we don't already know what our return value will be and
649       // store the result in our return value PHI node.
650       SelectInst *SI = SelectInst::Create(
651           RetKnownPN, RetPN, Ret->getReturnValue(), "current.ret.tr", Ret);
652       RetSelects.push_back(SI);
653 
654       RetPN->addIncoming(SI, BB);
655       RetKnownPN->addIncoming(ConstantInt::getTrue(RetKnownPN->getType()), BB);
656     }
657 
658     if (AccPN)
659       AccPN->addIncoming(AccRecInstr ? AccRecInstr : AccPN, BB);
660   }
661 
662   // Now that all of the PHI nodes are in place, remove the call and
663   // ret instructions, replacing them with an unconditional branch.
664   BranchInst *NewBI = BranchInst::Create(HeaderBB, Ret);
665   NewBI->setDebugLoc(CI->getDebugLoc());
666 
667   BB->getInstList().erase(Ret);  // Remove return.
668   BB->getInstList().erase(CI);   // Remove call.
669   DTU.applyUpdates({{DominatorTree::Insert, BB, HeaderBB}});
670   ++NumEliminated;
671   return true;
672 }
673 
674 void TailRecursionEliminator::cleanupAndFinalize() {
675   // If we eliminated any tail recursions, it's possible that we inserted some
676   // silly PHI nodes which just merge an initial value (the incoming operand)
677   // with themselves.  Check to see if we did and clean up our mess if so.  This
678   // occurs when a function passes an argument straight through to its tail
679   // call.
680   for (PHINode *PN : ArgumentPHIs) {
681     // If the PHI Node is a dynamic constant, replace it with the value it is.
682     if (Value *PNV = SimplifyInstruction(PN, F.getParent()->getDataLayout())) {
683       PN->replaceAllUsesWith(PNV);
684       PN->eraseFromParent();
685     }
686   }
687 
688   if (RetPN) {
689     if (RetSelects.empty()) {
690       // If we didn't insert any select instructions, then we know we didn't
691       // store a return value and we can remove the PHI nodes we inserted.
692       RetPN->dropAllReferences();
693       RetPN->eraseFromParent();
694 
695       RetKnownPN->dropAllReferences();
696       RetKnownPN->eraseFromParent();
697 
698       if (AccPN) {
699         // We need to insert a copy of our accumulator instruction before any
700         // return in the function, and return its result instead.
701         Instruction *AccRecInstr = AccumulatorRecursionInstr;
702         for (BasicBlock &BB : F) {
703           ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
704           if (!RI)
705             continue;
706 
707           Instruction *AccRecInstrNew = AccRecInstr->clone();
708           AccRecInstrNew->setName("accumulator.ret.tr");
709           AccRecInstrNew->setOperand(AccRecInstr->getOperand(0) == AccPN,
710                                      RI->getOperand(0));
711           AccRecInstrNew->insertBefore(RI);
712           RI->setOperand(0, AccRecInstrNew);
713         }
714       }
715     } else {
716       // We need to insert a select instruction before any return left in the
717       // function to select our stored return value if we have one.
718       for (BasicBlock &BB : F) {
719         ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator());
720         if (!RI)
721           continue;
722 
723         SelectInst *SI = SelectInst::Create(
724             RetKnownPN, RetPN, RI->getOperand(0), "current.ret.tr", RI);
725         RetSelects.push_back(SI);
726         RI->setOperand(0, SI);
727       }
728 
729       if (AccPN) {
730         // We need to insert a copy of our accumulator instruction before any
731         // of the selects we inserted, and select its result instead.
732         Instruction *AccRecInstr = AccumulatorRecursionInstr;
733         for (SelectInst *SI : RetSelects) {
734           Instruction *AccRecInstrNew = AccRecInstr->clone();
735           AccRecInstrNew->setName("accumulator.ret.tr");
736           AccRecInstrNew->setOperand(AccRecInstr->getOperand(0) == AccPN,
737                                      SI->getFalseValue());
738           AccRecInstrNew->insertBefore(SI);
739           SI->setFalseValue(AccRecInstrNew);
740         }
741       }
742     }
743   }
744 }
745 
746 bool TailRecursionEliminator::processBlock(
747     BasicBlock &BB, bool CannotTailCallElimCallsMarkedTail) {
748   Instruction *TI = BB.getTerminator();
749 
750   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
751     if (BI->isConditional())
752       return false;
753 
754     BasicBlock *Succ = BI->getSuccessor(0);
755     ReturnInst *Ret = dyn_cast<ReturnInst>(Succ->getFirstNonPHIOrDbg());
756 
757     if (!Ret)
758       return false;
759 
760     CallInst *CI = findTRECandidate(&BB, CannotTailCallElimCallsMarkedTail);
761 
762     if (!CI)
763       return false;
764 
765     LLVM_DEBUG(dbgs() << "FOLDING: " << *Succ
766                       << "INTO UNCOND BRANCH PRED: " << BB);
767     FoldReturnIntoUncondBranch(Ret, Succ, &BB, &DTU);
768     ++NumRetDuped;
769 
770     // If all predecessors of Succ have been eliminated by
771     // FoldReturnIntoUncondBranch, delete it.  It is important to empty it,
772     // because the ret instruction in there is still using a value which
773     // eliminateCall will attempt to remove.  This block can only contain
774     // instructions that can't have uses, therefore it is safe to remove.
775     if (pred_empty(Succ))
776       DTU.deleteBB(Succ);
777 
778     eliminateCall(CI);
779     return true;
780   } else if (isa<ReturnInst>(TI)) {
781     CallInst *CI = findTRECandidate(&BB, CannotTailCallElimCallsMarkedTail);
782 
783     if (CI)
784       return eliminateCall(CI);
785   }
786 
787   return false;
788 }
789 
790 bool TailRecursionEliminator::eliminate(Function &F,
791                                         const TargetTransformInfo *TTI,
792                                         AliasAnalysis *AA,
793                                         OptimizationRemarkEmitter *ORE,
794                                         DomTreeUpdater &DTU) {
795   if (F.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
796     return false;
797 
798   bool MadeChange = false;
799   bool AllCallsAreTailCalls = false;
800   MadeChange |= markTails(F, AllCallsAreTailCalls, ORE);
801   if (!AllCallsAreTailCalls)
802     return MadeChange;
803 
804   // If this function is a varargs function, we won't be able to PHI the args
805   // right, so don't even try to convert it...
806   if (F.getFunctionType()->isVarArg())
807     return MadeChange;
808 
809   // If false, we cannot perform TRE on tail calls marked with the 'tail'
810   // attribute, because doing so would cause the stack size to increase (real
811   // TRE would deallocate variable sized allocas, TRE doesn't).
812   bool CanTRETailMarkedCall = canTRE(F);
813 
814   // Change any tail recursive calls to loops.
815   TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU);
816 
817   for (BasicBlock &BB : F)
818     MadeChange |= TRE.processBlock(BB, !CanTRETailMarkedCall);
819 
820   TRE.cleanupAndFinalize();
821 
822   return MadeChange;
823 }
824 
825 namespace {
826 struct TailCallElim : public FunctionPass {
827   static char ID; // Pass identification, replacement for typeid
828   TailCallElim() : FunctionPass(ID) {
829     initializeTailCallElimPass(*PassRegistry::getPassRegistry());
830   }
831 
832   void getAnalysisUsage(AnalysisUsage &AU) const override {
833     AU.addRequired<TargetTransformInfoWrapperPass>();
834     AU.addRequired<AAResultsWrapperPass>();
835     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
836     AU.addPreserved<GlobalsAAWrapperPass>();
837     AU.addPreserved<DominatorTreeWrapperPass>();
838     AU.addPreserved<PostDominatorTreeWrapperPass>();
839   }
840 
841   bool runOnFunction(Function &F) override {
842     if (skipFunction(F))
843       return false;
844 
845     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
846     auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
847     auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
848     auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
849     // There is no noticable performance difference here between Lazy and Eager
850     // UpdateStrategy based on some test results. It is feasible to switch the
851     // UpdateStrategy to Lazy if we find it profitable later.
852     DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
853 
854     return TailRecursionEliminator::eliminate(
855         F, &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
856         &getAnalysis<AAResultsWrapperPass>().getAAResults(),
857         &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU);
858   }
859 };
860 }
861 
862 char TailCallElim::ID = 0;
863 INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim", "Tail Call Elimination",
864                       false, false)
865 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
866 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
867 INITIALIZE_PASS_END(TailCallElim, "tailcallelim", "Tail Call Elimination",
868                     false, false)
869 
870 // Public interface to the TailCallElimination pass
871 FunctionPass *llvm::createTailCallEliminationPass() {
872   return new TailCallElim();
873 }
874 
875 PreservedAnalyses TailCallElimPass::run(Function &F,
876                                         FunctionAnalysisManager &AM) {
877 
878   TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
879   AliasAnalysis &AA = AM.getResult<AAManager>(F);
880   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
881   auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
882   auto *PDT = AM.getCachedResult<PostDominatorTreeAnalysis>(F);
883   // There is no noticable performance difference here between Lazy and Eager
884   // UpdateStrategy based on some test results. It is feasible to switch the
885   // UpdateStrategy to Lazy if we find it profitable later.
886   DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
887   bool Changed = TailRecursionEliminator::eliminate(F, &TTI, &AA, &ORE, DTU);
888 
889   if (!Changed)
890     return PreservedAnalyses::all();
891   PreservedAnalyses PA;
892   PA.preserve<GlobalsAA>();
893   PA.preserve<DominatorTreeAnalysis>();
894   PA.preserve<PostDominatorTreeAnalysis>();
895   return PA;
896 }
897