1*0b57cec5SDimitry Andric //===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file implements the Loop SimplifyCFG Pass. This pass is responsible for
10*0b57cec5SDimitry Andric // basic loop CFG cleanup, primarily to assist other loop passes. If you
11*0b57cec5SDimitry Andric // encounter a noncanonical CFG construct that causes another loop pass to
12*0b57cec5SDimitry Andric // perform suboptimally, this is the place to fix it up.
13*0b57cec5SDimitry Andric //
14*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
15*0b57cec5SDimitry Andric 
16*0b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
19*0b57cec5SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
20*0b57cec5SDimitry Andric #include "llvm/Analysis/BasicAliasAnalysis.h"
21*0b57cec5SDimitry Andric #include "llvm/Analysis/DependenceAnalysis.h"
22*0b57cec5SDimitry Andric #include "llvm/Analysis/DomTreeUpdater.h"
23*0b57cec5SDimitry Andric #include "llvm/Analysis/GlobalsModRef.h"
24*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
255ffd83dbSDimitry Andric #include "llvm/Analysis/LoopIterator.h"
26*0b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
27*0b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
28*0b57cec5SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
29*0b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
30*0b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
31*0b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
335ffd83dbSDimitry Andric #include "llvm/IR/IRBuilder.h"
34480093f4SDimitry Andric #include "llvm/InitializePasses.h"
35480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
36*0b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
37*0b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/LoopPassManager.h"
38*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils.h"
39*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
41*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
42*0b57cec5SDimitry Andric using namespace llvm;
43*0b57cec5SDimitry Andric 
44*0b57cec5SDimitry Andric #define DEBUG_TYPE "loop-simplifycfg"
45*0b57cec5SDimitry Andric 
46*0b57cec5SDimitry Andric static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
47*0b57cec5SDimitry Andric                                        cl::init(true));
48*0b57cec5SDimitry Andric 
49*0b57cec5SDimitry Andric STATISTIC(NumTerminatorsFolded,
50*0b57cec5SDimitry Andric           "Number of terminators folded to unconditional branches");
51*0b57cec5SDimitry Andric STATISTIC(NumLoopBlocksDeleted,
52*0b57cec5SDimitry Andric           "Number of loop blocks deleted");
53*0b57cec5SDimitry Andric STATISTIC(NumLoopExitsDeleted,
54*0b57cec5SDimitry Andric           "Number of loop exiting edges deleted");
55*0b57cec5SDimitry Andric 
56*0b57cec5SDimitry Andric /// If \p BB is a switch or a conditional branch, but only one of its successors
57*0b57cec5SDimitry Andric /// can be reached from this block in runtime, return this successor. Otherwise,
58*0b57cec5SDimitry Andric /// return nullptr.
59*0b57cec5SDimitry Andric static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
60*0b57cec5SDimitry Andric   Instruction *TI = BB->getTerminator();
61*0b57cec5SDimitry Andric   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
62*0b57cec5SDimitry Andric     if (BI->isUnconditional())
63*0b57cec5SDimitry Andric       return nullptr;
64*0b57cec5SDimitry Andric     if (BI->getSuccessor(0) == BI->getSuccessor(1))
65*0b57cec5SDimitry Andric       return BI->getSuccessor(0);
66*0b57cec5SDimitry Andric     ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
67*0b57cec5SDimitry Andric     if (!Cond)
68*0b57cec5SDimitry Andric       return nullptr;
69*0b57cec5SDimitry Andric     return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
70*0b57cec5SDimitry Andric   }
71*0b57cec5SDimitry Andric 
72*0b57cec5SDimitry Andric   if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
73*0b57cec5SDimitry Andric     auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
74*0b57cec5SDimitry Andric     if (!CI)
75*0b57cec5SDimitry Andric       return nullptr;
76*0b57cec5SDimitry Andric     for (auto Case : SI->cases())
77*0b57cec5SDimitry Andric       if (Case.getCaseValue() == CI)
78*0b57cec5SDimitry Andric         return Case.getCaseSuccessor();
79*0b57cec5SDimitry Andric     return SI->getDefaultDest();
80*0b57cec5SDimitry Andric   }
81*0b57cec5SDimitry Andric 
82*0b57cec5SDimitry Andric   return nullptr;
83*0b57cec5SDimitry Andric }
84*0b57cec5SDimitry Andric 
85*0b57cec5SDimitry Andric /// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
86*0b57cec5SDimitry Andric static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
87*0b57cec5SDimitry Andric                                  Loop *LastLoop = nullptr) {
88*0b57cec5SDimitry Andric   assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
89*0b57cec5SDimitry Andric          "First loop is supposed to be inside of last loop!");
90*0b57cec5SDimitry Andric   assert(FirstLoop->contains(BB) && "Must be a loop block!");
91*0b57cec5SDimitry Andric   for (Loop *Current = FirstLoop; Current != LastLoop;
92*0b57cec5SDimitry Andric        Current = Current->getParentLoop())
93*0b57cec5SDimitry Andric     Current->removeBlockFromLoop(BB);
94*0b57cec5SDimitry Andric }
95*0b57cec5SDimitry Andric 
96*0b57cec5SDimitry Andric /// Find innermost loop that contains at least one block from \p BBs and
97*0b57cec5SDimitry Andric /// contains the header of loop \p L.
98*0b57cec5SDimitry Andric static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
99*0b57cec5SDimitry Andric                                  Loop &L, LoopInfo &LI) {
100*0b57cec5SDimitry Andric   Loop *Innermost = nullptr;
101*0b57cec5SDimitry Andric   for (BasicBlock *BB : BBs) {
102*0b57cec5SDimitry Andric     Loop *BBL = LI.getLoopFor(BB);
103*0b57cec5SDimitry Andric     while (BBL && !BBL->contains(L.getHeader()))
104*0b57cec5SDimitry Andric       BBL = BBL->getParentLoop();
105*0b57cec5SDimitry Andric     if (BBL == &L)
106*0b57cec5SDimitry Andric       BBL = BBL->getParentLoop();
107*0b57cec5SDimitry Andric     if (!BBL)
108*0b57cec5SDimitry Andric       continue;
109*0b57cec5SDimitry Andric     if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
110*0b57cec5SDimitry Andric       Innermost = BBL;
111*0b57cec5SDimitry Andric   }
112*0b57cec5SDimitry Andric   return Innermost;
113*0b57cec5SDimitry Andric }
114*0b57cec5SDimitry Andric 
115*0b57cec5SDimitry Andric namespace {
116*0b57cec5SDimitry Andric /// Helper class that can turn branches and switches with constant conditions
117*0b57cec5SDimitry Andric /// into unconditional branches.
118*0b57cec5SDimitry Andric class ConstantTerminatorFoldingImpl {
119*0b57cec5SDimitry Andric private:
120*0b57cec5SDimitry Andric   Loop &L;
121*0b57cec5SDimitry Andric   LoopInfo &LI;
122*0b57cec5SDimitry Andric   DominatorTree &DT;
123*0b57cec5SDimitry Andric   ScalarEvolution &SE;
124*0b57cec5SDimitry Andric   MemorySSAUpdater *MSSAU;
125*0b57cec5SDimitry Andric   LoopBlocksDFS DFS;
126*0b57cec5SDimitry Andric   DomTreeUpdater DTU;
127*0b57cec5SDimitry Andric   SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
128*0b57cec5SDimitry Andric 
129*0b57cec5SDimitry Andric   // Whether or not the current loop has irreducible CFG.
130*0b57cec5SDimitry Andric   bool HasIrreducibleCFG = false;
131*0b57cec5SDimitry Andric   // Whether or not the current loop will still exist after terminator constant
132*0b57cec5SDimitry Andric   // folding will be done. In theory, there are two ways how it can happen:
133*0b57cec5SDimitry Andric   // 1. Loop's latch(es) become unreachable from loop header;
134*0b57cec5SDimitry Andric   // 2. Loop's header becomes unreachable from method entry.
135*0b57cec5SDimitry Andric   // In practice, the second situation is impossible because we only modify the
136*0b57cec5SDimitry Andric   // current loop and its preheader and do not affect preheader's reachibility
137*0b57cec5SDimitry Andric   // from any other block. So this variable set to true means that loop's latch
138*0b57cec5SDimitry Andric   // has become unreachable from loop header.
139*0b57cec5SDimitry Andric   bool DeleteCurrentLoop = false;
140*0b57cec5SDimitry Andric 
141*0b57cec5SDimitry Andric   // The blocks of the original loop that will still be reachable from entry
142*0b57cec5SDimitry Andric   // after the constant folding.
143*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
144*0b57cec5SDimitry Andric   // The blocks of the original loop that will become unreachable from entry
145*0b57cec5SDimitry Andric   // after the constant folding.
146*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> DeadLoopBlocks;
147*0b57cec5SDimitry Andric   // The exits of the original loop that will still be reachable from entry
148*0b57cec5SDimitry Andric   // after the constant folding.
149*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
150*0b57cec5SDimitry Andric   // The exits of the original loop that will become unreachable from entry
151*0b57cec5SDimitry Andric   // after the constant folding.
152*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> DeadExitBlocks;
153*0b57cec5SDimitry Andric   // The blocks that will still be a part of the current loop after folding.
154*0b57cec5SDimitry Andric   SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
155*0b57cec5SDimitry Andric   // The blocks that have terminators with constant condition that can be
156*0b57cec5SDimitry Andric   // folded. Note: fold candidates should be in L but not in any of its
157*0b57cec5SDimitry Andric   // subloops to avoid complex LI updates.
158*0b57cec5SDimitry Andric   SmallVector<BasicBlock *, 8> FoldCandidates;
159*0b57cec5SDimitry Andric 
160*0b57cec5SDimitry Andric   void dump() const {
161*0b57cec5SDimitry Andric     dbgs() << "Constant terminator folding for loop " << L << "\n";
162*0b57cec5SDimitry Andric     dbgs() << "After terminator constant-folding, the loop will";
163*0b57cec5SDimitry Andric     if (!DeleteCurrentLoop)
164*0b57cec5SDimitry Andric       dbgs() << " not";
165*0b57cec5SDimitry Andric     dbgs() << " be destroyed\n";
166*0b57cec5SDimitry Andric     auto PrintOutVector = [&](const char *Message,
167*0b57cec5SDimitry Andric                            const SmallVectorImpl<BasicBlock *> &S) {
168*0b57cec5SDimitry Andric       dbgs() << Message << "\n";
169*0b57cec5SDimitry Andric       for (const BasicBlock *BB : S)
170*0b57cec5SDimitry Andric         dbgs() << "\t" << BB->getName() << "\n";
171*0b57cec5SDimitry Andric     };
172*0b57cec5SDimitry Andric     auto PrintOutSet = [&](const char *Message,
173*0b57cec5SDimitry Andric                            const SmallPtrSetImpl<BasicBlock *> &S) {
174*0b57cec5SDimitry Andric       dbgs() << Message << "\n";
175*0b57cec5SDimitry Andric       for (const BasicBlock *BB : S)
176*0b57cec5SDimitry Andric         dbgs() << "\t" << BB->getName() << "\n";
177*0b57cec5SDimitry Andric     };
178*0b57cec5SDimitry Andric     PrintOutVector("Blocks in which we can constant-fold terminator:",
179*0b57cec5SDimitry Andric                    FoldCandidates);
180*0b57cec5SDimitry Andric     PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
181*0b57cec5SDimitry Andric     PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
182*0b57cec5SDimitry Andric     PrintOutSet("Live exit blocks:", LiveExitBlocks);
183*0b57cec5SDimitry Andric     PrintOutVector("Dead exit blocks:", DeadExitBlocks);
184*0b57cec5SDimitry Andric     if (!DeleteCurrentLoop)
185*0b57cec5SDimitry Andric       PrintOutSet("The following blocks will still be part of the loop:",
186*0b57cec5SDimitry Andric                   BlocksInLoopAfterFolding);
187*0b57cec5SDimitry Andric   }
188*0b57cec5SDimitry Andric 
189*0b57cec5SDimitry Andric   /// Whether or not the current loop has irreducible CFG.
190*0b57cec5SDimitry Andric   bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
191*0b57cec5SDimitry Andric     assert(DFS.isComplete() && "DFS is expected to be finished");
192*0b57cec5SDimitry Andric     // Index of a basic block in RPO traversal.
193*0b57cec5SDimitry Andric     DenseMap<const BasicBlock *, unsigned> RPO;
194*0b57cec5SDimitry Andric     unsigned Current = 0;
195*0b57cec5SDimitry Andric     for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
196*0b57cec5SDimitry Andric       RPO[*I] = Current++;
197*0b57cec5SDimitry Andric 
198*0b57cec5SDimitry Andric     for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
199*0b57cec5SDimitry Andric       BasicBlock *BB = *I;
200*0b57cec5SDimitry Andric       for (auto *Succ : successors(BB))
201*0b57cec5SDimitry Andric         if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
202*0b57cec5SDimitry Andric           // If an edge goes from a block with greater order number into a block
203*0b57cec5SDimitry Andric           // with lesses number, and it is not a loop backedge, then it can only
204*0b57cec5SDimitry Andric           // be a part of irreducible non-loop cycle.
205*0b57cec5SDimitry Andric           return true;
206*0b57cec5SDimitry Andric     }
207*0b57cec5SDimitry Andric     return false;
208*0b57cec5SDimitry Andric   }
209*0b57cec5SDimitry Andric 
210*0b57cec5SDimitry Andric   /// Fill all information about status of blocks and exits of the current loop
211*0b57cec5SDimitry Andric   /// if constant folding of all branches will be done.
212*0b57cec5SDimitry Andric   void analyze() {
213*0b57cec5SDimitry Andric     DFS.perform(&LI);
214*0b57cec5SDimitry Andric     assert(DFS.isComplete() && "DFS is expected to be finished");
215*0b57cec5SDimitry Andric 
216*0b57cec5SDimitry Andric     // TODO: The algorithm below relies on both RPO and Postorder traversals.
217*0b57cec5SDimitry Andric     // When the loop has only reducible CFG inside, then the invariant "all
218*0b57cec5SDimitry Andric     // predecessors of X are processed before X in RPO" is preserved. However
219*0b57cec5SDimitry Andric     // an irreducible loop can break this invariant (e.g. latch does not have to
220*0b57cec5SDimitry Andric     // be the last block in the traversal in this case, and the algorithm relies
221*0b57cec5SDimitry Andric     // on this). We can later decide to support such cases by altering the
222*0b57cec5SDimitry Andric     // algorithms, but so far we just give up analyzing them.
223*0b57cec5SDimitry Andric     if (hasIrreducibleCFG(DFS)) {
224*0b57cec5SDimitry Andric       HasIrreducibleCFG = true;
225*0b57cec5SDimitry Andric       return;
226*0b57cec5SDimitry Andric     }
227*0b57cec5SDimitry Andric 
228*0b57cec5SDimitry Andric     // Collect live and dead loop blocks and exits.
229*0b57cec5SDimitry Andric     LiveLoopBlocks.insert(L.getHeader());
230*0b57cec5SDimitry Andric     for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
231*0b57cec5SDimitry Andric       BasicBlock *BB = *I;
232*0b57cec5SDimitry Andric 
233*0b57cec5SDimitry Andric       // If a loop block wasn't marked as live so far, then it's dead.
234*0b57cec5SDimitry Andric       if (!LiveLoopBlocks.count(BB)) {
235*0b57cec5SDimitry Andric         DeadLoopBlocks.push_back(BB);
236*0b57cec5SDimitry Andric         continue;
237*0b57cec5SDimitry Andric       }
238*0b57cec5SDimitry Andric 
239*0b57cec5SDimitry Andric       BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
240*0b57cec5SDimitry Andric 
241*0b57cec5SDimitry Andric       // If a block has only one live successor, it's a candidate on constant
242*0b57cec5SDimitry Andric       // folding. Only handle blocks from current loop: branches in child loops
243*0b57cec5SDimitry Andric       // are skipped because if they can be folded, they should be folded during
244*0b57cec5SDimitry Andric       // the processing of child loops.
245*0b57cec5SDimitry Andric       bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
246*0b57cec5SDimitry Andric       if (TakeFoldCandidate)
247*0b57cec5SDimitry Andric         FoldCandidates.push_back(BB);
248*0b57cec5SDimitry Andric 
249*0b57cec5SDimitry Andric       // Handle successors.
250*0b57cec5SDimitry Andric       for (BasicBlock *Succ : successors(BB))
251*0b57cec5SDimitry Andric         if (!TakeFoldCandidate || TheOnlySucc == Succ) {
252*0b57cec5SDimitry Andric           if (L.contains(Succ))
253*0b57cec5SDimitry Andric             LiveLoopBlocks.insert(Succ);
254*0b57cec5SDimitry Andric           else
255*0b57cec5SDimitry Andric             LiveExitBlocks.insert(Succ);
256*0b57cec5SDimitry Andric         }
257*0b57cec5SDimitry Andric     }
258*0b57cec5SDimitry Andric 
259*0b57cec5SDimitry Andric     // Sanity check: amount of dead and live loop blocks should match the total
260*0b57cec5SDimitry Andric     // number of blocks in loop.
261*0b57cec5SDimitry Andric     assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
262*0b57cec5SDimitry Andric            "Malformed block sets?");
263*0b57cec5SDimitry Andric 
264*0b57cec5SDimitry Andric     // Now, all exit blocks that are not marked as live are dead.
265*0b57cec5SDimitry Andric     SmallVector<BasicBlock *, 8> ExitBlocks;
266*0b57cec5SDimitry Andric     L.getExitBlocks(ExitBlocks);
267*0b57cec5SDimitry Andric     SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
268*0b57cec5SDimitry Andric     for (auto *ExitBlock : ExitBlocks)
269*0b57cec5SDimitry Andric       if (!LiveExitBlocks.count(ExitBlock) &&
270*0b57cec5SDimitry Andric           UniqueDeadExits.insert(ExitBlock).second)
271*0b57cec5SDimitry Andric         DeadExitBlocks.push_back(ExitBlock);
272*0b57cec5SDimitry Andric 
273*0b57cec5SDimitry Andric     // Whether or not the edge From->To will still be present in graph after the
274*0b57cec5SDimitry Andric     // folding.
275*0b57cec5SDimitry Andric     auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
276*0b57cec5SDimitry Andric       if (!LiveLoopBlocks.count(From))
277*0b57cec5SDimitry Andric         return false;
278*0b57cec5SDimitry Andric       BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
279*0b57cec5SDimitry Andric       return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
280*0b57cec5SDimitry Andric     };
281*0b57cec5SDimitry Andric 
282*0b57cec5SDimitry Andric     // The loop will not be destroyed if its latch is live.
283*0b57cec5SDimitry Andric     DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric     // If we are going to delete the current loop completely, no extra analysis
286*0b57cec5SDimitry Andric     // is needed.
287*0b57cec5SDimitry Andric     if (DeleteCurrentLoop)
288*0b57cec5SDimitry Andric       return;
289*0b57cec5SDimitry Andric 
290*0b57cec5SDimitry Andric     // Otherwise, we should check which blocks will still be a part of the
291*0b57cec5SDimitry Andric     // current loop after the transform.
292*0b57cec5SDimitry Andric     BlocksInLoopAfterFolding.insert(L.getLoopLatch());
293*0b57cec5SDimitry Andric     // If the loop is live, then we should compute what blocks are still in
294*0b57cec5SDimitry Andric     // loop after all branch folding has been done. A block is in loop if
295*0b57cec5SDimitry Andric     // it has a live edge to another block that is in the loop; by definition,
296*0b57cec5SDimitry Andric     // latch is in the loop.
297*0b57cec5SDimitry Andric     auto BlockIsInLoop = [&](BasicBlock *BB) {
298*0b57cec5SDimitry Andric       return any_of(successors(BB), [&](BasicBlock *Succ) {
299*0b57cec5SDimitry Andric         return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
300*0b57cec5SDimitry Andric       });
301*0b57cec5SDimitry Andric     };
302*0b57cec5SDimitry Andric     for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
303*0b57cec5SDimitry Andric       BasicBlock *BB = *I;
304*0b57cec5SDimitry Andric       if (BlockIsInLoop(BB))
305*0b57cec5SDimitry Andric         BlocksInLoopAfterFolding.insert(BB);
306*0b57cec5SDimitry Andric     }
307*0b57cec5SDimitry Andric 
308*0b57cec5SDimitry Andric     // Sanity check: header must be in loop.
309*0b57cec5SDimitry Andric     assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
310*0b57cec5SDimitry Andric            "Header not in loop?");
311*0b57cec5SDimitry Andric     assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
312*0b57cec5SDimitry Andric            "All blocks that stay in loop should be live!");
313*0b57cec5SDimitry Andric   }
314*0b57cec5SDimitry Andric 
315*0b57cec5SDimitry Andric   /// We need to preserve static reachibility of all loop exit blocks (this is)
316*0b57cec5SDimitry Andric   /// required by loop pass manager. In order to do it, we make the following
317*0b57cec5SDimitry Andric   /// trick:
318*0b57cec5SDimitry Andric   ///
319*0b57cec5SDimitry Andric   ///  preheader:
320*0b57cec5SDimitry Andric   ///    <preheader code>
321*0b57cec5SDimitry Andric   ///    br label %loop_header
322*0b57cec5SDimitry Andric   ///
323*0b57cec5SDimitry Andric   ///  loop_header:
324*0b57cec5SDimitry Andric   ///    ...
325*0b57cec5SDimitry Andric   ///    br i1 false, label %dead_exit, label %loop_block
326*0b57cec5SDimitry Andric   ///    ...
327*0b57cec5SDimitry Andric   ///
328*0b57cec5SDimitry Andric   /// We cannot simply remove edge from the loop to dead exit because in this
329*0b57cec5SDimitry Andric   /// case dead_exit (and its successors) may become unreachable. To avoid that,
330*0b57cec5SDimitry Andric   /// we insert the following fictive preheader:
331*0b57cec5SDimitry Andric   ///
332*0b57cec5SDimitry Andric   ///  preheader:
333*0b57cec5SDimitry Andric   ///    <preheader code>
334*0b57cec5SDimitry Andric   ///    switch i32 0, label %preheader-split,
335*0b57cec5SDimitry Andric   ///                  [i32 1, label %dead_exit_1],
336*0b57cec5SDimitry Andric   ///                  [i32 2, label %dead_exit_2],
337*0b57cec5SDimitry Andric   ///                  ...
338*0b57cec5SDimitry Andric   ///                  [i32 N, label %dead_exit_N],
339*0b57cec5SDimitry Andric   ///
340*0b57cec5SDimitry Andric   ///  preheader-split:
341*0b57cec5SDimitry Andric   ///    br label %loop_header
342*0b57cec5SDimitry Andric   ///
343*0b57cec5SDimitry Andric   ///  loop_header:
344*0b57cec5SDimitry Andric   ///    ...
345*0b57cec5SDimitry Andric   ///    br i1 false, label %dead_exit_N, label %loop_block
346*0b57cec5SDimitry Andric   ///    ...
347*0b57cec5SDimitry Andric   ///
348*0b57cec5SDimitry Andric   /// Doing so, we preserve static reachibility of all dead exits and can later
349*0b57cec5SDimitry Andric   /// remove edges from the loop to these blocks.
350*0b57cec5SDimitry Andric   void handleDeadExits() {
351*0b57cec5SDimitry Andric     // If no dead exits, nothing to do.
352*0b57cec5SDimitry Andric     if (DeadExitBlocks.empty())
353*0b57cec5SDimitry Andric       return;
354*0b57cec5SDimitry Andric 
355*0b57cec5SDimitry Andric     // Construct split preheader and the dummy switch to thread edges from it to
356*0b57cec5SDimitry Andric     // dead exits.
357*0b57cec5SDimitry Andric     BasicBlock *Preheader = L.getLoopPreheader();
358*0b57cec5SDimitry Andric     BasicBlock *NewPreheader = llvm::SplitBlock(
359*0b57cec5SDimitry Andric         Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
360*0b57cec5SDimitry Andric 
361*0b57cec5SDimitry Andric     IRBuilder<> Builder(Preheader->getTerminator());
362*0b57cec5SDimitry Andric     SwitchInst *DummySwitch =
363*0b57cec5SDimitry Andric         Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
364*0b57cec5SDimitry Andric     Preheader->getTerminator()->eraseFromParent();
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric     unsigned DummyIdx = 1;
367*0b57cec5SDimitry Andric     for (BasicBlock *BB : DeadExitBlocks) {
368e8d8bef9SDimitry Andric       // Eliminate all Phis and LandingPads from dead exits.
369e8d8bef9SDimitry Andric       // TODO: Consider removing all instructions in this dead block.
370e8d8bef9SDimitry Andric       SmallVector<Instruction *, 4> DeadInstructions;
371*0b57cec5SDimitry Andric       for (auto &PN : BB->phis())
372e8d8bef9SDimitry Andric         DeadInstructions.push_back(&PN);
373*0b57cec5SDimitry Andric 
374e8d8bef9SDimitry Andric       if (auto *LandingPad = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()))
375e8d8bef9SDimitry Andric         DeadInstructions.emplace_back(LandingPad);
376e8d8bef9SDimitry Andric 
377e8d8bef9SDimitry Andric       for (Instruction *I : DeadInstructions) {
378e8d8bef9SDimitry Andric         I->replaceAllUsesWith(UndefValue::get(I->getType()));
379e8d8bef9SDimitry Andric         I->eraseFromParent();
380*0b57cec5SDimitry Andric       }
381e8d8bef9SDimitry Andric 
382*0b57cec5SDimitry Andric       assert(DummyIdx != 0 && "Too many dead exits!");
383*0b57cec5SDimitry Andric       DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
384*0b57cec5SDimitry Andric       DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
385*0b57cec5SDimitry Andric       ++NumLoopExitsDeleted;
386*0b57cec5SDimitry Andric     }
387*0b57cec5SDimitry Andric 
388*0b57cec5SDimitry Andric     assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
389*0b57cec5SDimitry Andric     if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
390*0b57cec5SDimitry Andric       // When we break dead edges, the outer loop may become unreachable from
391*0b57cec5SDimitry Andric       // the current loop. We need to fix loop info accordingly. For this, we
392*0b57cec5SDimitry Andric       // find the most nested loop that still contains L and remove L from all
393*0b57cec5SDimitry Andric       // loops that are inside of it.
394*0b57cec5SDimitry Andric       Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
395*0b57cec5SDimitry Andric 
396*0b57cec5SDimitry Andric       // Okay, our loop is no longer in the outer loop (and maybe not in some of
397*0b57cec5SDimitry Andric       // its parents as well). Make the fixup.
398*0b57cec5SDimitry Andric       if (StillReachable != OuterLoop) {
399*0b57cec5SDimitry Andric         LI.changeLoopFor(NewPreheader, StillReachable);
400*0b57cec5SDimitry Andric         removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
401*0b57cec5SDimitry Andric         for (auto *BB : L.blocks())
402*0b57cec5SDimitry Andric           removeBlockFromLoops(BB, OuterLoop, StillReachable);
403*0b57cec5SDimitry Andric         OuterLoop->removeChildLoop(&L);
404*0b57cec5SDimitry Andric         if (StillReachable)
405*0b57cec5SDimitry Andric           StillReachable->addChildLoop(&L);
406*0b57cec5SDimitry Andric         else
407*0b57cec5SDimitry Andric           LI.addTopLevelLoop(&L);
408*0b57cec5SDimitry Andric 
409*0b57cec5SDimitry Andric         // Some values from loops in [OuterLoop, StillReachable) could be used
410*0b57cec5SDimitry Andric         // in the current loop. Now it is not their child anymore, so such uses
411*0b57cec5SDimitry Andric         // require LCSSA Phis.
412*0b57cec5SDimitry Andric         Loop *FixLCSSALoop = OuterLoop;
413*0b57cec5SDimitry Andric         while (FixLCSSALoop->getParentLoop() != StillReachable)
414*0b57cec5SDimitry Andric           FixLCSSALoop = FixLCSSALoop->getParentLoop();
415*0b57cec5SDimitry Andric         assert(FixLCSSALoop && "Should be a loop!");
416*0b57cec5SDimitry Andric         // We need all DT updates to be done before forming LCSSA.
417*0b57cec5SDimitry Andric         if (MSSAU)
418e8d8bef9SDimitry Andric           MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
419e8d8bef9SDimitry Andric         else
420e8d8bef9SDimitry Andric           DTU.applyUpdates(DTUpdates);
421*0b57cec5SDimitry Andric         DTUpdates.clear();
422*0b57cec5SDimitry Andric         formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
423*0b57cec5SDimitry Andric       }
424*0b57cec5SDimitry Andric     }
425*0b57cec5SDimitry Andric 
426*0b57cec5SDimitry Andric     if (MSSAU) {
427*0b57cec5SDimitry Andric       // Clear all updates now. Facilitates deletes that follow.
428e8d8bef9SDimitry Andric       MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
429*0b57cec5SDimitry Andric       DTUpdates.clear();
430*0b57cec5SDimitry Andric       if (VerifyMemorySSA)
431*0b57cec5SDimitry Andric         MSSAU->getMemorySSA()->verifyMemorySSA();
432*0b57cec5SDimitry Andric     }
433*0b57cec5SDimitry Andric   }
434*0b57cec5SDimitry Andric 
435*0b57cec5SDimitry Andric   /// Delete loop blocks that have become unreachable after folding. Make all
436*0b57cec5SDimitry Andric   /// relevant updates to DT and LI.
437*0b57cec5SDimitry Andric   void deleteDeadLoopBlocks() {
438*0b57cec5SDimitry Andric     if (MSSAU) {
439*0b57cec5SDimitry Andric       SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
440*0b57cec5SDimitry Andric                                                         DeadLoopBlocks.end());
441*0b57cec5SDimitry Andric       MSSAU->removeBlocks(DeadLoopBlocksSet);
442*0b57cec5SDimitry Andric     }
443*0b57cec5SDimitry Andric 
444*0b57cec5SDimitry Andric     // The function LI.erase has some invariants that need to be preserved when
445*0b57cec5SDimitry Andric     // it tries to remove a loop which is not the top-level loop. In particular,
446*0b57cec5SDimitry Andric     // it requires loop's preheader to be strictly in loop's parent. We cannot
447*0b57cec5SDimitry Andric     // just remove blocks one by one, because after removal of preheader we may
448*0b57cec5SDimitry Andric     // break this invariant for the dead loop. So we detatch and erase all dead
449*0b57cec5SDimitry Andric     // loops beforehand.
450*0b57cec5SDimitry Andric     for (auto *BB : DeadLoopBlocks)
451*0b57cec5SDimitry Andric       if (LI.isLoopHeader(BB)) {
452*0b57cec5SDimitry Andric         assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
453*0b57cec5SDimitry Andric         Loop *DL = LI.getLoopFor(BB);
454e8d8bef9SDimitry Andric         if (!DL->isOutermost()) {
455*0b57cec5SDimitry Andric           for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
456*0b57cec5SDimitry Andric             for (auto *BB : DL->getBlocks())
457*0b57cec5SDimitry Andric               PL->removeBlockFromLoop(BB);
458*0b57cec5SDimitry Andric           DL->getParentLoop()->removeChildLoop(DL);
459*0b57cec5SDimitry Andric           LI.addTopLevelLoop(DL);
460*0b57cec5SDimitry Andric         }
461*0b57cec5SDimitry Andric         LI.erase(DL);
462*0b57cec5SDimitry Andric       }
463*0b57cec5SDimitry Andric 
464*0b57cec5SDimitry Andric     for (auto *BB : DeadLoopBlocks) {
465*0b57cec5SDimitry Andric       assert(BB != L.getHeader() &&
466*0b57cec5SDimitry Andric              "Header of the current loop cannot be dead!");
467*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
468*0b57cec5SDimitry Andric                         << "\n");
469*0b57cec5SDimitry Andric       LI.removeBlock(BB);
470*0b57cec5SDimitry Andric     }
471*0b57cec5SDimitry Andric 
472*0b57cec5SDimitry Andric     DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
473*0b57cec5SDimitry Andric     DTU.applyUpdates(DTUpdates);
474*0b57cec5SDimitry Andric     DTUpdates.clear();
475*0b57cec5SDimitry Andric     for (auto *BB : DeadLoopBlocks)
476*0b57cec5SDimitry Andric       DTU.deleteBB(BB);
477*0b57cec5SDimitry Andric 
478*0b57cec5SDimitry Andric     NumLoopBlocksDeleted += DeadLoopBlocks.size();
479*0b57cec5SDimitry Andric   }
480*0b57cec5SDimitry Andric 
481*0b57cec5SDimitry Andric   /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
482*0b57cec5SDimitry Andric   /// unconditional branches.
483*0b57cec5SDimitry Andric   void foldTerminators() {
484*0b57cec5SDimitry Andric     for (BasicBlock *BB : FoldCandidates) {
485*0b57cec5SDimitry Andric       assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
486*0b57cec5SDimitry Andric       BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
487*0b57cec5SDimitry Andric       assert(TheOnlySucc && "Should have one live successor!");
488*0b57cec5SDimitry Andric 
489*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
490*0b57cec5SDimitry Andric                         << " with an unconditional branch to the block "
491*0b57cec5SDimitry Andric                         << TheOnlySucc->getName() << "\n");
492*0b57cec5SDimitry Andric 
493*0b57cec5SDimitry Andric       SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
494*0b57cec5SDimitry Andric       // Remove all BB's successors except for the live one.
495*0b57cec5SDimitry Andric       unsigned TheOnlySuccDuplicates = 0;
496*0b57cec5SDimitry Andric       for (auto *Succ : successors(BB))
497*0b57cec5SDimitry Andric         if (Succ != TheOnlySucc) {
498*0b57cec5SDimitry Andric           DeadSuccessors.insert(Succ);
499*0b57cec5SDimitry Andric           // If our successor lies in a different loop, we don't want to remove
500*0b57cec5SDimitry Andric           // the one-input Phi because it is a LCSSA Phi.
501*0b57cec5SDimitry Andric           bool PreserveLCSSAPhi = !L.contains(Succ);
502*0b57cec5SDimitry Andric           Succ->removePredecessor(BB, PreserveLCSSAPhi);
503*0b57cec5SDimitry Andric           if (MSSAU)
504*0b57cec5SDimitry Andric             MSSAU->removeEdge(BB, Succ);
505*0b57cec5SDimitry Andric         } else
506*0b57cec5SDimitry Andric           ++TheOnlySuccDuplicates;
507*0b57cec5SDimitry Andric 
508*0b57cec5SDimitry Andric       assert(TheOnlySuccDuplicates > 0 && "Should be!");
509*0b57cec5SDimitry Andric       // If TheOnlySucc was BB's successor more than once, after transform it
510*0b57cec5SDimitry Andric       // will be its successor only once. Remove redundant inputs from
511*0b57cec5SDimitry Andric       // TheOnlySucc's Phis.
512*0b57cec5SDimitry Andric       bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
513*0b57cec5SDimitry Andric       for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
514*0b57cec5SDimitry Andric         TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
515*0b57cec5SDimitry Andric       if (MSSAU && TheOnlySuccDuplicates > 1)
516*0b57cec5SDimitry Andric         MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
517*0b57cec5SDimitry Andric 
518*0b57cec5SDimitry Andric       IRBuilder<> Builder(BB->getContext());
519*0b57cec5SDimitry Andric       Instruction *Term = BB->getTerminator();
520*0b57cec5SDimitry Andric       Builder.SetInsertPoint(Term);
521*0b57cec5SDimitry Andric       Builder.CreateBr(TheOnlySucc);
522*0b57cec5SDimitry Andric       Term->eraseFromParent();
523*0b57cec5SDimitry Andric 
524*0b57cec5SDimitry Andric       for (auto *DeadSucc : DeadSuccessors)
525*0b57cec5SDimitry Andric         DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
526*0b57cec5SDimitry Andric 
527*0b57cec5SDimitry Andric       ++NumTerminatorsFolded;
528*0b57cec5SDimitry Andric     }
529*0b57cec5SDimitry Andric   }
530*0b57cec5SDimitry Andric 
531*0b57cec5SDimitry Andric public:
532*0b57cec5SDimitry Andric   ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
533*0b57cec5SDimitry Andric                                 ScalarEvolution &SE,
534*0b57cec5SDimitry Andric                                 MemorySSAUpdater *MSSAU)
535*0b57cec5SDimitry Andric       : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
536*0b57cec5SDimitry Andric         DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
537*0b57cec5SDimitry Andric   bool run() {
538*0b57cec5SDimitry Andric     assert(L.getLoopLatch() && "Should be single latch!");
539*0b57cec5SDimitry Andric 
540*0b57cec5SDimitry Andric     // Collect all available information about status of blocks after constant
541*0b57cec5SDimitry Andric     // folding.
542*0b57cec5SDimitry Andric     analyze();
543*0b57cec5SDimitry Andric     BasicBlock *Header = L.getHeader();
544*0b57cec5SDimitry Andric     (void)Header;
545*0b57cec5SDimitry Andric 
546*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
547*0b57cec5SDimitry Andric                       << ": ");
548*0b57cec5SDimitry Andric 
549*0b57cec5SDimitry Andric     if (HasIrreducibleCFG) {
550*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
551*0b57cec5SDimitry Andric       return false;
552*0b57cec5SDimitry Andric     }
553*0b57cec5SDimitry Andric 
554*0b57cec5SDimitry Andric     // Nothing to constant-fold.
555*0b57cec5SDimitry Andric     if (FoldCandidates.empty()) {
556*0b57cec5SDimitry Andric       LLVM_DEBUG(
557*0b57cec5SDimitry Andric           dbgs() << "No constant terminator folding candidates found in loop "
558*0b57cec5SDimitry Andric                  << Header->getName() << "\n");
559*0b57cec5SDimitry Andric       return false;
560*0b57cec5SDimitry Andric     }
561*0b57cec5SDimitry Andric 
562*0b57cec5SDimitry Andric     // TODO: Support deletion of the current loop.
563*0b57cec5SDimitry Andric     if (DeleteCurrentLoop) {
564*0b57cec5SDimitry Andric       LLVM_DEBUG(
565*0b57cec5SDimitry Andric           dbgs()
566*0b57cec5SDimitry Andric           << "Give up constant terminator folding in loop " << Header->getName()
567*0b57cec5SDimitry Andric           << ": we don't currently support deletion of the current loop.\n");
568*0b57cec5SDimitry Andric       return false;
569*0b57cec5SDimitry Andric     }
570*0b57cec5SDimitry Andric 
571*0b57cec5SDimitry Andric     // TODO: Support blocks that are not dead, but also not in loop after the
572*0b57cec5SDimitry Andric     // folding.
573*0b57cec5SDimitry Andric     if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
574*0b57cec5SDimitry Andric         L.getNumBlocks()) {
575*0b57cec5SDimitry Andric       LLVM_DEBUG(
576*0b57cec5SDimitry Andric           dbgs() << "Give up constant terminator folding in loop "
577*0b57cec5SDimitry Andric                  << Header->getName() << ": we don't currently"
578*0b57cec5SDimitry Andric                     " support blocks that are not dead, but will stop "
579*0b57cec5SDimitry Andric                     "being a part of the loop after constant-folding.\n");
580*0b57cec5SDimitry Andric       return false;
581*0b57cec5SDimitry Andric     }
582*0b57cec5SDimitry Andric 
583*0b57cec5SDimitry Andric     SE.forgetTopmostLoop(&L);
584*0b57cec5SDimitry Andric     // Dump analysis results.
585*0b57cec5SDimitry Andric     LLVM_DEBUG(dump());
586*0b57cec5SDimitry Andric 
587*0b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
588*0b57cec5SDimitry Andric                       << " terminators in loop " << Header->getName() << "\n");
589*0b57cec5SDimitry Andric 
590*0b57cec5SDimitry Andric     // Make the actual transforms.
591*0b57cec5SDimitry Andric     handleDeadExits();
592*0b57cec5SDimitry Andric     foldTerminators();
593*0b57cec5SDimitry Andric 
594*0b57cec5SDimitry Andric     if (!DeadLoopBlocks.empty()) {
595*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
596*0b57cec5SDimitry Andric                     << " dead blocks in loop " << Header->getName() << "\n");
597*0b57cec5SDimitry Andric       deleteDeadLoopBlocks();
598*0b57cec5SDimitry Andric     } else {
599*0b57cec5SDimitry Andric       // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
600*0b57cec5SDimitry Andric       DTU.applyUpdates(DTUpdates);
601*0b57cec5SDimitry Andric       DTUpdates.clear();
602*0b57cec5SDimitry Andric     }
603*0b57cec5SDimitry Andric 
604*0b57cec5SDimitry Andric     if (MSSAU && VerifyMemorySSA)
605*0b57cec5SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
606*0b57cec5SDimitry Andric 
607*0b57cec5SDimitry Andric #ifndef NDEBUG
608*0b57cec5SDimitry Andric     // Make sure that we have preserved all data structures after the transform.
609*0b57cec5SDimitry Andric #if defined(EXPENSIVE_CHECKS)
610*0b57cec5SDimitry Andric     assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
611*0b57cec5SDimitry Andric            "DT broken after transform!");
612*0b57cec5SDimitry Andric #else
613*0b57cec5SDimitry Andric     assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
614*0b57cec5SDimitry Andric            "DT broken after transform!");
615*0b57cec5SDimitry Andric #endif
616*0b57cec5SDimitry Andric     assert(DT.isReachableFromEntry(Header));
617*0b57cec5SDimitry Andric     LI.verify(DT);
618*0b57cec5SDimitry Andric #endif
619*0b57cec5SDimitry Andric 
620*0b57cec5SDimitry Andric     return true;
621*0b57cec5SDimitry Andric   }
622*0b57cec5SDimitry Andric 
623*0b57cec5SDimitry Andric   bool foldingBreaksCurrentLoop() const {
624*0b57cec5SDimitry Andric     return DeleteCurrentLoop;
625*0b57cec5SDimitry Andric   }
626*0b57cec5SDimitry Andric };
627*0b57cec5SDimitry Andric } // namespace
628*0b57cec5SDimitry Andric 
629*0b57cec5SDimitry Andric /// Turn branches and switches with known constant conditions into unconditional
630*0b57cec5SDimitry Andric /// branches.
631*0b57cec5SDimitry Andric static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
632*0b57cec5SDimitry Andric                                     ScalarEvolution &SE,
633*0b57cec5SDimitry Andric                                     MemorySSAUpdater *MSSAU,
634*0b57cec5SDimitry Andric                                     bool &IsLoopDeleted) {
635*0b57cec5SDimitry Andric   if (!EnableTermFolding)
636*0b57cec5SDimitry Andric     return false;
637*0b57cec5SDimitry Andric 
638*0b57cec5SDimitry Andric   // To keep things simple, only process loops with single latch. We
639*0b57cec5SDimitry Andric   // canonicalize most loops to this form. We can support multi-latch if needed.
640*0b57cec5SDimitry Andric   if (!L.getLoopLatch())
641*0b57cec5SDimitry Andric     return false;
642*0b57cec5SDimitry Andric 
643*0b57cec5SDimitry Andric   ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
644*0b57cec5SDimitry Andric   bool Changed = BranchFolder.run();
645*0b57cec5SDimitry Andric   IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
646*0b57cec5SDimitry Andric   return Changed;
647*0b57cec5SDimitry Andric }
648*0b57cec5SDimitry Andric 
649*0b57cec5SDimitry Andric static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
650*0b57cec5SDimitry Andric                                         LoopInfo &LI, MemorySSAUpdater *MSSAU) {
651*0b57cec5SDimitry Andric   bool Changed = false;
652*0b57cec5SDimitry Andric   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
653*0b57cec5SDimitry Andric   // Copy blocks into a temporary array to avoid iterator invalidation issues
654*0b57cec5SDimitry Andric   // as we remove them.
655*0b57cec5SDimitry Andric   SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
656*0b57cec5SDimitry Andric 
657*0b57cec5SDimitry Andric   for (auto &Block : Blocks) {
658*0b57cec5SDimitry Andric     // Attempt to merge blocks in the trivial case. Don't modify blocks which
659*0b57cec5SDimitry Andric     // belong to other loops.
660*0b57cec5SDimitry Andric     BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
661*0b57cec5SDimitry Andric     if (!Succ)
662*0b57cec5SDimitry Andric       continue;
663*0b57cec5SDimitry Andric 
664*0b57cec5SDimitry Andric     BasicBlock *Pred = Succ->getSinglePredecessor();
665*0b57cec5SDimitry Andric     if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
666*0b57cec5SDimitry Andric       continue;
667*0b57cec5SDimitry Andric 
668*0b57cec5SDimitry Andric     // Merge Succ into Pred and delete it.
669*0b57cec5SDimitry Andric     MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
670*0b57cec5SDimitry Andric 
671480093f4SDimitry Andric     if (MSSAU && VerifyMemorySSA)
672480093f4SDimitry Andric       MSSAU->getMemorySSA()->verifyMemorySSA();
673480093f4SDimitry Andric 
674*0b57cec5SDimitry Andric     Changed = true;
675*0b57cec5SDimitry Andric   }
676*0b57cec5SDimitry Andric 
677*0b57cec5SDimitry Andric   return Changed;
678*0b57cec5SDimitry Andric }
679*0b57cec5SDimitry Andric 
680*0b57cec5SDimitry Andric static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
681*0b57cec5SDimitry Andric                             ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
6825ffd83dbSDimitry Andric                             bool &IsLoopDeleted) {
683*0b57cec5SDimitry Andric   bool Changed = false;
684*0b57cec5SDimitry Andric 
685*0b57cec5SDimitry Andric   // Constant-fold terminators with known constant conditions.
6865ffd83dbSDimitry Andric   Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);
687*0b57cec5SDimitry Andric 
6885ffd83dbSDimitry Andric   if (IsLoopDeleted)
689*0b57cec5SDimitry Andric     return true;
690*0b57cec5SDimitry Andric 
691*0b57cec5SDimitry Andric   // Eliminate unconditional branches by merging blocks into their predecessors.
692*0b57cec5SDimitry Andric   Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
693*0b57cec5SDimitry Andric 
694*0b57cec5SDimitry Andric   if (Changed)
695*0b57cec5SDimitry Andric     SE.forgetTopmostLoop(&L);
696*0b57cec5SDimitry Andric 
697*0b57cec5SDimitry Andric   return Changed;
698*0b57cec5SDimitry Andric }
699*0b57cec5SDimitry Andric 
700*0b57cec5SDimitry Andric PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
701*0b57cec5SDimitry Andric                                            LoopStandardAnalysisResults &AR,
702*0b57cec5SDimitry Andric                                            LPMUpdater &LPMU) {
703*0b57cec5SDimitry Andric   Optional<MemorySSAUpdater> MSSAU;
7048bcb0991SDimitry Andric   if (AR.MSSA)
705*0b57cec5SDimitry Andric     MSSAU = MemorySSAUpdater(AR.MSSA);
706*0b57cec5SDimitry Andric   bool DeleteCurrentLoop = false;
707*0b57cec5SDimitry Andric   if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
708*0b57cec5SDimitry Andric                        MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
709*0b57cec5SDimitry Andric                        DeleteCurrentLoop))
710*0b57cec5SDimitry Andric     return PreservedAnalyses::all();
711*0b57cec5SDimitry Andric 
712*0b57cec5SDimitry Andric   if (DeleteCurrentLoop)
713*0b57cec5SDimitry Andric     LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
714*0b57cec5SDimitry Andric 
715*0b57cec5SDimitry Andric   auto PA = getLoopPassPreservedAnalyses();
7168bcb0991SDimitry Andric   if (AR.MSSA)
717*0b57cec5SDimitry Andric     PA.preserve<MemorySSAAnalysis>();
718*0b57cec5SDimitry Andric   return PA;
719*0b57cec5SDimitry Andric }
720*0b57cec5SDimitry Andric 
721*0b57cec5SDimitry Andric namespace {
722*0b57cec5SDimitry Andric class LoopSimplifyCFGLegacyPass : public LoopPass {
723*0b57cec5SDimitry Andric public:
724*0b57cec5SDimitry Andric   static char ID; // Pass ID, replacement for typeid
725*0b57cec5SDimitry Andric   LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
726*0b57cec5SDimitry Andric     initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
727*0b57cec5SDimitry Andric   }
728*0b57cec5SDimitry Andric 
729*0b57cec5SDimitry Andric   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
730*0b57cec5SDimitry Andric     if (skipLoop(L))
731*0b57cec5SDimitry Andric       return false;
732*0b57cec5SDimitry Andric 
733*0b57cec5SDimitry Andric     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
734*0b57cec5SDimitry Andric     LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
735*0b57cec5SDimitry Andric     ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
736*0b57cec5SDimitry Andric     Optional<MemorySSAUpdater> MSSAU;
737*0b57cec5SDimitry Andric     if (EnableMSSALoopDependency) {
738*0b57cec5SDimitry Andric       MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
739*0b57cec5SDimitry Andric       MSSAU = MemorySSAUpdater(MSSA);
740*0b57cec5SDimitry Andric       if (VerifyMemorySSA)
741*0b57cec5SDimitry Andric         MSSA->verifyMemorySSA();
742*0b57cec5SDimitry Andric     }
743*0b57cec5SDimitry Andric     bool DeleteCurrentLoop = false;
744*0b57cec5SDimitry Andric     bool Changed = simplifyLoopCFG(
745*0b57cec5SDimitry Andric         *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
746*0b57cec5SDimitry Andric         DeleteCurrentLoop);
747*0b57cec5SDimitry Andric     if (DeleteCurrentLoop)
748*0b57cec5SDimitry Andric       LPM.markLoopAsDeleted(*L);
749*0b57cec5SDimitry Andric     return Changed;
750*0b57cec5SDimitry Andric   }
751*0b57cec5SDimitry Andric 
752*0b57cec5SDimitry Andric   void getAnalysisUsage(AnalysisUsage &AU) const override {
753*0b57cec5SDimitry Andric     if (EnableMSSALoopDependency) {
754*0b57cec5SDimitry Andric       AU.addRequired<MemorySSAWrapperPass>();
755*0b57cec5SDimitry Andric       AU.addPreserved<MemorySSAWrapperPass>();
756*0b57cec5SDimitry Andric     }
757*0b57cec5SDimitry Andric     AU.addPreserved<DependenceAnalysisWrapperPass>();
758*0b57cec5SDimitry Andric     getLoopAnalysisUsage(AU);
759*0b57cec5SDimitry Andric   }
760*0b57cec5SDimitry Andric };
7615ffd83dbSDimitry Andric } // end namespace
762*0b57cec5SDimitry Andric 
763*0b57cec5SDimitry Andric char LoopSimplifyCFGLegacyPass::ID = 0;
764*0b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
765*0b57cec5SDimitry Andric                       "Simplify loop CFG", false, false)
766*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopPass)
767*0b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
768*0b57cec5SDimitry Andric INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
769*0b57cec5SDimitry Andric                     "Simplify loop CFG", false, false)
770*0b57cec5SDimitry Andric 
771*0b57cec5SDimitry Andric Pass *llvm::createLoopSimplifyCFGPass() {
772*0b57cec5SDimitry Andric   return new LoopSimplifyCFGLegacyPass();
773*0b57cec5SDimitry Andric }
774