blob: 0f03f35496f242d5d145288cde5ae87f043342b6 [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"
Justin Bognerab6a5132016-05-03 21:47:32 +000034#include "llvm/Transforms/Scalar.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000035#include "llvm/Transforms/Scalar/LoopPassManager.h"
David Blaikiea373d182018-03-28 17:44:36 +000036#include "llvm/Transforms/Utils.h"
Alina Sbirleadfd14ad2018-06-20 22:01:04 +000037#include "llvm/Transforms/Utils/BasicBlockUtils.h"
38#include "llvm/Transforms/Utils/Local.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000039#include "llvm/Transforms/Utils/LoopUtils.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000040using namespace llvm;
41
42#define DEBUG_TYPE "loop-simplifycfg"
43
Max Kazantseve1c2dc22018-11-23 09:14:53 +000044static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
Max Kazantsev5cf777e2019-02-13 06:12:48 +000045 cl::init(true));
Max Kazantseve1c2dc22018-11-23 09:14:53 +000046
Max Kazantsevc04b5302018-11-20 05:43:32 +000047STATISTIC(NumTerminatorsFolded,
48 "Number of terminators folded to unconditional branches");
Max Kazantsev347c5832018-12-24 06:06:17 +000049STATISTIC(NumLoopBlocksDeleted,
50 "Number of loop blocks deleted");
Max Kazantsevedabb9a2018-12-24 07:41:33 +000051STATISTIC(NumLoopExitsDeleted,
52 "Number of loop exiting edges deleted");
Max Kazantsevc04b5302018-11-20 05:43:32 +000053
54/// If \p BB is a switch or a conditional branch, but only one of its successors
55/// can be reached from this block in runtime, return this successor. Otherwise,
56/// return nullptr.
57static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
58 Instruction *TI = BB->getTerminator();
59 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
60 if (BI->isUnconditional())
61 return nullptr;
62 if (BI->getSuccessor(0) == BI->getSuccessor(1))
63 return BI->getSuccessor(0);
64 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
65 if (!Cond)
66 return nullptr;
67 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
68 }
69
70 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
71 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
72 if (!CI)
73 return nullptr;
74 for (auto Case : SI->cases())
75 if (Case.getCaseValue() == CI)
76 return Case.getCaseSuccessor();
77 return SI->getDefaultDest();
78 }
79
80 return nullptr;
81}
82
Max Kazantsevc065b022019-02-15 12:18:10 +000083/// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
84static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
85 Loop *LastLoop = nullptr) {
86 assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
87 "First loop is supposed to be inside of last loop!");
88 assert(FirstLoop->contains(BB) && "Must be a loop block!");
89 for (Loop *Current = FirstLoop; Current != LastLoop;
90 Current = Current->getParentLoop())
91 Current->removeBlockFromLoop(BB);
92}
93
Max Kazantsevd72c1a02019-02-17 15:22:48 +000094/// Find innermost loop that contains at least one block from \p BBs and
95/// contains the header of loop \p L.
96static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
97 Loop &L, LoopInfo &LI) {
Max Kazantsev45614752019-02-17 18:21:51 +000098 Loop *Innermost = nullptr;
Max Kazantsev0f943262019-02-17 15:04:09 +000099 for (BasicBlock *BB : BBs) {
100 Loop *BBL = LI.getLoopFor(BB);
Max Kazantsev45614752019-02-17 18:21:51 +0000101 while (BBL && !BBL->contains(L.getHeader()))
102 BBL = BBL->getParentLoop();
103 if (BBL == &L)
104 BBL = BBL->getParentLoop();
105 if (!BBL)
106 continue;
107 if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
108 Innermost = BBL;
Max Kazantsev0f943262019-02-17 15:04:09 +0000109 }
Max Kazantsev45614752019-02-17 18:21:51 +0000110 return Innermost;
Max Kazantsev0f943262019-02-17 15:04:09 +0000111}
112
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000113namespace {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000114/// Helper class that can turn branches and switches with constant conditions
115/// into unconditional branches.
116class ConstantTerminatorFoldingImpl {
117private:
118 Loop &L;
119 LoopInfo &LI;
120 DominatorTree &DT;
Max Kazantsev201534d2018-12-29 04:26:22 +0000121 ScalarEvolution &SE;
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000122 MemorySSAUpdater *MSSAU;
Max Kazantsev136f09b2019-02-15 11:39:35 +0000123 LoopBlocksDFS DFS;
Simon Pilgrim623c38d2019-02-15 12:13:16 +0000124 DomTreeUpdater DTU;
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000125 SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000126
Max Kazantseva523a212018-12-07 05:44:45 +0000127 // Whether or not the current loop has irreducible CFG.
128 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000129 // Whether or not the current loop will still exist after terminator constant
130 // folding will be done. In theory, there are two ways how it can happen:
131 // 1. Loop's latch(es) become unreachable from loop header;
132 // 2. Loop's header becomes unreachable from method entry.
133 // In practice, the second situation is impossible because we only modify the
134 // current loop and its preheader and do not affect preheader's reachibility
135 // from any other block. So this variable set to true means that loop's latch
136 // has become unreachable from loop header.
137 bool DeleteCurrentLoop = false;
138
139 // The blocks of the original loop that will still be reachable from entry
140 // after the constant folding.
141 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
142 // The blocks of the original loop that will become unreachable from entry
143 // after the constant folding.
Max Kazantsev80e4b402018-12-28 06:08:51 +0000144 SmallVector<BasicBlock *, 8> DeadLoopBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000145 // The exits of the original loop that will still be reachable from entry
146 // after the constant folding.
147 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
148 // The exits of the original loop that will become unreachable from entry
149 // after the constant folding.
Max Kazantsev56a24432018-11-22 12:33:41 +0000150 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000151 // The blocks that will still be a part of the current loop after folding.
152 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
153 // The blocks that have terminators with constant condition that can be
154 // folded. Note: fold candidates should be in L but not in any of its
155 // subloops to avoid complex LI updates.
156 SmallVector<BasicBlock *, 8> FoldCandidates;
157
158 void dump() const {
159 dbgs() << "Constant terminator folding for loop " << L << "\n";
160 dbgs() << "After terminator constant-folding, the loop will";
161 if (!DeleteCurrentLoop)
162 dbgs() << " not";
163 dbgs() << " be destroyed\n";
Max Kazantsev56a24432018-11-22 12:33:41 +0000164 auto PrintOutVector = [&](const char *Message,
165 const SmallVectorImpl<BasicBlock *> &S) {
166 dbgs() << Message << "\n";
167 for (const BasicBlock *BB : S)
168 dbgs() << "\t" << BB->getName() << "\n";
169 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000170 auto PrintOutSet = [&](const char *Message,
171 const SmallPtrSetImpl<BasicBlock *> &S) {
172 dbgs() << Message << "\n";
173 for (const BasicBlock *BB : S)
174 dbgs() << "\t" << BB->getName() << "\n";
175 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000176 PrintOutVector("Blocks in which we can constant-fold terminator:",
177 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000178 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
Max Kazantsev80e4b402018-12-28 06:08:51 +0000179 PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000180 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000181 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000182 if (!DeleteCurrentLoop)
183 PrintOutSet("The following blocks will still be part of the loop:",
184 BlocksInLoopAfterFolding);
185 }
186
Max Kazantseva523a212018-12-07 05:44:45 +0000187 /// Whether or not the current loop has irreducible CFG.
188 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
189 assert(DFS.isComplete() && "DFS is expected to be finished");
190 // Index of a basic block in RPO traversal.
191 DenseMap<const BasicBlock *, unsigned> RPO;
192 unsigned Current = 0;
193 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
194 RPO[*I] = Current++;
195
196 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
197 BasicBlock *BB = *I;
198 for (auto *Succ : successors(BB))
199 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
200 // If an edge goes from a block with greater order number into a block
201 // with lesses number, and it is not a loop backedge, then it can only
202 // be a part of irreducible non-loop cycle.
203 return true;
204 }
205 return false;
206 }
207
Max Kazantsevc04b5302018-11-20 05:43:32 +0000208 /// Fill all information about status of blocks and exits of the current loop
209 /// if constant folding of all branches will be done.
210 void analyze() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000211 DFS.perform(&LI);
212 assert(DFS.isComplete() && "DFS is expected to be finished");
213
Max Kazantseva523a212018-12-07 05:44:45 +0000214 // TODO: The algorithm below relies on both RPO and Postorder traversals.
215 // When the loop has only reducible CFG inside, then the invariant "all
216 // predecessors of X are processed before X in RPO" is preserved. However
217 // an irreducible loop can break this invariant (e.g. latch does not have to
218 // be the last block in the traversal in this case, and the algorithm relies
219 // on this). We can later decide to support such cases by altering the
220 // algorithms, but so far we just give up analyzing them.
221 if (hasIrreducibleCFG(DFS)) {
222 HasIrreducibleCFG = true;
223 return;
224 }
225
Max Kazantsevc04b5302018-11-20 05:43:32 +0000226 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000227 LiveLoopBlocks.insert(L.getHeader());
228 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
229 BasicBlock *BB = *I;
230
231 // If a loop block wasn't marked as live so far, then it's dead.
232 if (!LiveLoopBlocks.count(BB)) {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000233 DeadLoopBlocks.push_back(BB);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000234 continue;
235 }
236
237 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
238
239 // If a block has only one live successor, it's a candidate on constant
240 // folding. Only handle blocks from current loop: branches in child loops
241 // are skipped because if they can be folded, they should be folded during
242 // the processing of child loops.
Max Kazantsev56515a22019-01-24 05:20:29 +0000243 bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
244 if (TakeFoldCandidate)
Max Kazantsevc04b5302018-11-20 05:43:32 +0000245 FoldCandidates.push_back(BB);
246
247 // Handle successors.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000248 for (BasicBlock *Succ : successors(BB))
Max Kazantsev56515a22019-01-24 05:20:29 +0000249 if (!TakeFoldCandidate || TheOnlySucc == Succ) {
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000250 if (L.contains(Succ))
251 LiveLoopBlocks.insert(Succ);
252 else
253 LiveExitBlocks.insert(Succ);
254 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000255 }
256
257 // Sanity check: amount of dead and live loop blocks should match the total
258 // number of blocks in loop.
259 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
260 "Malformed block sets?");
261
262 // Now, all exit blocks that are not marked as live are dead.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000263 SmallVector<BasicBlock *, 8> ExitBlocks;
264 L.getExitBlocks(ExitBlocks);
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000265 SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000266 for (auto *ExitBlock : ExitBlocks)
Max Kazantseva4ccfc12019-02-06 07:49:17 +0000267 if (!LiveExitBlocks.count(ExitBlock) &&
268 UniqueDeadExits.insert(ExitBlock).second)
Max Kazantsev56a24432018-11-22 12:33:41 +0000269 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000270
271 // Whether or not the edge From->To will still be present in graph after the
272 // folding.
273 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
274 if (!LiveLoopBlocks.count(From))
275 return false;
276 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
Max Kazantsev38cd9ac2019-01-25 05:05:02 +0000277 return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000278 };
279
280 // The loop will not be destroyed if its latch is live.
281 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
282
283 // If we are going to delete the current loop completely, no extra analysis
284 // is needed.
285 if (DeleteCurrentLoop)
286 return;
287
288 // Otherwise, we should check which blocks will still be a part of the
289 // current loop after the transform.
290 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
291 // If the loop is live, then we should compute what blocks are still in
292 // loop after all branch folding has been done. A block is in loop if
293 // it has a live edge to another block that is in the loop; by definition,
294 // latch is in the loop.
295 auto BlockIsInLoop = [&](BasicBlock *BB) {
296 return any_of(successors(BB), [&](BasicBlock *Succ) {
297 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
298 });
299 };
300 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
301 BasicBlock *BB = *I;
302 if (BlockIsInLoop(BB))
303 BlocksInLoopAfterFolding.insert(BB);
304 }
305
306 // Sanity check: header must be in loop.
307 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
308 "Header not in loop?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000309 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
310 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000311 }
312
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000313 /// We need to preserve static reachibility of all loop exit blocks (this is)
314 /// required by loop pass manager. In order to do it, we make the following
315 /// trick:
316 ///
317 /// preheader:
318 /// <preheader code>
319 /// br label %loop_header
320 ///
321 /// loop_header:
322 /// ...
323 /// br i1 false, label %dead_exit, label %loop_block
324 /// ...
325 ///
326 /// We cannot simply remove edge from the loop to dead exit because in this
327 /// case dead_exit (and its successors) may become unreachable. To avoid that,
328 /// we insert the following fictive preheader:
329 ///
330 /// preheader:
331 /// <preheader code>
332 /// switch i32 0, label %preheader-split,
333 /// [i32 1, label %dead_exit_1],
334 /// [i32 2, label %dead_exit_2],
335 /// ...
336 /// [i32 N, label %dead_exit_N],
337 ///
338 /// preheader-split:
339 /// br label %loop_header
340 ///
341 /// loop_header:
342 /// ...
343 /// br i1 false, label %dead_exit_N, label %loop_block
344 /// ...
345 ///
346 /// Doing so, we preserve static reachibility of all dead exits and can later
347 /// remove edges from the loop to these blocks.
348 void handleDeadExits() {
349 // If no dead exits, nothing to do.
350 if (DeadExitBlocks.empty())
351 return;
352
353 // Construct split preheader and the dummy switch to thread edges from it to
354 // dead exits.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000355 BasicBlock *Preheader = L.getLoopPreheader();
Alina Sbirlead2d32442019-02-21 19:54:05 +0000356 BasicBlock *NewPreheader = llvm::SplitBlock(
357 Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
358
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000359 IRBuilder<> Builder(Preheader->getTerminator());
360 SwitchInst *DummySwitch =
361 Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
362 Preheader->getTerminator()->eraseFromParent();
363
364 unsigned DummyIdx = 1;
365 for (BasicBlock *BB : DeadExitBlocks) {
366 SmallVector<Instruction *, 4> DeadPhis;
367 for (auto &PN : BB->phis())
368 DeadPhis.push_back(&PN);
369
370 // Eliminate all Phis from dead exits.
371 for (Instruction *PN : DeadPhis) {
372 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
373 PN->eraseFromParent();
374 }
375 assert(DummyIdx != 0 && "Too many dead exits!");
376 DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000377 DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000378 ++NumLoopExitsDeleted;
379 }
380
381 assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
382 if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000383 // When we break dead edges, the outer loop may become unreachable from
384 // the current loop. We need to fix loop info accordingly. For this, we
385 // find the most nested loop that still contains L and remove L from all
386 // loops that are inside of it.
Max Kazantsevd72c1a02019-02-17 15:22:48 +0000387 Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000388
389 // Okay, our loop is no longer in the outer loop (and maybe not in some of
390 // its parents as well). Make the fixup.
391 if (StillReachable != OuterLoop) {
392 LI.changeLoopFor(NewPreheader, StillReachable);
Max Kazantsevc065b022019-02-15 12:18:10 +0000393 removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
394 for (auto *BB : L.blocks())
395 removeBlockFromLoops(BB, OuterLoop, StillReachable);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000396 OuterLoop->removeChildLoop(&L);
397 if (StillReachable)
398 StillReachable->addChildLoop(&L);
399 else
400 LI.addTopLevelLoop(&L);
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000401
402 // Some values from loops in [OuterLoop, StillReachable) could be used
403 // in the current loop. Now it is not their child anymore, so such uses
404 // require LCSSA Phis.
405 Loop *FixLCSSALoop = OuterLoop;
406 while (FixLCSSALoop->getParentLoop() != StillReachable)
407 FixLCSSALoop = FixLCSSALoop->getParentLoop();
408 assert(FixLCSSALoop && "Should be a loop!");
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000409 // We need all DT updates to be done before forming LCSSA.
410 DTU.applyUpdates(DTUpdates);
Alina Sbirlead2d32442019-02-21 19:54:05 +0000411 if (MSSAU)
412 MSSAU->applyUpdates(DTUpdates, DT);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000413 DTUpdates.clear();
Max Kazantsev61a8d3f2019-01-17 12:51:10 +0000414 formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000415 }
416 }
Alina Sbirlead2d32442019-02-21 19:54:05 +0000417
418 if (MSSAU) {
419 // Clear all updates now. Facilitates deletes that follow.
420 DTU.applyUpdates(DTUpdates);
421 MSSAU->applyUpdates(DTUpdates, DT);
422 DTUpdates.clear();
423 if (VerifyMemorySSA)
424 MSSAU->getMemorySSA()->verifyMemorySSA();
425 }
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000426 }
427
Max Kazantsev347c5832018-12-24 06:06:17 +0000428 /// Delete loop blocks that have become unreachable after folding. Make all
429 /// relevant updates to DT and LI.
430 void deleteDeadLoopBlocks() {
Max Kazantsev80e4b402018-12-28 06:08:51 +0000431 if (MSSAU) {
Alina Sbirleadb101862019-07-12 22:30:30 +0000432 SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
433 DeadLoopBlocks.end());
Max Kazantsev80e4b402018-12-28 06:08:51 +0000434 MSSAU->removeBlocks(DeadLoopBlocksSet);
435 }
Max Kazantsevbf6af8f2019-02-12 09:37:00 +0000436
437 // The function LI.erase has some invariants that need to be preserved when
438 // it tries to remove a loop which is not the top-level loop. In particular,
439 // it requires loop's preheader to be strictly in loop's parent. We cannot
440 // just remove blocks one by one, because after removal of preheader we may
441 // break this invariant for the dead loop. So we detatch and erase all dead
442 // loops beforehand.
443 for (auto *BB : DeadLoopBlocks)
444 if (LI.isLoopHeader(BB)) {
445 assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
446 Loop *DL = LI.getLoopFor(BB);
447 if (DL->getParentLoop()) {
448 for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
449 for (auto *BB : DL->getBlocks())
450 PL->removeBlockFromLoop(BB);
451 DL->getParentLoop()->removeChildLoop(DL);
452 LI.addTopLevelLoop(DL);
453 }
454 LI.erase(DL);
455 }
456
Max Kazantsev347c5832018-12-24 06:06:17 +0000457 for (auto *BB : DeadLoopBlocks) {
458 assert(BB != L.getHeader() &&
459 "Header of the current loop cannot be dead!");
460 LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
461 << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000462 LI.removeBlock(BB);
Max Kazantsev347c5832018-12-24 06:06:17 +0000463 }
Max Kazantsev8b134162019-01-17 12:25:40 +0000464
Max Kazantsev6bf86152019-02-12 07:48:07 +0000465 DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000466 DTU.applyUpdates(DTUpdates);
467 DTUpdates.clear();
468 for (auto *BB : DeadLoopBlocks)
Max Kazantsev9aae9da2019-02-12 08:10:29 +0000469 DTU.deleteBB(BB);
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000470
Max Kazantsev8b134162019-01-17 12:25:40 +0000471 NumLoopBlocksDeleted += DeadLoopBlocks.size();
Max Kazantsev347c5832018-12-24 06:06:17 +0000472 }
473
Max Kazantsevc04b5302018-11-20 05:43:32 +0000474 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
475 /// unconditional branches.
476 void foldTerminators() {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000477 for (BasicBlock *BB : FoldCandidates) {
478 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
479 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
480 assert(TheOnlySucc && "Should have one live successor!");
481
482 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
483 << " with an unconditional branch to the block "
484 << TheOnlySucc->getName() << "\n");
485
486 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
487 // Remove all BB's successors except for the live one.
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000488 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000489 for (auto *Succ : successors(BB))
490 if (Succ != TheOnlySucc) {
491 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000492 // If our successor lies in a different loop, we don't want to remove
493 // the one-input Phi because it is a LCSSA Phi.
494 bool PreserveLCSSAPhi = !L.contains(Succ);
495 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000496 if (MSSAU)
497 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000498 } else
499 ++TheOnlySuccDuplicates;
500
501 assert(TheOnlySuccDuplicates > 0 && "Should be!");
502 // If TheOnlySucc was BB's successor more than once, after transform it
503 // will be its successor only once. Remove redundant inputs from
504 // TheOnlySucc's Phis.
505 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
506 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
507 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000508 if (MSSAU && TheOnlySuccDuplicates > 1)
509 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000510
511 IRBuilder<> Builder(BB->getContext());
512 Instruction *Term = BB->getTerminator();
513 Builder.SetInsertPoint(Term);
514 Builder.CreateBr(TheOnlySucc);
515 Term->eraseFromParent();
516
517 for (auto *DeadSucc : DeadSuccessors)
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000518 DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
Max Kazantsevc04b5302018-11-20 05:43:32 +0000519
520 ++NumTerminatorsFolded;
521 }
522 }
523
524public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000525 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
Max Kazantsev201534d2018-12-29 04:26:22 +0000526 ScalarEvolution &SE,
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000527 MemorySSAUpdater *MSSAU)
Max Kazantsev136f09b2019-02-15 11:39:35 +0000528 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000529 DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000530 bool run() {
531 assert(L.getLoopLatch() && "Should be single latch!");
532
533 // Collect all available information about status of blocks after constant
534 // folding.
535 analyze();
Max Kazantsev30095d92019-02-19 11:13:58 +0000536 BasicBlock *Header = L.getHeader();
537 (void)Header;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000538
Max Kazantsev30095d92019-02-19 11:13:58 +0000539 LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
Max Kazantsevc04b5302018-11-20 05:43:32 +0000540 << ": ");
541
Max Kazantseva523a212018-12-07 05:44:45 +0000542 if (HasIrreducibleCFG) {
543 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
544 return false;
545 }
546
Max Kazantsevc04b5302018-11-20 05:43:32 +0000547 // Nothing to constant-fold.
548 if (FoldCandidates.empty()) {
549 LLVM_DEBUG(
550 dbgs() << "No constant terminator folding candidates found in loop "
Max Kazantsev30095d92019-02-19 11:13:58 +0000551 << Header->getName() << "\n");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000552 return false;
553 }
554
555 // TODO: Support deletion of the current loop.
556 if (DeleteCurrentLoop) {
557 LLVM_DEBUG(
558 dbgs()
Max Kazantsev30095d92019-02-19 11:13:58 +0000559 << "Give up constant terminator folding in loop " << Header->getName()
Max Kazantsevc04b5302018-11-20 05:43:32 +0000560 << ": we don't currently support deletion of the current loop.\n");
561 return false;
562 }
563
Max Kazantsevc04b5302018-11-20 05:43:32 +0000564 // TODO: Support blocks that are not dead, but also not in loop after the
565 // folding.
Max Kazantsev347c5832018-12-24 06:06:17 +0000566 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
567 L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000568 LLVM_DEBUG(
569 dbgs() << "Give up constant terminator folding in loop "
Max Kazantsev30095d92019-02-19 11:13:58 +0000570 << Header->getName() << ": we don't currently"
Max Kazantsevc04b5302018-11-20 05:43:32 +0000571 " support blocks that are not dead, but will stop "
572 "being a part of the loop after constant-folding.\n");
573 return false;
574 }
575
Max Kazantsev201534d2018-12-29 04:26:22 +0000576 SE.forgetTopmostLoop(&L);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000577 // Dump analysis results.
578 LLVM_DEBUG(dump());
579
580 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
Max Kazantsev30095d92019-02-19 11:13:58 +0000581 << " terminators in loop " << Header->getName() << "\n");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000582
583 // Make the actual transforms.
Max Kazantsevedabb9a2018-12-24 07:41:33 +0000584 handleDeadExits();
Max Kazantsevc04b5302018-11-20 05:43:32 +0000585 foldTerminators();
586
Max Kazantsev347c5832018-12-24 06:06:17 +0000587 if (!DeadLoopBlocks.empty()) {
588 LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
Max Kazantsev30095d92019-02-19 11:13:58 +0000589 << " dead blocks in loop " << Header->getName() << "\n");
Max Kazantsev347c5832018-12-24 06:06:17 +0000590 deleteDeadLoopBlocks();
Max Kazantsev6b63d3a2019-02-08 08:12:41 +0000591 } else {
592 // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
593 DTU.applyUpdates(DTUpdates);
594 DTUpdates.clear();
Max Kazantsev347c5832018-12-24 06:06:17 +0000595 }
596
Alina Sbirlead2d32442019-02-21 19:54:05 +0000597 if (MSSAU && VerifyMemorySSA)
598 MSSAU->getMemorySSA()->verifyMemorySSA();
599
Max Kazantsevc04b5302018-11-20 05:43:32 +0000600#ifndef NDEBUG
601 // Make sure that we have preserved all data structures after the transform.
Yevgeny Rouban0822bfc2019-04-29 13:29:55 +0000602#if defined(EXPENSIVE_CHECKS)
603 assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
604 "DT broken after transform!");
605#else
606 assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
607 "DT broken after transform!");
608#endif
Max Kazantsev30095d92019-02-19 11:13:58 +0000609 assert(DT.isReachableFromEntry(Header));
Max Kazantsevc04b5302018-11-20 05:43:32 +0000610 LI.verify(DT);
611#endif
612
613 return true;
614 }
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000615
616 bool foldingBreaksCurrentLoop() const {
617 return DeleteCurrentLoop;
618 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000619};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000620} // namespace
Max Kazantsevc04b5302018-11-20 05:43:32 +0000621
622/// Turn branches and switches with known constant conditions into unconditional
623/// branches.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000624static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsev201534d2018-12-29 04:26:22 +0000625 ScalarEvolution &SE,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000626 MemorySSAUpdater *MSSAU,
627 bool &IsLoopDeleted) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000628 if (!EnableTermFolding)
629 return false;
630
Max Kazantsevc04b5302018-11-20 05:43:32 +0000631 // To keep things simple, only process loops with single latch. We
632 // canonicalize most loops to this form. We can support multi-latch if needed.
633 if (!L.getLoopLatch())
634 return false;
635
Max Kazantsev201534d2018-12-29 04:26:22 +0000636 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000637 bool Changed = BranchFolder.run();
638 IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
639 return Changed;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000640}
641
Max Kazantsev46955b52018-11-01 09:42:50 +0000642static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
643 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000644 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000645 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000646 // Copy blocks into a temporary array to avoid iterator invalidation issues
647 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000648 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000649
650 for (auto &Block : Blocks) {
651 // Attempt to merge blocks in the trivial case. Don't modify blocks which
652 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000653 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000654 if (!Succ)
655 continue;
656
657 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000658 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000659 continue;
660
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000661 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000662 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000663
Fiona Glaserb417d462016-01-29 22:35:36 +0000664 Changed = true;
665 }
666
667 return Changed;
668}
669
Max Kazantsev46955b52018-11-01 09:42:50 +0000670static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000671 ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
672 bool &isLoopDeleted) {
Max Kazantsev46955b52018-11-01 09:42:50 +0000673 bool Changed = false;
674
Max Kazantsevc04b5302018-11-20 05:43:32 +0000675 // Constant-fold terminators with known constant conditions.
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000676 Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, isLoopDeleted);
677
678 if (isLoopDeleted)
679 return true;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000680
Max Kazantsev46955b52018-11-01 09:42:50 +0000681 // Eliminate unconditional branches by merging blocks into their predecessors.
682 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
683
684 if (Changed)
685 SE.forgetTopmostLoop(&L);
686
687 return Changed;
688}
689
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000690PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
691 LoopStandardAnalysisResults &AR,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000692 LPMUpdater &LPMU) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000693 Optional<MemorySSAUpdater> MSSAU;
Alina Sbirleaf92109d2019-08-17 01:02:12 +0000694 if (AR.MSSA)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000695 MSSAU = MemorySSAUpdater(AR.MSSA);
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000696 bool DeleteCurrentLoop = false;
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000697 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000698 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
699 DeleteCurrentLoop))
Justin Bognerab6a5132016-05-03 21:47:32 +0000700 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000701
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000702 if (DeleteCurrentLoop)
703 LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
704
Alina Sbirlea3cef1f72019-06-11 18:27:49 +0000705 auto PA = getLoopPassPreservedAnalyses();
Alina Sbirleaf92109d2019-08-17 01:02:12 +0000706 if (AR.MSSA)
Alina Sbirlea3cef1f72019-06-11 18:27:49 +0000707 PA.preserve<MemorySSAAnalysis>();
708 return PA;
Justin Bognerab6a5132016-05-03 21:47:32 +0000709}
710
711namespace {
712class LoopSimplifyCFGLegacyPass : public LoopPass {
713public:
714 static char ID; // Pass ID, replacement for typeid
715 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
716 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
717 }
718
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000719 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
Justin Bognerab6a5132016-05-03 21:47:32 +0000720 if (skipLoop(L))
721 return false;
722
723 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
724 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000725 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000726 Optional<MemorySSAUpdater> MSSAU;
727 if (EnableMSSALoopDependency) {
728 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
729 MSSAU = MemorySSAUpdater(MSSA);
730 if (VerifyMemorySSA)
731 MSSA->verifyMemorySSA();
732 }
Max Kazantsevebd95ea2019-02-19 11:14:05 +0000733 bool DeleteCurrentLoop = false;
734 bool Changed = simplifyLoopCFG(
735 *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
736 DeleteCurrentLoop);
737 if (DeleteCurrentLoop)
738 LPM.markLoopAsDeleted(*L);
739 return Changed;
Justin Bognerab6a5132016-05-03 21:47:32 +0000740 }
741
742 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000743 if (EnableMSSALoopDependency) {
744 AU.addRequired<MemorySSAWrapperPass>();
745 AU.addPreserved<MemorySSAWrapperPass>();
746 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000747 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000748 getLoopAnalysisUsage(AU);
749 }
750};
751}
752
753char LoopSimplifyCFGLegacyPass::ID = 0;
754INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
755 "Simplify loop CFG", false, false)
756INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000757INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000758INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
759 "Simplify loop CFG", false, false)
760
761Pass *llvm::createLoopSimplifyCFGPass() {
762 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000763}