xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
1*5ffd83dbSDimitry Andric //===- UnifyLoopExits.cpp - Redirect exiting edges to one block -*- C++ -*-===//
2*5ffd83dbSDimitry Andric //
3*5ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*5ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*5ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*5ffd83dbSDimitry Andric //
7*5ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
8*5ffd83dbSDimitry Andric //
9*5ffd83dbSDimitry Andric // For each natural loop with multiple exit blocks, this pass creates a new
10*5ffd83dbSDimitry Andric // block N such that all exiting blocks now branch to N, and then control flow
11*5ffd83dbSDimitry Andric // is redistributed to all the original exit blocks.
12*5ffd83dbSDimitry Andric //
13*5ffd83dbSDimitry Andric // Limitation: This assumes that all terminators in the CFG are direct branches
14*5ffd83dbSDimitry Andric //             (the "br" instruction). The presence of any other control flow
15*5ffd83dbSDimitry Andric //             such as indirectbr, switch or callbr will cause an assert.
16*5ffd83dbSDimitry Andric //
17*5ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
18*5ffd83dbSDimitry Andric 
19*5ffd83dbSDimitry Andric #include "llvm/Analysis/LoopInfo.h"
20*5ffd83dbSDimitry Andric #include "llvm/IR/Dominators.h"
21*5ffd83dbSDimitry Andric #include "llvm/InitializePasses.h"
22*5ffd83dbSDimitry Andric #include "llvm/Transforms/Utils.h"
23*5ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24*5ffd83dbSDimitry Andric 
25*5ffd83dbSDimitry Andric #define DEBUG_TYPE "unify-loop-exits"
26*5ffd83dbSDimitry Andric 
27*5ffd83dbSDimitry Andric using namespace llvm;
28*5ffd83dbSDimitry Andric 
29*5ffd83dbSDimitry Andric namespace {
30*5ffd83dbSDimitry Andric struct UnifyLoopExits : public FunctionPass {
31*5ffd83dbSDimitry Andric   static char ID;
32*5ffd83dbSDimitry Andric   UnifyLoopExits() : FunctionPass(ID) {
33*5ffd83dbSDimitry Andric     initializeUnifyLoopExitsPass(*PassRegistry::getPassRegistry());
34*5ffd83dbSDimitry Andric   }
35*5ffd83dbSDimitry Andric 
36*5ffd83dbSDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
37*5ffd83dbSDimitry Andric     AU.addRequiredID(LowerSwitchID);
38*5ffd83dbSDimitry Andric     AU.addRequired<LoopInfoWrapperPass>();
39*5ffd83dbSDimitry Andric     AU.addRequired<DominatorTreeWrapperPass>();
40*5ffd83dbSDimitry Andric     AU.addPreservedID(LowerSwitchID);
41*5ffd83dbSDimitry Andric     AU.addPreserved<LoopInfoWrapperPass>();
42*5ffd83dbSDimitry Andric     AU.addPreserved<DominatorTreeWrapperPass>();
43*5ffd83dbSDimitry Andric   }
44*5ffd83dbSDimitry Andric 
45*5ffd83dbSDimitry Andric   bool runOnFunction(Function &F) override;
46*5ffd83dbSDimitry Andric };
47*5ffd83dbSDimitry Andric } // namespace
48*5ffd83dbSDimitry Andric 
49*5ffd83dbSDimitry Andric char UnifyLoopExits::ID = 0;
50*5ffd83dbSDimitry Andric 
51*5ffd83dbSDimitry Andric FunctionPass *llvm::createUnifyLoopExitsPass() { return new UnifyLoopExits(); }
52*5ffd83dbSDimitry Andric 
53*5ffd83dbSDimitry Andric INITIALIZE_PASS_BEGIN(UnifyLoopExits, "unify-loop-exits",
54*5ffd83dbSDimitry Andric                       "Fixup each natural loop to have a single exit block",
55*5ffd83dbSDimitry Andric                       false /* Only looks at CFG */, false /* Analysis Pass */)
56*5ffd83dbSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LowerSwitch)
57*5ffd83dbSDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
58*5ffd83dbSDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
59*5ffd83dbSDimitry Andric INITIALIZE_PASS_END(UnifyLoopExits, "unify-loop-exits",
60*5ffd83dbSDimitry Andric                     "Fixup each natural loop to have a single exit block",
61*5ffd83dbSDimitry Andric                     false /* Only looks at CFG */, false /* Analysis Pass */)
62*5ffd83dbSDimitry Andric 
63*5ffd83dbSDimitry Andric // The current transform introduces new control flow paths which may break the
64*5ffd83dbSDimitry Andric // SSA requirement that every def must dominate all its uses. For example,
65*5ffd83dbSDimitry Andric // consider a value D defined inside the loop that is used by some instruction
66*5ffd83dbSDimitry Andric // U outside the loop. It follows that D dominates U, since the original
67*5ffd83dbSDimitry Andric // program has valid SSA form. After merging the exits, all paths from D to U
68*5ffd83dbSDimitry Andric // now flow through the unified exit block. In addition, there may be other
69*5ffd83dbSDimitry Andric // paths that do not pass through D, but now reach the unified exit
70*5ffd83dbSDimitry Andric // block. Thus, D no longer dominates U.
71*5ffd83dbSDimitry Andric //
72*5ffd83dbSDimitry Andric // Restore the dominance by creating a phi for each such D at the new unified
73*5ffd83dbSDimitry Andric // loop exit. But when doing this, ignore any uses U that are in the new unified
74*5ffd83dbSDimitry Andric // loop exit, since those were introduced specially when the block was created.
75*5ffd83dbSDimitry Andric //
76*5ffd83dbSDimitry Andric // The use of SSAUpdater seems like overkill for this operation. The location
77*5ffd83dbSDimitry Andric // for creating the new PHI is well-known, and also the set of incoming blocks
78*5ffd83dbSDimitry Andric // to the new PHI.
79*5ffd83dbSDimitry Andric static void restoreSSA(const DominatorTree &DT, const Loop *L,
80*5ffd83dbSDimitry Andric                        const SetVector<BasicBlock *> &Incoming,
81*5ffd83dbSDimitry Andric                        BasicBlock *LoopExitBlock) {
82*5ffd83dbSDimitry Andric   using InstVector = SmallVector<Instruction *, 8>;
83*5ffd83dbSDimitry Andric   using IIMap = DenseMap<Instruction *, InstVector>;
84*5ffd83dbSDimitry Andric   IIMap ExternalUsers;
85*5ffd83dbSDimitry Andric   for (auto BB : L->blocks()) {
86*5ffd83dbSDimitry Andric     for (auto &I : *BB) {
87*5ffd83dbSDimitry Andric       for (auto &U : I.uses()) {
88*5ffd83dbSDimitry Andric         auto UserInst = cast<Instruction>(U.getUser());
89*5ffd83dbSDimitry Andric         auto UserBlock = UserInst->getParent();
90*5ffd83dbSDimitry Andric         if (UserBlock == LoopExitBlock)
91*5ffd83dbSDimitry Andric           continue;
92*5ffd83dbSDimitry Andric         if (L->contains(UserBlock))
93*5ffd83dbSDimitry Andric           continue;
94*5ffd83dbSDimitry Andric         LLVM_DEBUG(dbgs() << "added ext use for " << I.getName() << "("
95*5ffd83dbSDimitry Andric                           << BB->getName() << ")"
96*5ffd83dbSDimitry Andric                           << ": " << UserInst->getName() << "("
97*5ffd83dbSDimitry Andric                           << UserBlock->getName() << ")"
98*5ffd83dbSDimitry Andric                           << "\n");
99*5ffd83dbSDimitry Andric         ExternalUsers[&I].push_back(UserInst);
100*5ffd83dbSDimitry Andric       }
101*5ffd83dbSDimitry Andric     }
102*5ffd83dbSDimitry Andric   }
103*5ffd83dbSDimitry Andric 
104*5ffd83dbSDimitry Andric   for (auto II : ExternalUsers) {
105*5ffd83dbSDimitry Andric     // For each Def used outside the loop, create NewPhi in
106*5ffd83dbSDimitry Andric     // LoopExitBlock. NewPhi receives Def only along exiting blocks that
107*5ffd83dbSDimitry Andric     // dominate it, while the remaining values are undefined since those paths
108*5ffd83dbSDimitry Andric     // didn't exist in the original CFG.
109*5ffd83dbSDimitry Andric     auto Def = II.first;
110*5ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "externally used: " << Def->getName() << "\n");
111*5ffd83dbSDimitry Andric     auto NewPhi = PHINode::Create(Def->getType(), Incoming.size(),
112*5ffd83dbSDimitry Andric                                   Def->getName() + ".moved",
113*5ffd83dbSDimitry Andric                                   LoopExitBlock->getTerminator());
114*5ffd83dbSDimitry Andric     for (auto In : Incoming) {
115*5ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "predecessor " << In->getName() << ": ");
116*5ffd83dbSDimitry Andric       if (Def->getParent() == In || DT.dominates(Def, In)) {
117*5ffd83dbSDimitry Andric         LLVM_DEBUG(dbgs() << "dominated\n");
118*5ffd83dbSDimitry Andric         NewPhi->addIncoming(Def, In);
119*5ffd83dbSDimitry Andric       } else {
120*5ffd83dbSDimitry Andric         LLVM_DEBUG(dbgs() << "not dominated\n");
121*5ffd83dbSDimitry Andric         NewPhi->addIncoming(UndefValue::get(Def->getType()), In);
122*5ffd83dbSDimitry Andric       }
123*5ffd83dbSDimitry Andric     }
124*5ffd83dbSDimitry Andric 
125*5ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "external users:");
126*5ffd83dbSDimitry Andric     for (auto U : II.second) {
127*5ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << " " << U->getName());
128*5ffd83dbSDimitry Andric       U->replaceUsesOfWith(Def, NewPhi);
129*5ffd83dbSDimitry Andric     }
130*5ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "\n");
131*5ffd83dbSDimitry Andric   }
132*5ffd83dbSDimitry Andric }
133*5ffd83dbSDimitry Andric 
134*5ffd83dbSDimitry Andric static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) {
135*5ffd83dbSDimitry Andric   // To unify the loop exits, we need a list of the exiting blocks as
136*5ffd83dbSDimitry Andric   // well as exit blocks. The functions for locating these lists both
137*5ffd83dbSDimitry Andric   // traverse the entire loop body. It is more efficient to first
138*5ffd83dbSDimitry Andric   // locate the exiting blocks and then examine their successors to
139*5ffd83dbSDimitry Andric   // locate the exit blocks.
140*5ffd83dbSDimitry Andric   SetVector<BasicBlock *> ExitingBlocks;
141*5ffd83dbSDimitry Andric   SetVector<BasicBlock *> Exits;
142*5ffd83dbSDimitry Andric 
143*5ffd83dbSDimitry Andric   // We need SetVectors, but the Loop API takes a vector, so we use a temporary.
144*5ffd83dbSDimitry Andric   SmallVector<BasicBlock *, 8> Temp;
145*5ffd83dbSDimitry Andric   L->getExitingBlocks(Temp);
146*5ffd83dbSDimitry Andric   for (auto BB : Temp) {
147*5ffd83dbSDimitry Andric     ExitingBlocks.insert(BB);
148*5ffd83dbSDimitry Andric     for (auto S : successors(BB)) {
149*5ffd83dbSDimitry Andric       auto SL = LI.getLoopFor(S);
150*5ffd83dbSDimitry Andric       // A successor is not an exit if it is directly or indirectly in the
151*5ffd83dbSDimitry Andric       // current loop.
152*5ffd83dbSDimitry Andric       if (SL == L || L->contains(SL))
153*5ffd83dbSDimitry Andric         continue;
154*5ffd83dbSDimitry Andric       Exits.insert(S);
155*5ffd83dbSDimitry Andric     }
156*5ffd83dbSDimitry Andric   }
157*5ffd83dbSDimitry Andric 
158*5ffd83dbSDimitry Andric   LLVM_DEBUG(
159*5ffd83dbSDimitry Andric       dbgs() << "Found exit blocks:";
160*5ffd83dbSDimitry Andric       for (auto Exit : Exits) {
161*5ffd83dbSDimitry Andric         dbgs() << " " << Exit->getName();
162*5ffd83dbSDimitry Andric       }
163*5ffd83dbSDimitry Andric       dbgs() << "\n";
164*5ffd83dbSDimitry Andric 
165*5ffd83dbSDimitry Andric       dbgs() << "Found exiting blocks:";
166*5ffd83dbSDimitry Andric       for (auto EB : ExitingBlocks) {
167*5ffd83dbSDimitry Andric         dbgs() << " " << EB->getName();
168*5ffd83dbSDimitry Andric       }
169*5ffd83dbSDimitry Andric       dbgs() << "\n";);
170*5ffd83dbSDimitry Andric 
171*5ffd83dbSDimitry Andric   if (Exits.size() <= 1) {
172*5ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "loop does not have multiple exits; nothing to do\n");
173*5ffd83dbSDimitry Andric     return false;
174*5ffd83dbSDimitry Andric   }
175*5ffd83dbSDimitry Andric 
176*5ffd83dbSDimitry Andric   SmallVector<BasicBlock *, 8> GuardBlocks;
177*5ffd83dbSDimitry Andric   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
178*5ffd83dbSDimitry Andric   auto LoopExitBlock = CreateControlFlowHub(&DTU, GuardBlocks, ExitingBlocks,
179*5ffd83dbSDimitry Andric                                             Exits, "loop.exit");
180*5ffd83dbSDimitry Andric 
181*5ffd83dbSDimitry Andric   restoreSSA(DT, L, ExitingBlocks, LoopExitBlock);
182*5ffd83dbSDimitry Andric 
183*5ffd83dbSDimitry Andric #if defined(EXPENSIVE_CHECKS)
184*5ffd83dbSDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Full));
185*5ffd83dbSDimitry Andric #else
186*5ffd83dbSDimitry Andric   assert(DT.verify(DominatorTree::VerificationLevel::Fast));
187*5ffd83dbSDimitry Andric #endif // EXPENSIVE_CHECKS
188*5ffd83dbSDimitry Andric   L->verifyLoop();
189*5ffd83dbSDimitry Andric 
190*5ffd83dbSDimitry Andric   // The guard blocks were created outside the loop, so they need to become
191*5ffd83dbSDimitry Andric   // members of the parent loop.
192*5ffd83dbSDimitry Andric   if (auto ParentLoop = L->getParentLoop()) {
193*5ffd83dbSDimitry Andric     for (auto G : GuardBlocks) {
194*5ffd83dbSDimitry Andric       ParentLoop->addBasicBlockToLoop(G, LI);
195*5ffd83dbSDimitry Andric     }
196*5ffd83dbSDimitry Andric     ParentLoop->verifyLoop();
197*5ffd83dbSDimitry Andric   }
198*5ffd83dbSDimitry Andric 
199*5ffd83dbSDimitry Andric #if defined(EXPENSIVE_CHECKS)
200*5ffd83dbSDimitry Andric   LI.verify(DT);
201*5ffd83dbSDimitry Andric #endif // EXPENSIVE_CHECKS
202*5ffd83dbSDimitry Andric 
203*5ffd83dbSDimitry Andric   return true;
204*5ffd83dbSDimitry Andric }
205*5ffd83dbSDimitry Andric 
206*5ffd83dbSDimitry Andric bool UnifyLoopExits::runOnFunction(Function &F) {
207*5ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "===== Unifying loop exits in function " << F.getName()
208*5ffd83dbSDimitry Andric                     << "\n");
209*5ffd83dbSDimitry Andric   auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
210*5ffd83dbSDimitry Andric   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
211*5ffd83dbSDimitry Andric 
212*5ffd83dbSDimitry Andric   bool Changed = false;
213*5ffd83dbSDimitry Andric   auto Loops = LI.getLoopsInPreorder();
214*5ffd83dbSDimitry Andric   for (auto L : Loops) {
215*5ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Loop: " << L->getHeader()->getName() << " (depth: "
216*5ffd83dbSDimitry Andric                       << LI.getLoopDepth(L->getHeader()) << ")\n");
217*5ffd83dbSDimitry Andric     Changed |= unifyLoopExits(DT, LI, L);
218*5ffd83dbSDimitry Andric   }
219*5ffd83dbSDimitry Andric   return Changed;
220*5ffd83dbSDimitry Andric }
221