blob: 960ba1390fd3da9398c20d2c7776c7cd66b50b0b [file] [log] [blame]
Fiona Glaserb417d462016-01-29 22:35:36 +00001//===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Fiona Glaserb417d462016-01-29 22:35:36 +00006//
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
Justin Bognerab6a5132016-05-03 21:47:32 +000016#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000020#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000021#include "llvm/Analysis/BasicAliasAnalysis.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000022#include "llvm/Analysis/DependenceAnalysis.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000023#include "llvm/Analysis/DomTreeUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000024#include "llvm/Analysis/GlobalsModRef.h"
25#include "llvm/Analysis/LoopInfo.h"
26#include "llvm/Analysis/LoopPass.h"
Alina Sbirlea8b83d682018-08-22 20:10:21 +000027#include "llvm/Analysis/MemorySSA.h"
28#include "llvm/Analysis/MemorySSAUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000029#include "llvm/Analysis/ScalarEvolution.h"
30#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
31#include "llvm/Analysis/TargetTransformInfo.h"
32#include "llvm/IR/Dominators.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080033#include "llvm/InitializePasses.h"
Reid Kleckner4c1a1d32019-11-14 15:15:48 -080034#include "llvm/Support/CommandLine.h"
Justin Bognerab6a5132016-05-03 21:47:32 +000035#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000036#include "llvm/Transforms/Scalar/LoopPassManager.h"
David Blaikiea373d182018-03-28 17:44:36 +000037#include "llvm/Transforms/Utils.h"
Alina Sbirleadfd14ad2018-06-20 22:01:04 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000040#include "llvm/Transforms/Utils/LoopUtils.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000041using namespace llvm;
42
43#define DEBUG_TYPE "loop-simplifycfg"
44
Max Kazantseve1c2dc22018-11-23 09:14:53 +000045static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
Max Kazantsev5cf777e2019-02-13 06:12:48 +000046 cl::init(true));
Max Kazantseve1c2dc22018-11-23 09:14:53 +000047
Max Kazantsevc04b5302018-11-20 05:43:32 +000048STATISTIC(NumTerminatorsFolded,
49 "Number of terminators folded to unconditional branches");
Max Kazantsev347c5832018-12-24 06:06:17 +000050STATISTIC(NumLoopBlocksDeleted,
51 "Number of loop blocks deleted");
Max Kazantsevedabb9a2018-12-24 07:41:33 +000052STATISTIC(NumLoopExitsDeleted,
53 "Number of loop exiting edges deleted");
Max Kazantsevc04b5302018-11-20 05:43:32 +000054
55/// If \p BB is a switch or a conditional branch, but only one of its successors
56/// can be reached from this block in runtime, return this successor. Otherwise,
57/// return nullptr.
58static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
59 Instruction *TI = BB->getTerminator();
60 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
61 if (BI->isUnconditional())
62 return nullptr;
63 if (BI->getSuccessor(0) == BI->getSuccessor(1))
64 return BI->getSuccessor(0);
65 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
66 if (!Cond)
67 return nullptr;
68 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
69 }
70
71 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
72 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
73 if (!CI)
74 return nullptr;
75 for (auto Case : SI->cases())
76 if (Case.getCaseValue() == CI)
77 return Case.getCaseSuccessor();
78 return SI->getDefaultDest();
79 }
80
81 return nullptr;
82}
83
Max Kazantsevc065b022019-02-15 12:18:10 +000084/// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
85static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
86 Loop *LastLoop = nullptr) {
87 assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
88 "First loop is supposed to be inside of last loop!");
89 assert(FirstLoop->contains(BB) && "Must be a loop block!");
90 for (Loop *Current = FirstLoop; Current != LastLoop;
91 Current = Current->getParentLoop())
92 Current->removeBlockFromLoop(BB);
93}
94
Max Kazantsevd72c1a02019-02-17 15:22:48 +000095/// Find innermost loop that contains at least one block from \p BBs and
96/// contains the header of loop \p L.
97static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
98 Loop &L, LoopInfo &LI) {
Max Kazantsev45614752019-02-17 18:21:51 +000099 Loop *Innermost = nullptr;
Max Kazantsev0f943262019-02-17 15:04:09 +0000100 for (BasicBlock *BB : BBs) {
101 Loop *BBL = LI.getLoopFor(BB);
Max Kazantsev45614752019-02-17 18:21:51 +0000102 while (BBL && !BBL->contains(L.getHeader()))
103 BBL = BBL->getParentLoop();
104 if (BBL == &L)
105 BBL = BBL->getParentLoop();
106 if (!BBL)
107 continue;
108 if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
109 Innermost = BBL;
Max Kazantsev0f943262019-02-17 15:04:09 +0000110 }
Max Kazantsev45614752019-02-17 18:21:51 +0000111 return Innermost;
Max Kazantsev0f943262019-02-17 15:04:09 +0000112}
113
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000114namespace {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000115/// Helper class that can turn branches and switches with constant conditions
116/// into unconditional branches.
117class ConstantTerminatorFoldingImpl {
118private:
119 Loop &L;
120 LoopInfo &LI;
121 DominatorTree &DT;
Max Kazantsev201534d2018-12-29 04:26:22 +0000122 ScalarEvolution &SE;
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000123 MemorySSAUpdater *MSSAU;
Max Kazantsev136f09b2019-02-15 11:39:35 +0000124 LoopBlocksDFS DFS;
Simon Pilgrim623c38d2019-02-15 12:13:16 +0000125 DomTreeUpdater DTU;
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000126 SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000127
Max Kazantseva523a212018-12-07 05:44:45 +0000128 // Whether or not the current loop has irreducible CFG.
129 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000130 // Whether or not the current loop will still exist after terminator constant
131 // folding will be done. In theory, there are two ways how it can happen:
132 // 1. Loop's latch(es) become unreachable from loop header;
133 // 2. Loop's header becomes unreachable from method entry.
134 // In practice, the second situation is impossible because we only modify the
135 // current loop and its preheader and do not affect preheader's reachibility
136 // from any other block. So this variable set to true means that loop's latch
137 // has become unreachable from loop header.
138 bool DeleteCurrentLoop = false;
139
140 // The blocks of the original loop that will still be reachable from entry
141 // after the constant folding.
142 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
143 // The blocks of the original loop that will become unreachable from entry
144 // after the constant folding.
Max Kazantsev80e4b402018-12-28 06:08:51 +0000145 SmallVector<BasicBlock *, 8> DeadLoopBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000146 // The exits of the original loop that will still be reachable from entry
147 // after the constant folding.
148 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
149 // The exits of the original loop that will become unreachable from entry
150 // after the constant folding.
Max Kazantsev56a24432018-11-22 12:33:41 +0000151 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000152 // The blocks that will still be a part of the current loop after folding.
153 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
154 // The blocks that have terminators with constant condition that can be
155 // folded. Note: fold candidates should be in L but not in any of its
156 // subloops to avoid complex LI updates.
157 SmallVector<BasicBlock *, 8> FoldCandidates;
158
159 void dump() const {
160 dbgs() << "Constant terminator folding for loop " << L << "\n";
161 dbgs() << "After terminator constant-folding, the loop will";
162 if (!DeleteCurrentLoop)
163 dbgs() << " not";
164 dbgs() << " be destroyed\n";
Max Kazantsev56a24432018-11-22 12:33:41 +0000165 auto PrintOutVector = [&](const char *Message,
166 const SmallVectorImpl<BasicBlock *> &S) {
167 dbgs() << Message << "\n";
168 for (const BasicBlock *BB : S)
169 dbgs() << "\t" << BB->getName() << "\n";
170 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000171 auto PrintOutSet = [&](const char *Message,
172 const SmallPtrSetImpl<BasicBlock *> &S) {
173 dbgs() << Message << "\n";
174 for (const BasicBlock *BB : S)
175 dbgs() << "\t" << BB->getName() << "\n";
176 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000177 PrintOutVector("Blocks in which we can constant-fold terminator:",
178 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000179 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
Max Kazantsev80e4b402018-12-28 06:08:51 +0000180 PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000181 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000182 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000183 if (!DeleteCurrentLoop)
184 PrintOutSet("The following blocks will still be part of the loop:",
185 BlocksInLoopAfterFolding);
186 }
187
Max Kazantseva523a212018-12-07 05:44:45 +0000188 /// Whether or not the current loop has irreducible CFG.
189 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
190 assert(DFS.isComplete() && "DFS is expected to be finished");
191 // Index of a basic block in RPO traversal.
192 DenseMap<const BasicBlock *, unsigned> RPO;
193 unsigned Current = 0;
194 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
195 RPO[*I] = Current++;
196
197 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
198 BasicBlock *BB = *I;
199 for (auto *Succ : successors(BB))
200 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
201 // If an edge goes from a block with greater order number into a block
202 // with lesses number, and it is not a loop backedge, then it can only
203 // be a part of irreducible non-loop cycle.
204 return true;
205 }
206 return false;
207 }
208
Max Kazantsevc04b5302018-11-20 05:43:32 +0000209 /// Fill all information about status of blocks and exits of the current loop
210 /// if constant folding of all branches will be done.
211 void analyze() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000212 DFS.perform(&LI);
213 assert(DFS.isComplete() && "DFS is expected to be finished");
214
Max Kazantseva523a212018-12-07 05:44:45 +0000215 // TODO: The algorithm below relies on both RPO and Postorder traversals.
216 // When the loop has only reducible CFG inside, then the invariant "all
217 // predecessors of X are processed before X in RPO" is preserved. However
218 // an irreducible loop can break this invariant (e.g. latch does not have to
219 // be the last block in the traversal in this case, and the algorithm relies
220 // on this). We can later decide to support such cases by altering the
221 // algorithms, but so far we just give up analyzing them.
222 if (hasIrreducibleCFG(DFS)) {
223 HasIrreducibleCFG = true;
224 return;
225 }
226
Max Kazantsevc04b5302018-11-20 05:43:32 +0000227 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000228 LiveLoopBlocks.insert(L.getHeader());
229 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
230 BasicBlock *BB = *I;
231
232 // If a loop block wasn't marked as live so far, then it's dead.
233 if (!LiveLoopBlocks.count(BB)) {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000234 DeadLoopBlocks.push_back(BB);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000235 continue;
236 }
237
238 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
239
240 // If a block has only one live successor, it's a candidate on constant
241 // folding. Only handle blocks from current loop: branches in child loops
242 // are skipped because if they can be folded, they should be folded during
243 // the processing of child loops.
Max Kazantsev56515a22019-01-24 05:20:29 +0000244 bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
245 if (TakeFoldCandidate)
Max Kazantsevc04b5302018-11-20 05:43:32 +0000246 FoldCandidates.push_back(BB);
247
248 // Handle successors.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000249 for (BasicBlock *Succ : successors(BB))
Max Kazantsev56515a22019-01-24 05:20:29 +0000250 if (!TakeFoldCandidate || TheOnlySucc == Succ) {
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000251 if (L.contains(Succ))
252 LiveLoopBlocks.insert(Succ);
253 else
254 LiveExitBlocks.insert(Succ);
255 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000256 }
257
258 // Sanity check: amount of dead and live loop blocks should match the total
259 // number of blocks in loop.
260 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
261 "Malformed block sets?");
262
263 // Now, all exit blocks that are not marked as live are dead.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000264 SmallVector<BasicBlock *, 8> ExitBlocks;
265 L.getExitBlocks(ExitBlocks);
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000266 SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000267 for (auto *ExitBlock : ExitBlocks)
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000268 if (!LiveExitBlocks.count(ExitBlock) &&
269 UniqueDeadExits.insert(ExitBlock).second)
Max Kazantsev56a24432018-11-22 12:33:41 +0000270 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000271
272 // Whether or not the edge From->To will still be present in graph after the
273 // folding.
274 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
275 if (!LiveLoopBlocks.count(From))
276 return false;
277 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
Max Kazantsev38cd9ac2019-01-25 05:05:02 +0000278 return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000279 };
280
281 // The loop will not be destroyed if its latch is live.
282 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
283
284 // If we are going to delete the current loop completely, no extra analysis
285 // is needed.
286 if (DeleteCurrentLoop)
287 return;
288
289 // Otherwise, we should check which blocks will still be a part of the
290 // current loop after the transform.
291 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
292 // If the loop is live, then we should compute what blocks are still in
293 // loop after all branch folding has been done. A block is in loop if
294 // it has a live edge to another block that is in the loop; by definition,
295 // latch is in the loop.
296 auto BlockIsInLoop = [&](BasicBlock *BB) {
297 return any_of(successors(BB), [&](BasicBlock *Succ) {
298 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
299 });
300 };
301 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
302 BasicBlock *BB = *I;
303 if (BlockIsInLoop(BB))
304 BlocksInLoopAfterFolding.insert(BB);
305 }
306
307 // Sanity check: header must be in loop.
308 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
309 "Header not in loop?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000310 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
311 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000312 }
313
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000314 /// We need to preserve static reachibility of all loop exit blocks (this is)
315 /// required by loop pass manager. In order to do it, we make the following
316 /// trick:
317 ///
318 /// preheader:
319 /// <preheader code>
320 /// br label %loop_header
321 ///
322 /// loop_header:
323 /// ...
324 /// br i1 false, label %dead_exit, label %loop_block
325 /// ...
326 ///
327 /// We cannot simply remove edge from the loop to dead exit because in this
328 /// case dead_exit (and its successors) may become unreachable. To avoid that,
329 /// we insert the following fictive preheader:
330 ///
331 /// preheader:
332 /// <preheader code>
333 /// switch i32 0, label %preheader-split,
334 /// [i32 1, label %dead_exit_1],
335 /// [i32 2, label %dead_exit_2],
336 /// ...
337 /// [i32 N, label %dead_exit_N],
338 ///
339 /// preheader-split:
340 /// br label %loop_header
341 ///
342 /// loop_header:
343 /// ...
344 /// br i1 false, label %dead_exit_N, label %loop_block
345 /// ...
346 ///
347 /// Doing so, we preserve static reachibility of all dead exits and can later
348 /// remove edges from the loop to these blocks.
349 void handleDeadExits() {
350 // If no dead exits, nothing to do.
351 if (DeadExitBlocks.empty())
352 return;
353
354 // Construct split preheader and the dummy switch to thread edges from it to
355 // dead exits.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000356 BasicBlock *Preheader = L.getLoopPreheader();
Alina Sbirlead2d32442019-02-21 19:54:05 +0000357 BasicBlock *NewPreheader = llvm::SplitBlock(
358 Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
359
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000360 IRBuilder<> Builder(Preheader->getTerminator());
361 SwitchInst *DummySwitch =
362 Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
363 Preheader->getTerminator()->eraseFromParent();
364
365 unsigned DummyIdx = 1;
366 for (BasicBlock *BB : DeadExitBlocks) {
367 SmallVector<Instruction *, 4> DeadPhis;
368 for (auto &PN : BB->phis())
369 DeadPhis.push_back(&PN);
370
371 // Eliminate all Phis from dead exits.
372 for (Instruction *PN : DeadPhis) {
373 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
374 PN->eraseFromParent();
375 }
376 assert(DummyIdx != 0 && "Too many dead exits!");
377 DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000378 DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000379 ++NumLoopExitsDeleted;
380 }
381
382 assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
383 if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000384 // When we break dead edges, the outer loop may become unreachable from
385 // the current loop. We need to fix loop info accordingly. For this, we
386 // find the most nested loop that still contains L and remove L from all
387 // loops that are inside of it.
Max Kazantsevd72c1a02019-02-17 15:22:48 +0000388 Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000389
390 // Okay, our loop is no longer in the outer loop (and maybe not in some of
391 // its parents as well). Make the fixup.
392 if (StillReachable != OuterLoop) {
393 LI.changeLoopFor(NewPreheader, StillReachable);
Max Kazantsevc065b022019-02-15 12:18:10 +0000394 removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
395 for (auto *BB : L.blocks())
396 removeBlockFromLoops(BB, OuterLoop, StillReachable);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000397 OuterLoop->removeChildLoop(&L);
398 if (StillReachable)
399 StillReachable->addChildLoop(&L);
400 else
401 LI.addTopLevelLoop(&L);
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000402
403 // Some values from loops in [OuterLoop, StillReachable) could be used
404 // in the current loop. Now it is not their child anymore, so such uses
405 // require LCSSA Phis.
406 Loop *FixLCSSALoop = OuterLoop;
407 while (FixLCSSALoop->getParentLoop() != StillReachable)
408 FixLCSSALoop = FixLCSSALoop->getParentLoop();
409 assert(FixLCSSALoop && "Should be a loop!");
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000410 // We need all DT updates to be done before forming LCSSA.
411 DTU.applyUpdates(DTUpdates);
Alina Sbirlead2d32442019-02-21 19:54:05 +0000412 if (MSSAU)
413 MSSAU->applyUpdates(DTUpdates, DT);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000414 DTUpdates.clear();
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000415 formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000416 }
417 }
Alina Sbirlead2d32442019-02-21 19:54:05 +0000418
419 if (MSSAU) {
420 // Clear all updates now. Facilitates deletes that follow.
421 DTU.applyUpdates(DTUpdates);
422 MSSAU->applyUpdates(DTUpdates, DT);
423 DTUpdates.clear();
424 if (VerifyMemorySSA)
425 MSSAU->getMemorySSA()->verifyMemorySSA();
426 }
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000427 }
428
Max Kazantsev347c5832018-12-24 06:06:17 +0000429 /// Delete loop blocks that have become unreachable after folding. Make all
430 /// relevant updates to DT and LI.
431 void deleteDeadLoopBlocks() {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000432 if (MSSAU) {
Alina Sbirleadb101862019-07-12 22:30:30 +0000433 SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
434 DeadLoopBlocks.end());
Max Kazantsev80e4b402018-12-28 06:08:51 +0000435 MSSAU->removeBlocks(DeadLoopBlocksSet);
436 }
Max Kazantsevbf6af8f2019-02-12 09:37:00 +0000437
438 // The function LI.erase has some invariants that need to be preserved when
439 // it tries to remove a loop which is not the top-level loop. In particular,
440 // it requires loop's preheader to be strictly in loop's parent. We cannot
441 // just remove blocks one by one, because after removal of preheader we may
442 // break this invariant for the dead loop. So we detatch and erase all dead
443 // loops beforehand.
444 for (auto *BB : DeadLoopBlocks)
445 if (LI.isLoopHeader(BB)) {
446 assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
447 Loop *DL = LI.getLoopFor(BB);
448 if (DL->getParentLoop()) {
449 for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
450 for (auto *BB : DL->getBlocks())
451 PL->removeBlockFromLoop(BB);
452 DL->getParentLoop()->removeChildLoop(DL);
453 LI.addTopLevelLoop(DL);
454 }
455 LI.erase(DL);
456 }
457
Max Kazantsev347c5832018-12-24 06:06:17 +0000458 for (auto *BB : DeadLoopBlocks) {
459 assert(BB != L.getHeader() &&
460 "Header of the current loop cannot be dead!");
461 LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
462 << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000463 LI.removeBlock(BB);
Max Kazantsev347c5832018-12-24 06:06:17 +0000464 }
Max Kazantsev8b134162019-01-17 12:25:40 +0000465
Max Kazantsev6bf86152019-02-12 07:48:07 +0000466 DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000467 DTU.applyUpdates(DTUpdates);
468 DTUpdates.clear();
469 for (auto *BB : DeadLoopBlocks)
Max Kazantsev9aae9da2019-02-12 08:10:29 +0000470 DTU.deleteBB(BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000471
Max Kazantsev8b134162019-01-17 12:25:40 +0000472 NumLoopBlocksDeleted += DeadLoopBlocks.size();
Max Kazantsev347c5832018-12-24 06:06:17 +0000473 }
474
Max Kazantsevc04b5302018-11-20 05:43:32 +0000475 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
476 /// unconditional branches.
477 void foldTerminators() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000478 for (BasicBlock *BB : FoldCandidates) {
479 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
480 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
481 assert(TheOnlySucc && "Should have one live successor!");
482
483 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
484 << " with an unconditional branch to the block "
485 << TheOnlySucc->getName() << "\n");
486
487 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
488 // Remove all BB's successors except for the live one.
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000489 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000490 for (auto *Succ : successors(BB))
491 if (Succ != TheOnlySucc) {
492 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000493 // If our successor lies in a different loop, we don't want to remove
494 // the one-input Phi because it is a LCSSA Phi.
495 bool PreserveLCSSAPhi = !L.contains(Succ);
496 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000497 if (MSSAU)
498 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000499 } else
500 ++TheOnlySuccDuplicates;
501
502 assert(TheOnlySuccDuplicates > 0 && "Should be!");
503 // If TheOnlySucc was BB's successor more than once, after transform it
504 // will be its successor only once. Remove redundant inputs from
505 // TheOnlySucc's Phis.
506 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
507 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
508 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000509 if (MSSAU && TheOnlySuccDuplicates > 1)
510 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000511
512 IRBuilder<> Builder(BB->getContext());
513 Instruction *Term = BB->getTerminator();
514 Builder.SetInsertPoint(Term);
515 Builder.CreateBr(TheOnlySucc);
516 Term->eraseFromParent();
517
518 for (auto *DeadSucc : DeadSuccessors)
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000519 DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
Max Kazantsevc04b5302018-11-20 05:43:32 +0000520
521 ++NumTerminatorsFolded;
522 }
523 }
524
525public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000526 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
Max Kazantsev201534d2018-12-29 04:26:22 +0000527 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000528 MemorySSAUpdater *MSSAU)
Max Kazantsev136f09b2019-02-15 11:39:35 +0000529 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000530 DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000531 bool run() {
532 assert(L.getLoopLatch() && "Should be single latch!");
533
534 // Collect all available information about status of blocks after constant
535 // folding.
536 analyze();
Max Kazantsev30095d92019-02-19 11:13:58 +0000537 BasicBlock *Header = L.getHeader();
538 (void)Header;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000539
Max Kazantsev30095d92019-02-19 11:13:58 +0000540 LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
Max Kazantsevc04b5302018-11-20 05:43:32 +0000541 << ": ");
542
Max Kazantseva523a212018-12-07 05:44:45 +0000543 if (HasIrreducibleCFG) {
544 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
545 return false;
546 }
547
Max Kazantsevc04b5302018-11-20 05:43:32 +0000548 // Nothing to constant-fold.
549 if (FoldCandidates.empty()) {
550 LLVM_DEBUG(
551 dbgs() << "No constant terminator folding candidates found in loop "
Max Kazantsev30095d92019-02-19 11:13:58 +0000552 << Header->getName() << "\n");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000553 return false;
554 }
555
556 // TODO: Support deletion of the current loop.
557 if (DeleteCurrentLoop) {
558 LLVM_DEBUG(
559 dbgs()
Max Kazantsev30095d92019-02-19 11:13:58 +0000560 << "Give up constant terminator folding in loop " << Header->getName()
Max Kazantsevc04b5302018-11-20 05:43:32 +0000561 << ": we don't currently support deletion of the current loop.\n");
562 return false;
563 }
564
Max Kazantsevc04b5302018-11-20 05:43:32 +0000565 // TODO: Support blocks that are not dead, but also not in loop after the
566 // folding.
Max Kazantsev347c5832018-12-24 06:06:17 +0000567 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
568 L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000569 LLVM_DEBUG(
570 dbgs() << "Give up constant terminator folding in loop "
Max Kazantsev30095d92019-02-19 11:13:58 +0000571 << Header->getName() << ": we don't currently"
Max Kazantsevc04b5302018-11-20 05:43:32 +0000572 " support blocks that are not dead, but will stop "
573 "being a part of the loop after constant-folding.\n");
574 return false;
575 }
576
Max Kazantsev201534d2018-12-29 04:26:22 +0000577 SE.forgetTopmostLoop(&L);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000578 // Dump analysis results.
579 LLVM_DEBUG(dump());
580
581 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
Max Kazantsev30095d92019-02-19 11:13:58 +0000582 << " terminators in loop " << Header->getName() << "\n");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000583
584 // Make the actual transforms.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000585 handleDeadExits();
Max Kazantsevc04b5302018-11-20 05:43:32 +0000586 foldTerminators();
587
Max Kazantsev347c5832018-12-24 06:06:17 +0000588 if (!DeadLoopBlocks.empty()) {
589 LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
Max Kazantsev30095d92019-02-19 11:13:58 +0000590 << " dead blocks in loop " << Header->getName() << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000591 deleteDeadLoopBlocks();
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000592 } else {
593 // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
594 DTU.applyUpdates(DTUpdates);
595 DTUpdates.clear();
Max Kazantsev347c5832018-12-24 06:06:17 +0000596 }
597
Alina Sbirlead2d32442019-02-21 19:54:05 +0000598 if (MSSAU && VerifyMemorySSA)
599 MSSAU->getMemorySSA()->verifyMemorySSA();
600
Max Kazantsevc04b5302018-11-20 05:43:32 +0000601#ifndef NDEBUG
602 // Make sure that we have preserved all data structures after the transform.
Yevgeny Rouban0822bfc2019-04-29 13:29:55 +0000603#if defined(EXPENSIVE_CHECKS)
604 assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
605 "DT broken after transform!");
606#else
607 assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
608 "DT broken after transform!");
609#endif
Max Kazantsev30095d92019-02-19 11:13:58 +0000610 assert(DT.isReachableFromEntry(Header));
Max Kazantsevc04b5302018-11-20 05:43:32 +0000611 LI.verify(DT);
612#endif
613
614 return true;
615 }
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000616
617 bool foldingBreaksCurrentLoop() const {
618 return DeleteCurrentLoop;
619 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000620};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000621} // namespace
Max Kazantsevc04b5302018-11-20 05:43:32 +0000622
623/// Turn branches and switches with known constant conditions into unconditional
624/// branches.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000625static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsev201534d2018-12-29 04:26:22 +0000626 ScalarEvolution &SE,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000627 MemorySSAUpdater *MSSAU,
628 bool &IsLoopDeleted) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000629 if (!EnableTermFolding)
630 return false;
631
Max Kazantsevc04b5302018-11-20 05:43:32 +0000632 // To keep things simple, only process loops with single latch. We
633 // canonicalize most loops to this form. We can support multi-latch if needed.
634 if (!L.getLoopLatch())
635 return false;
636
Max Kazantsev201534d2018-12-29 04:26:22 +0000637 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000638 bool Changed = BranchFolder.run();
639 IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
640 return Changed;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000641}
642
Max Kazantsev46955b52018-11-01 09:42:50 +0000643static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
644 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000645 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000646 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000647 // Copy blocks into a temporary array to avoid iterator invalidation issues
648 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000649 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000650
651 for (auto &Block : Blocks) {
652 // Attempt to merge blocks in the trivial case. Don't modify blocks which
653 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000654 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000655 if (!Succ)
656 continue;
657
658 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000659 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000660 continue;
661
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000662 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000663 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000664
Alina Sbirleada4baa22019-11-20 13:44:51 -0800665 if (MSSAU && VerifyMemorySSA)
666 MSSAU->getMemorySSA()->verifyMemorySSA();
667
Fiona Glaserb417d462016-01-29 22:35:36 +0000668 Changed = true;
669 }
670
671 return Changed;
672}
673
Max Kazantsev46955b52018-11-01 09:42:50 +0000674static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000675 ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
Alina Sbirlea1c03cc52020-02-04 16:29:04 -0800676 bool &IsLoopDeleted) {
Max Kazantsev46955b52018-11-01 09:42:50 +0000677 bool Changed = false;
678
Max Kazantsevc04b5302018-11-20 05:43:32 +0000679 // Constant-fold terminators with known constant conditions.
Alina Sbirlea1c03cc52020-02-04 16:29:04 -0800680 Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000681
Alina Sbirlea1c03cc52020-02-04 16:29:04 -0800682 if (IsLoopDeleted)
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000683 return true;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000684
Max Kazantsev46955b52018-11-01 09:42:50 +0000685 // Eliminate unconditional branches by merging blocks into their predecessors.
686 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
687
688 if (Changed)
689 SE.forgetTopmostLoop(&L);
690
691 return Changed;
692}
693
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000694PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
695 LoopStandardAnalysisResults &AR,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000696 LPMUpdater &LPMU) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000697 Optional<MemorySSAUpdater> MSSAU;
Alina Sbirleaf92109d2019-08-17 01:02:12 +0000698 if (AR.MSSA)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000699 MSSAU = MemorySSAUpdater(AR.MSSA);
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000700 bool DeleteCurrentLoop = false;
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000701 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000702 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
703 DeleteCurrentLoop))
Justin Bognerab6a5132016-05-03 21:47:32 +0000704 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000705
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000706 if (DeleteCurrentLoop)
707 LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
708
Alina Sbirlea3cef1f72019-06-11 18:27:49 +0000709 auto PA = getLoopPassPreservedAnalyses();
Alina Sbirleaf92109d2019-08-17 01:02:12 +0000710 if (AR.MSSA)
Alina Sbirlea3cef1f72019-06-11 18:27:49 +0000711 PA.preserve<MemorySSAAnalysis>();
712 return PA;
Justin Bognerab6a5132016-05-03 21:47:32 +0000713}
714
715namespace {
716class LoopSimplifyCFGLegacyPass : public LoopPass {
717public:
718 static char ID; // Pass ID, replacement for typeid
719 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
720 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
721 }
722
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000723 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Justin Bognerab6a5132016-05-03 21:47:32 +0000724 if (skipLoop(L))
725 return false;
726
727 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
728 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000729 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000730 Optional<MemorySSAUpdater> MSSAU;
731 if (EnableMSSALoopDependency) {
732 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
733 MSSAU = MemorySSAUpdater(MSSA);
734 if (VerifyMemorySSA)
735 MSSA->verifyMemorySSA();
736 }
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000737 bool DeleteCurrentLoop = false;
738 bool Changed = simplifyLoopCFG(
739 *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
740 DeleteCurrentLoop);
741 if (DeleteCurrentLoop)
742 LPM.markLoopAsDeleted(*L);
743 return Changed;
Justin Bognerab6a5132016-05-03 21:47:32 +0000744 }
745
746 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000747 if (EnableMSSALoopDependency) {
748 AU.addRequired<MemorySSAWrapperPass>();
749 AU.addPreserved<MemorySSAWrapperPass>();
750 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000751 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000752 getLoopAnalysisUsage(AU);
753 }
754};
Alina Sbirlea1c03cc52020-02-04 16:29:04 -0800755} // end namespace
Justin Bognerab6a5132016-05-03 21:47:32 +0000756
757char LoopSimplifyCFGLegacyPass::ID = 0;
758INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
759 "Simplify loop CFG", false, false)
760INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000761INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000762INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
763 "Simplify loop CFG", false, false)
764
765Pass *llvm::createLoopSimplifyCFGPass() {
766 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000767}