15ffd83dbSDimitry Andric //===- UnifyLoopExits.cpp - Redirect exiting edges to one block -*- C++ -*-===// 25ffd83dbSDimitry Andric // 35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 65ffd83dbSDimitry Andric // 75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===// 85ffd83dbSDimitry Andric // 95ffd83dbSDimitry Andric // For each natural loop with multiple exit blocks, this pass creates a new 105ffd83dbSDimitry Andric // block N such that all exiting blocks now branch to N, and then control flow 115ffd83dbSDimitry Andric // is redistributed to all the original exit blocks. 125ffd83dbSDimitry Andric // 135ffd83dbSDimitry Andric // Limitation: This assumes that all terminators in the CFG are direct branches 145ffd83dbSDimitry Andric // (the "br" instruction). The presence of any other control flow 155ffd83dbSDimitry Andric // such as indirectbr, switch or callbr will cause an assert. 165ffd83dbSDimitry Andric // 175ffd83dbSDimitry Andric //===----------------------------------------------------------------------===// 185ffd83dbSDimitry Andric 19e8d8bef9SDimitry Andric #include "llvm/Transforms/Utils/UnifyLoopExits.h" 20e8d8bef9SDimitry Andric #include "llvm/ADT/MapVector.h" 21*81ad6265SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h" 225ffd83dbSDimitry Andric #include "llvm/Analysis/LoopInfo.h" 23*81ad6265SDimitry Andric #include "llvm/IR/Constants.h" 245ffd83dbSDimitry Andric #include "llvm/IR/Dominators.h" 255ffd83dbSDimitry Andric #include "llvm/InitializePasses.h" 265ffd83dbSDimitry Andric #include "llvm/Transforms/Utils.h" 275ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h" 285ffd83dbSDimitry Andric 295ffd83dbSDimitry Andric #define DEBUG_TYPE "unify-loop-exits" 305ffd83dbSDimitry Andric 315ffd83dbSDimitry Andric using namespace llvm; 325ffd83dbSDimitry Andric 335ffd83dbSDimitry Andric namespace { 34e8d8bef9SDimitry Andric struct UnifyLoopExitsLegacyPass : public FunctionPass { 355ffd83dbSDimitry Andric static char ID; 36e8d8bef9SDimitry Andric UnifyLoopExitsLegacyPass() : FunctionPass(ID) { 37e8d8bef9SDimitry Andric initializeUnifyLoopExitsLegacyPassPass(*PassRegistry::getPassRegistry()); 385ffd83dbSDimitry Andric } 395ffd83dbSDimitry Andric 405ffd83dbSDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 415ffd83dbSDimitry Andric AU.addRequiredID(LowerSwitchID); 425ffd83dbSDimitry Andric AU.addRequired<LoopInfoWrapperPass>(); 435ffd83dbSDimitry Andric AU.addRequired<DominatorTreeWrapperPass>(); 445ffd83dbSDimitry Andric AU.addPreservedID(LowerSwitchID); 455ffd83dbSDimitry Andric AU.addPreserved<LoopInfoWrapperPass>(); 465ffd83dbSDimitry Andric AU.addPreserved<DominatorTreeWrapperPass>(); 475ffd83dbSDimitry Andric } 485ffd83dbSDimitry Andric 495ffd83dbSDimitry Andric bool runOnFunction(Function &F) override; 505ffd83dbSDimitry Andric }; 515ffd83dbSDimitry Andric } // namespace 525ffd83dbSDimitry Andric 53e8d8bef9SDimitry Andric char UnifyLoopExitsLegacyPass::ID = 0; 545ffd83dbSDimitry Andric 55e8d8bef9SDimitry Andric FunctionPass *llvm::createUnifyLoopExitsPass() { 56e8d8bef9SDimitry Andric return new UnifyLoopExitsLegacyPass(); 57e8d8bef9SDimitry Andric } 585ffd83dbSDimitry Andric 59e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(UnifyLoopExitsLegacyPass, "unify-loop-exits", 605ffd83dbSDimitry Andric "Fixup each natural loop to have a single exit block", 615ffd83dbSDimitry Andric false /* Only looks at CFG */, false /* Analysis Pass */) 62e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LowerSwitchLegacyPass) 635ffd83dbSDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 645ffd83dbSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) 65e8d8bef9SDimitry Andric INITIALIZE_PASS_END(UnifyLoopExitsLegacyPass, "unify-loop-exits", 665ffd83dbSDimitry Andric "Fixup each natural loop to have a single exit block", 675ffd83dbSDimitry Andric false /* Only looks at CFG */, false /* Analysis Pass */) 685ffd83dbSDimitry Andric 695ffd83dbSDimitry Andric // The current transform introduces new control flow paths which may break the 705ffd83dbSDimitry Andric // SSA requirement that every def must dominate all its uses. For example, 715ffd83dbSDimitry Andric // consider a value D defined inside the loop that is used by some instruction 725ffd83dbSDimitry Andric // U outside the loop. It follows that D dominates U, since the original 735ffd83dbSDimitry Andric // program has valid SSA form. After merging the exits, all paths from D to U 745ffd83dbSDimitry Andric // now flow through the unified exit block. In addition, there may be other 755ffd83dbSDimitry Andric // paths that do not pass through D, but now reach the unified exit 765ffd83dbSDimitry Andric // block. Thus, D no longer dominates U. 775ffd83dbSDimitry Andric // 785ffd83dbSDimitry Andric // Restore the dominance by creating a phi for each such D at the new unified 795ffd83dbSDimitry Andric // loop exit. But when doing this, ignore any uses U that are in the new unified 805ffd83dbSDimitry Andric // loop exit, since those were introduced specially when the block was created. 815ffd83dbSDimitry Andric // 825ffd83dbSDimitry Andric // The use of SSAUpdater seems like overkill for this operation. The location 835ffd83dbSDimitry Andric // for creating the new PHI is well-known, and also the set of incoming blocks 845ffd83dbSDimitry Andric // to the new PHI. 855ffd83dbSDimitry Andric static void restoreSSA(const DominatorTree &DT, const Loop *L, 865ffd83dbSDimitry Andric const SetVector<BasicBlock *> &Incoming, 875ffd83dbSDimitry Andric BasicBlock *LoopExitBlock) { 885ffd83dbSDimitry Andric using InstVector = SmallVector<Instruction *, 8>; 89e8d8bef9SDimitry Andric using IIMap = MapVector<Instruction *, InstVector>; 905ffd83dbSDimitry Andric IIMap ExternalUsers; 915ffd83dbSDimitry Andric for (auto BB : L->blocks()) { 925ffd83dbSDimitry Andric for (auto &I : *BB) { 935ffd83dbSDimitry Andric for (auto &U : I.uses()) { 945ffd83dbSDimitry Andric auto UserInst = cast<Instruction>(U.getUser()); 955ffd83dbSDimitry Andric auto UserBlock = UserInst->getParent(); 965ffd83dbSDimitry Andric if (UserBlock == LoopExitBlock) 975ffd83dbSDimitry Andric continue; 985ffd83dbSDimitry Andric if (L->contains(UserBlock)) 995ffd83dbSDimitry Andric continue; 1005ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "added ext use for " << I.getName() << "(" 1015ffd83dbSDimitry Andric << BB->getName() << ")" 1025ffd83dbSDimitry Andric << ": " << UserInst->getName() << "(" 1035ffd83dbSDimitry Andric << UserBlock->getName() << ")" 1045ffd83dbSDimitry Andric << "\n"); 1055ffd83dbSDimitry Andric ExternalUsers[&I].push_back(UserInst); 1065ffd83dbSDimitry Andric } 1075ffd83dbSDimitry Andric } 1085ffd83dbSDimitry Andric } 1095ffd83dbSDimitry Andric 1105ffd83dbSDimitry Andric for (auto II : ExternalUsers) { 1115ffd83dbSDimitry Andric // For each Def used outside the loop, create NewPhi in 1125ffd83dbSDimitry Andric // LoopExitBlock. NewPhi receives Def only along exiting blocks that 1135ffd83dbSDimitry Andric // dominate it, while the remaining values are undefined since those paths 1145ffd83dbSDimitry Andric // didn't exist in the original CFG. 1155ffd83dbSDimitry Andric auto Def = II.first; 1165ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "externally used: " << Def->getName() << "\n"); 1175ffd83dbSDimitry Andric auto NewPhi = PHINode::Create(Def->getType(), Incoming.size(), 1185ffd83dbSDimitry Andric Def->getName() + ".moved", 1195ffd83dbSDimitry Andric LoopExitBlock->getTerminator()); 1205ffd83dbSDimitry Andric for (auto In : Incoming) { 1215ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "predecessor " << In->getName() << ": "); 1225ffd83dbSDimitry Andric if (Def->getParent() == In || DT.dominates(Def, In)) { 1235ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "dominated\n"); 1245ffd83dbSDimitry Andric NewPhi->addIncoming(Def, In); 1255ffd83dbSDimitry Andric } else { 1265ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "not dominated\n"); 1275ffd83dbSDimitry Andric NewPhi->addIncoming(UndefValue::get(Def->getType()), In); 1285ffd83dbSDimitry Andric } 1295ffd83dbSDimitry Andric } 1305ffd83dbSDimitry Andric 1315ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "external users:"); 1325ffd83dbSDimitry Andric for (auto U : II.second) { 1335ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << " " << U->getName()); 1345ffd83dbSDimitry Andric U->replaceUsesOfWith(Def, NewPhi); 1355ffd83dbSDimitry Andric } 1365ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "\n"); 1375ffd83dbSDimitry Andric } 1385ffd83dbSDimitry Andric } 1395ffd83dbSDimitry Andric 1405ffd83dbSDimitry Andric static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) { 1415ffd83dbSDimitry Andric // To unify the loop exits, we need a list of the exiting blocks as 1425ffd83dbSDimitry Andric // well as exit blocks. The functions for locating these lists both 1435ffd83dbSDimitry Andric // traverse the entire loop body. It is more efficient to first 1445ffd83dbSDimitry Andric // locate the exiting blocks and then examine their successors to 1455ffd83dbSDimitry Andric // locate the exit blocks. 1465ffd83dbSDimitry Andric SetVector<BasicBlock *> ExitingBlocks; 1475ffd83dbSDimitry Andric SetVector<BasicBlock *> Exits; 148*81ad6265SDimitry Andric // Record the exit blocks that branch to the same block. 149*81ad6265SDimitry Andric MapVector<BasicBlock *, SetVector<BasicBlock *> > CommonSuccs; 1505ffd83dbSDimitry Andric 1515ffd83dbSDimitry Andric // We need SetVectors, but the Loop API takes a vector, so we use a temporary. 1525ffd83dbSDimitry Andric SmallVector<BasicBlock *, 8> Temp; 1535ffd83dbSDimitry Andric L->getExitingBlocks(Temp); 1545ffd83dbSDimitry Andric for (auto BB : Temp) { 1555ffd83dbSDimitry Andric ExitingBlocks.insert(BB); 1565ffd83dbSDimitry Andric for (auto S : successors(BB)) { 1575ffd83dbSDimitry Andric auto SL = LI.getLoopFor(S); 1585ffd83dbSDimitry Andric // A successor is not an exit if it is directly or indirectly in the 1595ffd83dbSDimitry Andric // current loop. 1605ffd83dbSDimitry Andric if (SL == L || L->contains(SL)) 1615ffd83dbSDimitry Andric continue; 1625ffd83dbSDimitry Andric Exits.insert(S); 163*81ad6265SDimitry Andric // The typical case for reducing the number of guard blocks occurs when 164*81ad6265SDimitry Andric // the exit block has a single predecessor and successor. 165*81ad6265SDimitry Andric if (S->getSinglePredecessor()) 166*81ad6265SDimitry Andric if (auto *Succ = S->getSingleSuccessor()) 167*81ad6265SDimitry Andric CommonSuccs[Succ].insert(S); 1685ffd83dbSDimitry Andric } 1695ffd83dbSDimitry Andric } 1705ffd83dbSDimitry Andric 1715ffd83dbSDimitry Andric LLVM_DEBUG( 1725ffd83dbSDimitry Andric dbgs() << "Found exit blocks:"; 1735ffd83dbSDimitry Andric for (auto Exit : Exits) { 1745ffd83dbSDimitry Andric dbgs() << " " << Exit->getName(); 1755ffd83dbSDimitry Andric } 1765ffd83dbSDimitry Andric dbgs() << "\n"; 1775ffd83dbSDimitry Andric 1785ffd83dbSDimitry Andric dbgs() << "Found exiting blocks:"; 1795ffd83dbSDimitry Andric for (auto EB : ExitingBlocks) { 1805ffd83dbSDimitry Andric dbgs() << " " << EB->getName(); 1815ffd83dbSDimitry Andric } 182*81ad6265SDimitry Andric dbgs() << "\n"; 183*81ad6265SDimitry Andric 184*81ad6265SDimitry Andric dbgs() << "Exit blocks with a common successor:\n"; 185*81ad6265SDimitry Andric for (auto CS : CommonSuccs) { 186*81ad6265SDimitry Andric dbgs() << " Succ " << CS.first->getName() << ", exits:"; 187*81ad6265SDimitry Andric for (auto Exit : CS.second) 188*81ad6265SDimitry Andric dbgs() << " " << Exit->getName(); 189*81ad6265SDimitry Andric dbgs() << "\n"; 190*81ad6265SDimitry Andric }); 1915ffd83dbSDimitry Andric 1925ffd83dbSDimitry Andric if (Exits.size() <= 1) { 1935ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "loop does not have multiple exits; nothing to do\n"); 1945ffd83dbSDimitry Andric return false; 1955ffd83dbSDimitry Andric } 1965ffd83dbSDimitry Andric 197*81ad6265SDimitry Andric // When multiple exit blocks branch to the same block, change the control 198*81ad6265SDimitry Andric // flow hub to after the exit blocks rather than before. This reduces the 199*81ad6265SDimitry Andric // number of guard blocks needed after the loop. 200*81ad6265SDimitry Andric for (auto CS : CommonSuccs) { 201*81ad6265SDimitry Andric auto CB = CS.first; 202*81ad6265SDimitry Andric auto Preds = CS.second; 203*81ad6265SDimitry Andric if (Exits.contains(CB)) 204*81ad6265SDimitry Andric continue; 205*81ad6265SDimitry Andric if (Preds.size() < 2 || Preds.size() == Exits.size()) 206*81ad6265SDimitry Andric continue; 207*81ad6265SDimitry Andric for (auto Exit : Preds) { 208*81ad6265SDimitry Andric Exits.remove(Exit); 209*81ad6265SDimitry Andric ExitingBlocks.remove(Exit->getSinglePredecessor()); 210*81ad6265SDimitry Andric ExitingBlocks.insert(Exit); 211*81ad6265SDimitry Andric } 212*81ad6265SDimitry Andric Exits.insert(CB); 213*81ad6265SDimitry Andric } 214*81ad6265SDimitry Andric 2155ffd83dbSDimitry Andric SmallVector<BasicBlock *, 8> GuardBlocks; 2165ffd83dbSDimitry Andric DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 2175ffd83dbSDimitry Andric auto LoopExitBlock = CreateControlFlowHub(&DTU, GuardBlocks, ExitingBlocks, 2185ffd83dbSDimitry Andric Exits, "loop.exit"); 2195ffd83dbSDimitry Andric 2205ffd83dbSDimitry Andric restoreSSA(DT, L, ExitingBlocks, LoopExitBlock); 2215ffd83dbSDimitry Andric 2225ffd83dbSDimitry Andric #if defined(EXPENSIVE_CHECKS) 2235ffd83dbSDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Full)); 2245ffd83dbSDimitry Andric #else 2255ffd83dbSDimitry Andric assert(DT.verify(DominatorTree::VerificationLevel::Fast)); 2265ffd83dbSDimitry Andric #endif // EXPENSIVE_CHECKS 2275ffd83dbSDimitry Andric L->verifyLoop(); 2285ffd83dbSDimitry Andric 2295ffd83dbSDimitry Andric // The guard blocks were created outside the loop, so they need to become 2305ffd83dbSDimitry Andric // members of the parent loop. 2315ffd83dbSDimitry Andric if (auto ParentLoop = L->getParentLoop()) { 2325ffd83dbSDimitry Andric for (auto G : GuardBlocks) { 2335ffd83dbSDimitry Andric ParentLoop->addBasicBlockToLoop(G, LI); 234*81ad6265SDimitry Andric // Ensure the guard block predecessors are in a valid loop. After the 235*81ad6265SDimitry Andric // change to the control flow hub for common successors, a guard block 236*81ad6265SDimitry Andric // predecessor may not be in a loop or may be in an outer loop. 237*81ad6265SDimitry Andric for (auto Pred : predecessors(G)) { 238*81ad6265SDimitry Andric auto PredLoop = LI.getLoopFor(Pred); 239*81ad6265SDimitry Andric if (!ParentLoop->contains(PredLoop)) { 240*81ad6265SDimitry Andric if (PredLoop) 241*81ad6265SDimitry Andric LI.removeBlock(Pred); 242*81ad6265SDimitry Andric ParentLoop->addBasicBlockToLoop(Pred, LI); 243*81ad6265SDimitry Andric } 244*81ad6265SDimitry Andric } 2455ffd83dbSDimitry Andric } 2465ffd83dbSDimitry Andric ParentLoop->verifyLoop(); 2475ffd83dbSDimitry Andric } 2485ffd83dbSDimitry Andric 2495ffd83dbSDimitry Andric #if defined(EXPENSIVE_CHECKS) 2505ffd83dbSDimitry Andric LI.verify(DT); 2515ffd83dbSDimitry Andric #endif // EXPENSIVE_CHECKS 2525ffd83dbSDimitry Andric 2535ffd83dbSDimitry Andric return true; 2545ffd83dbSDimitry Andric } 2555ffd83dbSDimitry Andric 256e8d8bef9SDimitry Andric static bool runImpl(LoopInfo &LI, DominatorTree &DT) { 2575ffd83dbSDimitry Andric 2585ffd83dbSDimitry Andric bool Changed = false; 2595ffd83dbSDimitry Andric auto Loops = LI.getLoopsInPreorder(); 2605ffd83dbSDimitry Andric for (auto L : Loops) { 2615ffd83dbSDimitry Andric LLVM_DEBUG(dbgs() << "Loop: " << L->getHeader()->getName() << " (depth: " 2625ffd83dbSDimitry Andric << LI.getLoopDepth(L->getHeader()) << ")\n"); 2635ffd83dbSDimitry Andric Changed |= unifyLoopExits(DT, LI, L); 2645ffd83dbSDimitry Andric } 2655ffd83dbSDimitry Andric return Changed; 2665ffd83dbSDimitry Andric } 267e8d8bef9SDimitry Andric 268e8d8bef9SDimitry Andric bool UnifyLoopExitsLegacyPass::runOnFunction(Function &F) { 269e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "===== Unifying loop exits in function " << F.getName() 270e8d8bef9SDimitry Andric << "\n"); 271e8d8bef9SDimitry Andric auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 272e8d8bef9SDimitry Andric auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 273e8d8bef9SDimitry Andric 274e8d8bef9SDimitry Andric return runImpl(LI, DT); 275e8d8bef9SDimitry Andric } 276e8d8bef9SDimitry Andric 277e8d8bef9SDimitry Andric namespace llvm { 278e8d8bef9SDimitry Andric 279e8d8bef9SDimitry Andric PreservedAnalyses UnifyLoopExitsPass::run(Function &F, 280e8d8bef9SDimitry Andric FunctionAnalysisManager &AM) { 281e8d8bef9SDimitry Andric auto &LI = AM.getResult<LoopAnalysis>(F); 282e8d8bef9SDimitry Andric auto &DT = AM.getResult<DominatorTreeAnalysis>(F); 283e8d8bef9SDimitry Andric 284e8d8bef9SDimitry Andric if (!runImpl(LI, DT)) 285e8d8bef9SDimitry Andric return PreservedAnalyses::all(); 286e8d8bef9SDimitry Andric PreservedAnalyses PA; 287e8d8bef9SDimitry Andric PA.preserve<LoopAnalysis>(); 288e8d8bef9SDimitry Andric PA.preserve<DominatorTreeAnalysis>(); 289e8d8bef9SDimitry Andric return PA; 290e8d8bef9SDimitry Andric } 291e8d8bef9SDimitry Andric } // namespace llvm 292