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