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