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