blob: 4058c1d685cf27247ef1aeea5c9bbe2a0c9c4c39 [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"
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 Kazantsev6b63d3a2019-02-08 08:12:41 +000092 DomTreeUpdater DTU;
93 SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
Max Kazantsevc04b5302018-11-20 05:43:32 +000094
Max Kazantseva523a212018-12-07 05:44:45 +000095 // Whether or not the current loop has irreducible CFG.
96 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +000097 // Whether or not the current loop will still exist after terminator constant
98 // folding will be done. In theory, there are two ways how it can happen:
99 // 1. Loop's latch(es) become unreachable from loop header;
100 // 2. Loop's header becomes unreachable from method entry.
101 // In practice, the second situation is impossible because we only modify the
102 // current loop and its preheader and do not affect preheader's reachibility
103 // from any other block. So this variable set to true means that loop's latch
104 // has become unreachable from loop header.
105 bool DeleteCurrentLoop = false;
106
107 // The blocks of the original loop that will still be reachable from entry
108 // after the constant folding.
109 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
110 // The blocks of the original loop that will become unreachable from entry
111 // after the constant folding.
Max Kazantsev80e4b402018-12-28 06:08:51 +0000112 SmallVector<BasicBlock *, 8> DeadLoopBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000113 // The exits of the original loop that will still be reachable from entry
114 // after the constant folding.
115 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
116 // The exits of the original loop that will become unreachable from entry
117 // after the constant folding.
Max Kazantsev56a24432018-11-22 12:33:41 +0000118 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000119 // The blocks that will still be a part of the current loop after folding.
120 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
121 // The blocks that have terminators with constant condition that can be
122 // folded. Note: fold candidates should be in L but not in any of its
123 // subloops to avoid complex LI updates.
124 SmallVector<BasicBlock *, 8> FoldCandidates;
125
126 void dump() const {
127 dbgs() << "Constant terminator folding for loop " << L << "\n";
128 dbgs() << "After terminator constant-folding, the loop will";
129 if (!DeleteCurrentLoop)
130 dbgs() << " not";
131 dbgs() << " be destroyed\n";
Max Kazantsev56a24432018-11-22 12:33:41 +0000132 auto PrintOutVector = [&](const char *Message,
133 const SmallVectorImpl<BasicBlock *> &S) {
134 dbgs() << Message << "\n";
135 for (const BasicBlock *BB : S)
136 dbgs() << "\t" << BB->getName() << "\n";
137 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000138 auto PrintOutSet = [&](const char *Message,
139 const SmallPtrSetImpl<BasicBlock *> &S) {
140 dbgs() << Message << "\n";
141 for (const BasicBlock *BB : S)
142 dbgs() << "\t" << BB->getName() << "\n";
143 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000144 PrintOutVector("Blocks in which we can constant-fold terminator:",
145 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000146 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
Max Kazantsev80e4b402018-12-28 06:08:51 +0000147 PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000148 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000149 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000150 if (!DeleteCurrentLoop)
151 PrintOutSet("The following blocks will still be part of the loop:",
152 BlocksInLoopAfterFolding);
153 }
154
Max Kazantseva523a212018-12-07 05:44:45 +0000155 /// Whether or not the current loop has irreducible CFG.
156 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
157 assert(DFS.isComplete() && "DFS is expected to be finished");
158 // Index of a basic block in RPO traversal.
159 DenseMap<const BasicBlock *, unsigned> RPO;
160 unsigned Current = 0;
161 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
162 RPO[*I] = Current++;
163
164 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
165 BasicBlock *BB = *I;
166 for (auto *Succ : successors(BB))
167 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
168 // If an edge goes from a block with greater order number into a block
169 // with lesses number, and it is not a loop backedge, then it can only
170 // be a part of irreducible non-loop cycle.
171 return true;
172 }
173 return false;
174 }
175
Max Kazantsevc04b5302018-11-20 05:43:32 +0000176 /// Fill all information about status of blocks and exits of the current loop
177 /// if constant folding of all branches will be done.
178 void analyze() {
179 LoopBlocksDFS DFS(&L);
180 DFS.perform(&LI);
181 assert(DFS.isComplete() && "DFS is expected to be finished");
182
Max Kazantseva523a212018-12-07 05:44:45 +0000183 // TODO: The algorithm below relies on both RPO and Postorder traversals.
184 // When the loop has only reducible CFG inside, then the invariant "all
185 // predecessors of X are processed before X in RPO" is preserved. However
186 // an irreducible loop can break this invariant (e.g. latch does not have to
187 // be the last block in the traversal in this case, and the algorithm relies
188 // on this). We can later decide to support such cases by altering the
189 // algorithms, but so far we just give up analyzing them.
190 if (hasIrreducibleCFG(DFS)) {
191 HasIrreducibleCFG = true;
192 return;
193 }
194
Max Kazantsevc04b5302018-11-20 05:43:32 +0000195 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000196 LiveLoopBlocks.insert(L.getHeader());
197 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
198 BasicBlock *BB = *I;
199
200 // If a loop block wasn't marked as live so far, then it's dead.
201 if (!LiveLoopBlocks.count(BB)) {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000202 DeadLoopBlocks.push_back(BB);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000203 continue;
204 }
205
206 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
207
208 // If a block has only one live successor, it's a candidate on constant
209 // folding. Only handle blocks from current loop: branches in child loops
210 // are skipped because if they can be folded, they should be folded during
211 // the processing of child loops.
Max Kazantsev56515a22019-01-24 05:20:29 +0000212 bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
213 if (TakeFoldCandidate)
Max Kazantsevc04b5302018-11-20 05:43:32 +0000214 FoldCandidates.push_back(BB);
215
216 // Handle successors.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000217 for (BasicBlock *Succ : successors(BB))
Max Kazantsev56515a22019-01-24 05:20:29 +0000218 if (!TakeFoldCandidate || TheOnlySucc == Succ) {
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000219 if (L.contains(Succ))
220 LiveLoopBlocks.insert(Succ);
221 else
222 LiveExitBlocks.insert(Succ);
223 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000224 }
225
226 // Sanity check: amount of dead and live loop blocks should match the total
227 // number of blocks in loop.
228 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
229 "Malformed block sets?");
230
231 // Now, all exit blocks that are not marked as live are dead.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000232 SmallVector<BasicBlock *, 8> ExitBlocks;
233 L.getExitBlocks(ExitBlocks);
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000234 SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000235 for (auto *ExitBlock : ExitBlocks)
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000236 if (!LiveExitBlocks.count(ExitBlock) &&
237 UniqueDeadExits.insert(ExitBlock).second)
Max Kazantsev56a24432018-11-22 12:33:41 +0000238 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000239
240 // Whether or not the edge From->To will still be present in graph after the
241 // folding.
242 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
243 if (!LiveLoopBlocks.count(From))
244 return false;
245 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
Max Kazantsev38cd9ac2019-01-25 05:05:02 +0000246 return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000247 };
248
249 // The loop will not be destroyed if its latch is live.
250 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
251
252 // If we are going to delete the current loop completely, no extra analysis
253 // is needed.
254 if (DeleteCurrentLoop)
255 return;
256
257 // Otherwise, we should check which blocks will still be a part of the
258 // current loop after the transform.
259 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
260 // If the loop is live, then we should compute what blocks are still in
261 // loop after all branch folding has been done. A block is in loop if
262 // it has a live edge to another block that is in the loop; by definition,
263 // latch is in the loop.
264 auto BlockIsInLoop = [&](BasicBlock *BB) {
265 return any_of(successors(BB), [&](BasicBlock *Succ) {
266 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
267 });
268 };
269 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
270 BasicBlock *BB = *I;
271 if (BlockIsInLoop(BB))
272 BlocksInLoopAfterFolding.insert(BB);
273 }
274
275 // Sanity check: header must be in loop.
276 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
277 "Header not in loop?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000278 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
279 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000280 }
281
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000282 /// We need to preserve static reachibility of all loop exit blocks (this is)
283 /// required by loop pass manager. In order to do it, we make the following
284 /// trick:
285 ///
286 /// preheader:
287 /// <preheader code>
288 /// br label %loop_header
289 ///
290 /// loop_header:
291 /// ...
292 /// br i1 false, label %dead_exit, label %loop_block
293 /// ...
294 ///
295 /// We cannot simply remove edge from the loop to dead exit because in this
296 /// case dead_exit (and its successors) may become unreachable. To avoid that,
297 /// we insert the following fictive preheader:
298 ///
299 /// preheader:
300 /// <preheader code>
301 /// switch i32 0, label %preheader-split,
302 /// [i32 1, label %dead_exit_1],
303 /// [i32 2, label %dead_exit_2],
304 /// ...
305 /// [i32 N, label %dead_exit_N],
306 ///
307 /// preheader-split:
308 /// br label %loop_header
309 ///
310 /// loop_header:
311 /// ...
312 /// br i1 false, label %dead_exit_N, label %loop_block
313 /// ...
314 ///
315 /// Doing so, we preserve static reachibility of all dead exits and can later
316 /// remove edges from the loop to these blocks.
317 void handleDeadExits() {
318 // If no dead exits, nothing to do.
319 if (DeadExitBlocks.empty())
320 return;
321
322 // Construct split preheader and the dummy switch to thread edges from it to
323 // dead exits.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000324 BasicBlock *Preheader = L.getLoopPreheader();
325 BasicBlock *NewPreheader = Preheader->splitBasicBlock(
326 Preheader->getTerminator(),
327 Twine(Preheader->getName()).concat("-split"));
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000328 DTUpdates.push_back({DominatorTree::Delete, Preheader, L.getHeader()});
329 DTUpdates.push_back({DominatorTree::Insert, NewPreheader, L.getHeader()});
330 DTUpdates.push_back({DominatorTree::Insert, Preheader, NewPreheader});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000331 IRBuilder<> Builder(Preheader->getTerminator());
332 SwitchInst *DummySwitch =
333 Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
334 Preheader->getTerminator()->eraseFromParent();
335
336 unsigned DummyIdx = 1;
337 for (BasicBlock *BB : DeadExitBlocks) {
338 SmallVector<Instruction *, 4> DeadPhis;
339 for (auto &PN : BB->phis())
340 DeadPhis.push_back(&PN);
341
342 // Eliminate all Phis from dead exits.
343 for (Instruction *PN : DeadPhis) {
344 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
345 PN->eraseFromParent();
346 }
347 assert(DummyIdx != 0 && "Too many dead exits!");
348 DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000349 DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000350 ++NumLoopExitsDeleted;
351 }
352
353 assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
354 if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
355 OuterLoop->addBasicBlockToLoop(NewPreheader, LI);
356
357 // When we break dead edges, the outer loop may become unreachable from
358 // the current loop. We need to fix loop info accordingly. For this, we
359 // find the most nested loop that still contains L and remove L from all
360 // loops that are inside of it.
361 Loop *StillReachable = nullptr;
362 for (BasicBlock *BB : LiveExitBlocks) {
363 Loop *BBL = LI.getLoopFor(BB);
364 if (BBL && BBL->contains(L.getHeader()))
365 if (!StillReachable ||
366 BBL->getLoopDepth() > StillReachable->getLoopDepth())
367 StillReachable = BBL;
368 }
369
370 // Okay, our loop is no longer in the outer loop (and maybe not in some of
371 // its parents as well). Make the fixup.
372 if (StillReachable != OuterLoop) {
373 LI.changeLoopFor(NewPreheader, StillReachable);
374 for (Loop *NotContaining = OuterLoop; NotContaining != StillReachable;
375 NotContaining = NotContaining->getParentLoop()) {
376 NotContaining->removeBlockFromLoop(NewPreheader);
377 for (auto *BB : L.blocks())
378 NotContaining->removeBlockFromLoop(BB);
379 }
380 OuterLoop->removeChildLoop(&L);
381 if (StillReachable)
382 StillReachable->addChildLoop(&L);
383 else
384 LI.addTopLevelLoop(&L);
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000385
386 // Some values from loops in [OuterLoop, StillReachable) could be used
387 // in the current loop. Now it is not their child anymore, so such uses
388 // require LCSSA Phis.
389 Loop *FixLCSSALoop = OuterLoop;
390 while (FixLCSSALoop->getParentLoop() != StillReachable)
391 FixLCSSALoop = FixLCSSALoop->getParentLoop();
392 assert(FixLCSSALoop && "Should be a loop!");
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000393 // We need all DT updates to be done before forming LCSSA.
394 DTU.applyUpdates(DTUpdates);
395 DTUpdates.clear();
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000396 formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000397 }
398 }
399 }
400
Max Kazantsev347c5832018-12-24 06:06:17 +0000401 /// Delete loop blocks that have become unreachable after folding. Make all
402 /// relevant updates to DT and LI.
403 void deleteDeadLoopBlocks() {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000404 if (MSSAU) {
405 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
406 DeadLoopBlocks.end());
407 MSSAU->removeBlocks(DeadLoopBlocksSet);
408 }
Max Kazantsevbf6af8f2019-02-12 09:37:00 +0000409
410 // The function LI.erase has some invariants that need to be preserved when
411 // it tries to remove a loop which is not the top-level loop. In particular,
412 // it requires loop's preheader to be strictly in loop's parent. We cannot
413 // just remove blocks one by one, because after removal of preheader we may
414 // break this invariant for the dead loop. So we detatch and erase all dead
415 // loops beforehand.
416 for (auto *BB : DeadLoopBlocks)
417 if (LI.isLoopHeader(BB)) {
418 assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
419 Loop *DL = LI.getLoopFor(BB);
420 if (DL->getParentLoop()) {
421 for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
422 for (auto *BB : DL->getBlocks())
423 PL->removeBlockFromLoop(BB);
424 DL->getParentLoop()->removeChildLoop(DL);
425 LI.addTopLevelLoop(DL);
426 }
427 LI.erase(DL);
428 }
429
Max Kazantsev347c5832018-12-24 06:06:17 +0000430 for (auto *BB : DeadLoopBlocks) {
431 assert(BB != L.getHeader() &&
432 "Header of the current loop cannot be dead!");
433 LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
434 << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000435 LI.removeBlock(BB);
Max Kazantsev347c5832018-12-24 06:06:17 +0000436 }
Max Kazantsev8b134162019-01-17 12:25:40 +0000437
Max Kazantsev6bf86152019-02-12 07:48:07 +0000438 DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000439 DTU.applyUpdates(DTUpdates);
440 DTUpdates.clear();
441 for (auto *BB : DeadLoopBlocks)
Max Kazantsev9aae9da2019-02-12 08:10:29 +0000442 DTU.deleteBB(BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000443
Max Kazantsev8b134162019-01-17 12:25:40 +0000444 NumLoopBlocksDeleted += DeadLoopBlocks.size();
Max Kazantsev347c5832018-12-24 06:06:17 +0000445 }
446
Max Kazantsevc04b5302018-11-20 05:43:32 +0000447 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
448 /// unconditional branches.
449 void foldTerminators() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000450 for (BasicBlock *BB : FoldCandidates) {
451 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
452 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
453 assert(TheOnlySucc && "Should have one live successor!");
454
455 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
456 << " with an unconditional branch to the block "
457 << TheOnlySucc->getName() << "\n");
458
459 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
460 // Remove all BB's successors except for the live one.
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000461 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000462 for (auto *Succ : successors(BB))
463 if (Succ != TheOnlySucc) {
464 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000465 // If our successor lies in a different loop, we don't want to remove
466 // the one-input Phi because it is a LCSSA Phi.
467 bool PreserveLCSSAPhi = !L.contains(Succ);
468 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000469 if (MSSAU)
470 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000471 } else
472 ++TheOnlySuccDuplicates;
473
474 assert(TheOnlySuccDuplicates > 0 && "Should be!");
475 // If TheOnlySucc was BB's successor more than once, after transform it
476 // will be its successor only once. Remove redundant inputs from
477 // TheOnlySucc's Phis.
478 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
479 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
480 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000481 if (MSSAU && TheOnlySuccDuplicates > 1)
482 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000483
484 IRBuilder<> Builder(BB->getContext());
485 Instruction *Term = BB->getTerminator();
486 Builder.SetInsertPoint(Term);
487 Builder.CreateBr(TheOnlySucc);
488 Term->eraseFromParent();
489
490 for (auto *DeadSucc : DeadSuccessors)
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000491 DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
Max Kazantsevc04b5302018-11-20 05:43:32 +0000492
493 ++NumTerminatorsFolded;
494 }
495 }
496
497public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000498 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
Max Kazantsev201534d2018-12-29 04:26:22 +0000499 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000500 MemorySSAUpdater *MSSAU)
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000501 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU),
502 DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000503 bool run() {
504 assert(L.getLoopLatch() && "Should be single latch!");
505
506 // Collect all available information about status of blocks after constant
507 // folding.
508 analyze();
509
510 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName()
511 << ": ");
512
Max Kazantseva523a212018-12-07 05:44:45 +0000513 if (HasIrreducibleCFG) {
514 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
515 return false;
516 }
517
Max Kazantsevc04b5302018-11-20 05:43:32 +0000518 // Nothing to constant-fold.
519 if (FoldCandidates.empty()) {
520 LLVM_DEBUG(
521 dbgs() << "No constant terminator folding candidates found in loop "
522 << L.getHeader()->getName() << "\n");
523 return false;
524 }
525
526 // TODO: Support deletion of the current loop.
527 if (DeleteCurrentLoop) {
528 LLVM_DEBUG(
529 dbgs()
530 << "Give up constant terminator folding in loop "
531 << L.getHeader()->getName()
532 << ": we don't currently support deletion of the current loop.\n");
533 return false;
534 }
535
Max Kazantsevc04b5302018-11-20 05:43:32 +0000536 // TODO: Support blocks that are not dead, but also not in loop after the
537 // folding.
Max Kazantsev347c5832018-12-24 06:06:17 +0000538 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
539 L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000540 LLVM_DEBUG(
541 dbgs() << "Give up constant terminator folding in loop "
542 << L.getHeader()->getName()
543 << ": we don't currently"
544 " support blocks that are not dead, but will stop "
545 "being a part of the loop after constant-folding.\n");
546 return false;
547 }
548
Max Kazantsev201534d2018-12-29 04:26:22 +0000549 SE.forgetTopmostLoop(&L);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000550 // Dump analysis results.
551 LLVM_DEBUG(dump());
552
553 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
554 << " terminators in loop " << L.getHeader()->getName()
555 << "\n");
556
557 // Make the actual transforms.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000558 handleDeadExits();
Max Kazantsevc04b5302018-11-20 05:43:32 +0000559 foldTerminators();
560
Max Kazantsev347c5832018-12-24 06:06:17 +0000561 if (!DeadLoopBlocks.empty()) {
562 LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
563 << " dead blocks in loop " << L.getHeader()->getName()
564 << "\n");
565 deleteDeadLoopBlocks();
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000566 } else {
567 // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
568 DTU.applyUpdates(DTUpdates);
569 DTUpdates.clear();
Max Kazantsev347c5832018-12-24 06:06:17 +0000570 }
571
Max Kazantsevc04b5302018-11-20 05:43:32 +0000572#ifndef NDEBUG
573 // Make sure that we have preserved all data structures after the transform.
Max Kazantsev365021c2019-01-30 12:32:19 +0000574 assert(DT.verify() && "DT broken after transform!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000575 assert(DT.isReachableFromEntry(L.getHeader()));
576 LI.verify(DT);
577#endif
578
579 return true;
580 }
581};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000582} // namespace
Max Kazantsevc04b5302018-11-20 05:43:32 +0000583
584/// Turn branches and switches with known constant conditions into unconditional
585/// branches.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000586static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsev201534d2018-12-29 04:26:22 +0000587 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000588 MemorySSAUpdater *MSSAU) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000589 if (!EnableTermFolding)
590 return false;
591
Max Kazantsevc04b5302018-11-20 05:43:32 +0000592 // To keep things simple, only process loops with single latch. We
593 // canonicalize most loops to this form. We can support multi-latch if needed.
594 if (!L.getLoopLatch())
595 return false;
596
Max Kazantsev201534d2018-12-29 04:26:22 +0000597 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000598 return BranchFolder.run();
599}
600
Max Kazantsev46955b52018-11-01 09:42:50 +0000601static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
602 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000603 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000604 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000605 // Copy blocks into a temporary array to avoid iterator invalidation issues
606 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000607 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000608
609 for (auto &Block : Blocks) {
610 // Attempt to merge blocks in the trivial case. Don't modify blocks which
611 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000612 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000613 if (!Succ)
614 continue;
615
616 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000617 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000618 continue;
619
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000620 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000621 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000622
Fiona Glaserb417d462016-01-29 22:35:36 +0000623 Changed = true;
624 }
625
626 return Changed;
627}
628
Max Kazantsev46955b52018-11-01 09:42:50 +0000629static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
630 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) {
631 bool Changed = false;
632
Max Kazantsevc04b5302018-11-20 05:43:32 +0000633 // Constant-fold terminators with known constant conditions.
Max Kazantsev201534d2018-12-29 04:26:22 +0000634 Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000635
Max Kazantsev46955b52018-11-01 09:42:50 +0000636 // Eliminate unconditional branches by merging blocks into their predecessors.
637 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
638
639 if (Changed)
640 SE.forgetTopmostLoop(&L);
641
642 return Changed;
643}
644
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000645PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
646 LoopStandardAnalysisResults &AR,
647 LPMUpdater &) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000648 Optional<MemorySSAUpdater> MSSAU;
649 if (EnableMSSALoopDependency && AR.MSSA)
650 MSSAU = MemorySSAUpdater(AR.MSSA);
651 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
652 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Justin Bognerab6a5132016-05-03 21:47:32 +0000653 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000654
Justin Bognerab6a5132016-05-03 21:47:32 +0000655 return getLoopPassPreservedAnalyses();
656}
657
658namespace {
659class LoopSimplifyCFGLegacyPass : public LoopPass {
660public:
661 static char ID; // Pass ID, replacement for typeid
662 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
663 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
664 }
665
666 bool runOnLoop(Loop *L, LPPassManager &) override {
667 if (skipLoop(L))
668 return false;
669
670 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
671 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000672 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000673 Optional<MemorySSAUpdater> MSSAU;
674 if (EnableMSSALoopDependency) {
675 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
676 MSSAU = MemorySSAUpdater(MSSA);
677 if (VerifyMemorySSA)
678 MSSA->verifyMemorySSA();
679 }
680 return simplifyLoopCFG(*L, DT, LI, SE,
681 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
Justin Bognerab6a5132016-05-03 21:47:32 +0000682 }
683
684 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000685 if (EnableMSSALoopDependency) {
686 AU.addRequired<MemorySSAWrapperPass>();
687 AU.addPreserved<MemorySSAWrapperPass>();
688 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000689 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000690 getLoopAnalysisUsage(AU);
691 }
692};
693}
694
695char LoopSimplifyCFGLegacyPass::ID = 0;
696INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
697 "Simplify loop CFG", false, false)
698INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000699INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000700INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
701 "Simplify loop CFG", false, false)
702
703Pass *llvm::createLoopSimplifyCFGPass() {
704 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000705}