blob: b0fa4f7e0ef5aedce456fdc3be2b49bcc085fcc4 [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"
23#include "llvm/Analysis/GlobalsModRef.h"
24#include "llvm/Analysis/LoopInfo.h"
25#include "llvm/Analysis/LoopPass.h"
Alina Sbirlea8b83d682018-08-22 20:10:21 +000026#include "llvm/Analysis/MemorySSA.h"
27#include "llvm/Analysis/MemorySSAUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000028#include "llvm/Analysis/ScalarEvolution.h"
29#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
30#include "llvm/Analysis/TargetTransformInfo.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000031#include "llvm/IR/DomTreeUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000032#include "llvm/IR/Dominators.h"
Justin Bognerab6a5132016-05-03 21:47:32 +000033#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000034#include "llvm/Transforms/Scalar/LoopPassManager.h"
David Blaikiea373d182018-03-28 17:44:36 +000035#include "llvm/Transforms/Utils.h"
Alina Sbirleadfd14ad2018-06-20 22:01:04 +000036#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000038#include "llvm/Transforms/Utils/LoopUtils.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000039using namespace llvm;
40
41#define DEBUG_TYPE "loop-simplifycfg"
42
Max Kazantseve1c2dc22018-11-23 09:14:53 +000043static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
Jordan Rupprecht0efe27e2019-01-22 17:39:02 +000044 cl::init(false));
Max Kazantseve1c2dc22018-11-23 09:14:53 +000045
Max Kazantsevc04b5302018-11-20 05:43:32 +000046STATISTIC(NumTerminatorsFolded,
47 "Number of terminators folded to unconditional branches");
Max Kazantsev347c5832018-12-24 06:06:17 +000048STATISTIC(NumLoopBlocksDeleted,
49 "Number of loop blocks deleted");
Max Kazantsevedabb9a2018-12-24 07:41:33 +000050STATISTIC(NumLoopExitsDeleted,
51 "Number of loop exiting edges deleted");
Max Kazantsevc04b5302018-11-20 05:43:32 +000052
53/// If \p BB is a switch or a conditional branch, but only one of its successors
54/// can be reached from this block in runtime, return this successor. Otherwise,
55/// return nullptr.
56static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
57 Instruction *TI = BB->getTerminator();
58 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
59 if (BI->isUnconditional())
60 return nullptr;
61 if (BI->getSuccessor(0) == BI->getSuccessor(1))
62 return BI->getSuccessor(0);
63 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
64 if (!Cond)
65 return nullptr;
66 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
67 }
68
69 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
70 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
71 if (!CI)
72 return nullptr;
73 for (auto Case : SI->cases())
74 if (Case.getCaseValue() == CI)
75 return Case.getCaseSuccessor();
76 return SI->getDefaultDest();
77 }
78
79 return nullptr;
80}
81
Benjamin Kramerb17d2132019-01-12 18:36:22 +000082namespace {
Max Kazantsevc04b5302018-11-20 05:43:32 +000083/// Helper class that can turn branches and switches with constant conditions
84/// into unconditional branches.
85class ConstantTerminatorFoldingImpl {
86private:
87 Loop &L;
88 LoopInfo &LI;
89 DominatorTree &DT;
Max Kazantsev201534d2018-12-29 04:26:22 +000090 ScalarEvolution &SE;
Max Kazantsev9cf417d2018-11-30 10:06:23 +000091 MemorySSAUpdater *MSSAU;
Max Kazantsevc04b5302018-11-20 05:43:32 +000092
Max Kazantseva523a212018-12-07 05:44:45 +000093 // Whether or not the current loop has irreducible CFG.
94 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +000095 // 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.
Max Kazantsev80e4b402018-12-28 06:08:51 +0000110 SmallVector<BasicBlock *, 8> DeadLoopBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000111 // 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.
Max Kazantsev56a24432018-11-22 12:33:41 +0000116 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000117 // 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";
Max Kazantsev56a24432018-11-22 12:33:41 +0000130 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 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000136 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 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000142 PrintOutVector("Blocks in which we can constant-fold terminator:",
143 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000144 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
Max Kazantsev80e4b402018-12-28 06:08:51 +0000145 PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000146 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000147 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000148 if (!DeleteCurrentLoop)
149 PrintOutSet("The following blocks will still be part of the loop:",
150 BlocksInLoopAfterFolding);
151 }
152
Max Kazantseva523a212018-12-07 05:44:45 +0000153 /// 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
Max Kazantsevc04b5302018-11-20 05:43:32 +0000174 /// 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
Max Kazantseva523a212018-12-07 05:44:45 +0000181 // 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
Max Kazantsevc04b5302018-11-20 05:43:32 +0000193 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000194 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)) {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000200 DeadLoopBlocks.push_back(BB);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000201 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.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000214 for (BasicBlock *Succ : successors(BB))
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000215 if (!TheOnlySucc || TheOnlySucc == Succ) {
216 if (L.contains(Succ))
217 LiveLoopBlocks.insert(Succ);
218 else
219 LiveExitBlocks.insert(Succ);
220 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000221 }
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.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000229 SmallVector<BasicBlock *, 8> ExitBlocks;
230 L.getExitBlocks(ExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000231 for (auto *ExitBlock : ExitBlocks)
232 if (!LiveExitBlocks.count(ExitBlock))
Max Kazantsev56a24432018-11-22 12:33:41 +0000233 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000234
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?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000273 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
274 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000275 }
276
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000277 /// 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);
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000381
382 // Some values from loops in [OuterLoop, StillReachable) could be used
383 // in the current loop. Now it is not their child anymore, so such uses
384 // require LCSSA Phis.
385 Loop *FixLCSSALoop = OuterLoop;
386 while (FixLCSSALoop->getParentLoop() != StillReachable)
387 FixLCSSALoop = FixLCSSALoop->getParentLoop();
388 assert(FixLCSSALoop && "Should be a loop!");
389 formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000390 }
391 }
392 }
393
Max Kazantsev347c5832018-12-24 06:06:17 +0000394 /// Delete loop blocks that have become unreachable after folding. Make all
395 /// relevant updates to DT and LI.
396 void deleteDeadLoopBlocks() {
397 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Max Kazantsev80e4b402018-12-28 06:08:51 +0000398 if (MSSAU) {
399 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
400 DeadLoopBlocks.end());
401 MSSAU->removeBlocks(DeadLoopBlocksSet);
402 }
Max Kazantsev347c5832018-12-24 06:06:17 +0000403 for (auto *BB : DeadLoopBlocks) {
404 assert(BB != L.getHeader() &&
405 "Header of the current loop cannot be dead!");
406 LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
407 << "\n");
408 if (LI.isLoopHeader(BB)) {
409 assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
410 LI.erase(LI.getLoopFor(BB));
411 }
412 LI.removeBlock(BB);
Max Kazantsev347c5832018-12-24 06:06:17 +0000413 }
Max Kazantsev8b134162019-01-17 12:25:40 +0000414
415 DeleteDeadBlocks(DeadLoopBlocks, &DTU);
416 NumLoopBlocksDeleted += DeadLoopBlocks.size();
Max Kazantsev347c5832018-12-24 06:06:17 +0000417 }
418
Max Kazantsevc04b5302018-11-20 05:43:32 +0000419 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
420 /// unconditional branches.
421 void foldTerminators() {
422 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
423
424 for (BasicBlock *BB : FoldCandidates) {
425 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
426 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
427 assert(TheOnlySucc && "Should have one live successor!");
428
429 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
430 << " with an unconditional branch to the block "
431 << TheOnlySucc->getName() << "\n");
432
433 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
434 // Remove all BB's successors except for the live one.
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000435 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000436 for (auto *Succ : successors(BB))
437 if (Succ != TheOnlySucc) {
438 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000439 // If our successor lies in a different loop, we don't want to remove
440 // the one-input Phi because it is a LCSSA Phi.
441 bool PreserveLCSSAPhi = !L.contains(Succ);
442 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000443 if (MSSAU)
444 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000445 } else
446 ++TheOnlySuccDuplicates;
447
448 assert(TheOnlySuccDuplicates > 0 && "Should be!");
449 // If TheOnlySucc was BB's successor more than once, after transform it
450 // will be its successor only once. Remove redundant inputs from
451 // TheOnlySucc's Phis.
452 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
453 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
454 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000455 if (MSSAU && TheOnlySuccDuplicates > 1)
456 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000457
458 IRBuilder<> Builder(BB->getContext());
459 Instruction *Term = BB->getTerminator();
460 Builder.SetInsertPoint(Term);
461 Builder.CreateBr(TheOnlySucc);
462 Term->eraseFromParent();
463
464 for (auto *DeadSucc : DeadSuccessors)
465 DTU.deleteEdge(BB, DeadSucc);
466
467 ++NumTerminatorsFolded;
468 }
469 }
470
471public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000472 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
Max Kazantsev201534d2018-12-29 04:26:22 +0000473 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000474 MemorySSAUpdater *MSSAU)
Max Kazantsev201534d2018-12-29 04:26:22 +0000475 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000476 bool run() {
477 assert(L.getLoopLatch() && "Should be single latch!");
478
479 // Collect all available information about status of blocks after constant
480 // folding.
481 analyze();
482
483 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName()
484 << ": ");
485
Max Kazantseva523a212018-12-07 05:44:45 +0000486 if (HasIrreducibleCFG) {
487 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
488 return false;
489 }
490
Max Kazantsevc04b5302018-11-20 05:43:32 +0000491 // Nothing to constant-fold.
492 if (FoldCandidates.empty()) {
493 LLVM_DEBUG(
494 dbgs() << "No constant terminator folding candidates found in loop "
495 << L.getHeader()->getName() << "\n");
496 return false;
497 }
498
499 // TODO: Support deletion of the current loop.
500 if (DeleteCurrentLoop) {
501 LLVM_DEBUG(
502 dbgs()
503 << "Give up constant terminator folding in loop "
504 << L.getHeader()->getName()
505 << ": we don't currently support deletion of the current loop.\n");
506 return false;
507 }
508
Max Kazantsevc04b5302018-11-20 05:43:32 +0000509 // TODO: Support blocks that are not dead, but also not in loop after the
510 // folding.
Max Kazantsev347c5832018-12-24 06:06:17 +0000511 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
512 L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000513 LLVM_DEBUG(
514 dbgs() << "Give up constant terminator folding in loop "
515 << L.getHeader()->getName()
516 << ": we don't currently"
517 " support blocks that are not dead, but will stop "
518 "being a part of the loop after constant-folding.\n");
519 return false;
520 }
521
Max Kazantsev201534d2018-12-29 04:26:22 +0000522 SE.forgetTopmostLoop(&L);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000523 // Dump analysis results.
524 LLVM_DEBUG(dump());
525
526 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
527 << " terminators in loop " << L.getHeader()->getName()
528 << "\n");
529
530 // Make the actual transforms.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000531 handleDeadExits();
Max Kazantsevc04b5302018-11-20 05:43:32 +0000532 foldTerminators();
533
Max Kazantsev347c5832018-12-24 06:06:17 +0000534 if (!DeadLoopBlocks.empty()) {
535 LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
536 << " dead blocks in loop " << L.getHeader()->getName()
537 << "\n");
538 deleteDeadLoopBlocks();
539 }
540
Max Kazantsevc04b5302018-11-20 05:43:32 +0000541#ifndef NDEBUG
542 // Make sure that we have preserved all data structures after the transform.
543 DT.verify();
544 assert(DT.isReachableFromEntry(L.getHeader()));
545 LI.verify(DT);
546#endif
547
548 return true;
549 }
550};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000551} // namespace
Max Kazantsevc04b5302018-11-20 05:43:32 +0000552
553/// Turn branches and switches with known constant conditions into unconditional
554/// branches.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000555static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsev201534d2018-12-29 04:26:22 +0000556 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000557 MemorySSAUpdater *MSSAU) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000558 if (!EnableTermFolding)
559 return false;
560
Max Kazantsevc04b5302018-11-20 05:43:32 +0000561 // To keep things simple, only process loops with single latch. We
562 // canonicalize most loops to this form. We can support multi-latch if needed.
563 if (!L.getLoopLatch())
564 return false;
565
Max Kazantsev201534d2018-12-29 04:26:22 +0000566 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000567 return BranchFolder.run();
568}
569
Max Kazantsev46955b52018-11-01 09:42:50 +0000570static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
571 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000572 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000573 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000574 // Copy blocks into a temporary array to avoid iterator invalidation issues
575 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000576 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000577
578 for (auto &Block : Blocks) {
579 // Attempt to merge blocks in the trivial case. Don't modify blocks which
580 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000581 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000582 if (!Succ)
583 continue;
584
585 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000586 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000587 continue;
588
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000589 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000590 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000591
Fiona Glaserb417d462016-01-29 22:35:36 +0000592 Changed = true;
593 }
594
595 return Changed;
596}
597
Max Kazantsev46955b52018-11-01 09:42:50 +0000598static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
599 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) {
600 bool Changed = false;
601
Max Kazantsevc04b5302018-11-20 05:43:32 +0000602 // Constant-fold terminators with known constant conditions.
Max Kazantsev201534d2018-12-29 04:26:22 +0000603 Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000604
Max Kazantsev46955b52018-11-01 09:42:50 +0000605 // Eliminate unconditional branches by merging blocks into their predecessors.
606 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
607
608 if (Changed)
609 SE.forgetTopmostLoop(&L);
610
611 return Changed;
612}
613
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000614PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
615 LoopStandardAnalysisResults &AR,
616 LPMUpdater &) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000617 Optional<MemorySSAUpdater> MSSAU;
618 if (EnableMSSALoopDependency && AR.MSSA)
619 MSSAU = MemorySSAUpdater(AR.MSSA);
620 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
621 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Justin Bognerab6a5132016-05-03 21:47:32 +0000622 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000623
Justin Bognerab6a5132016-05-03 21:47:32 +0000624 return getLoopPassPreservedAnalyses();
625}
626
627namespace {
628class LoopSimplifyCFGLegacyPass : public LoopPass {
629public:
630 static char ID; // Pass ID, replacement for typeid
631 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
632 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
633 }
634
635 bool runOnLoop(Loop *L, LPPassManager &) override {
636 if (skipLoop(L))
637 return false;
638
639 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
640 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000641 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000642 Optional<MemorySSAUpdater> MSSAU;
643 if (EnableMSSALoopDependency) {
644 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
645 MSSAU = MemorySSAUpdater(MSSA);
646 if (VerifyMemorySSA)
647 MSSA->verifyMemorySSA();
648 }
649 return simplifyLoopCFG(*L, DT, LI, SE,
650 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
Justin Bognerab6a5132016-05-03 21:47:32 +0000651 }
652
653 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000654 if (EnableMSSALoopDependency) {
655 AU.addRequired<MemorySSAWrapperPass>();
656 AU.addPreserved<MemorySSAWrapperPass>();
657 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000658 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000659 getLoopAnalysisUsage(AU);
660 }
661};
662}
663
664char LoopSimplifyCFGLegacyPass::ID = 0;
665INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
666 "Simplify loop CFG", false, false)
667INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000668INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000669INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
670 "Simplify loop CFG", false, false)
671
672Pass *llvm::createLoopSimplifyCFGPass() {
673 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000674}