blob: c370efa120772714e2d3f56bc4e3c60e3cfcc71d [file] [log] [blame]
Fiona Glaserb417d462016-01-29 22:35:36 +00001//===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Loop SimplifyCFG Pass. This pass is responsible for
11// basic loop CFG cleanup, primarily to assist other loop passes. If you
12// encounter a noncanonical CFG construct that causes another loop pass to
13// perform suboptimally, this is the place to fix it up.
14//
15//===----------------------------------------------------------------------===//
16
Justin Bognerab6a5132016-05-03 21:47:32 +000017#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000018#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasperaec2fa32016-12-19 08:22:17 +000021#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruth3bab7e12017-01-11 09:43:56 +000022#include "llvm/Analysis/BasicAliasAnalysis.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000023#include "llvm/Analysis/DependenceAnalysis.h"
24#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"
Chijun Sima21a8b602018-08-03 05:08:17 +000032#include "llvm/IR/DomTreeUpdater.h"
Fiona Glaserb417d462016-01-29 22:35:36 +000033#include "llvm/IR/Dominators.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 Kazantsev9cf417d2018-11-30 10:06:23 +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");
49
50/// If \p BB is a switch or a conditional branch, but only one of its successors
51/// can be reached from this block in runtime, return this successor. Otherwise,
52/// return nullptr.
53static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
54 Instruction *TI = BB->getTerminator();
55 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
56 if (BI->isUnconditional())
57 return nullptr;
58 if (BI->getSuccessor(0) == BI->getSuccessor(1))
59 return BI->getSuccessor(0);
60 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
61 if (!Cond)
62 return nullptr;
63 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
64 }
65
66 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
67 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
68 if (!CI)
69 return nullptr;
70 for (auto Case : SI->cases())
71 if (Case.getCaseValue() == CI)
72 return Case.getCaseSuccessor();
73 return SI->getDefaultDest();
74 }
75
76 return nullptr;
77}
78
79/// Helper class that can turn branches and switches with constant conditions
80/// into unconditional branches.
81class ConstantTerminatorFoldingImpl {
82private:
83 Loop &L;
84 LoopInfo &LI;
85 DominatorTree &DT;
Max Kazantsev9cf417d2018-11-30 10:06:23 +000086 MemorySSAUpdater *MSSAU;
Max Kazantsevc04b5302018-11-20 05:43:32 +000087
Max Kazantseva523a212018-12-07 05:44:45 +000088 // Whether or not the current loop has irreducible CFG.
89 bool HasIrreducibleCFG = false;
Max Kazantsevc04b5302018-11-20 05:43:32 +000090 // Whether or not the current loop will still exist after terminator constant
91 // folding will be done. In theory, there are two ways how it can happen:
92 // 1. Loop's latch(es) become unreachable from loop header;
93 // 2. Loop's header becomes unreachable from method entry.
94 // In practice, the second situation is impossible because we only modify the
95 // current loop and its preheader and do not affect preheader's reachibility
96 // from any other block. So this variable set to true means that loop's latch
97 // has become unreachable from loop header.
98 bool DeleteCurrentLoop = false;
99
100 // The blocks of the original loop that will still be reachable from entry
101 // after the constant folding.
102 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
103 // The blocks of the original loop that will become unreachable from entry
104 // after the constant folding.
105 SmallPtrSet<BasicBlock *, 8> DeadLoopBlocks;
106 // The exits of the original loop that will still be reachable from entry
107 // after the constant folding.
108 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
109 // The exits of the original loop that will become unreachable from entry
110 // after the constant folding.
Max Kazantsev56a24432018-11-22 12:33:41 +0000111 SmallVector<BasicBlock *, 8> DeadExitBlocks;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000112 // The blocks that will still be a part of the current loop after folding.
113 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
114 // The blocks that have terminators with constant condition that can be
115 // folded. Note: fold candidates should be in L but not in any of its
116 // subloops to avoid complex LI updates.
117 SmallVector<BasicBlock *, 8> FoldCandidates;
118
119 void dump() const {
120 dbgs() << "Constant terminator folding for loop " << L << "\n";
121 dbgs() << "After terminator constant-folding, the loop will";
122 if (!DeleteCurrentLoop)
123 dbgs() << " not";
124 dbgs() << " be destroyed\n";
Max Kazantsev56a24432018-11-22 12:33:41 +0000125 auto PrintOutVector = [&](const char *Message,
126 const SmallVectorImpl<BasicBlock *> &S) {
127 dbgs() << Message << "\n";
128 for (const BasicBlock *BB : S)
129 dbgs() << "\t" << BB->getName() << "\n";
130 };
Max Kazantsevc04b5302018-11-20 05:43:32 +0000131 auto PrintOutSet = [&](const char *Message,
132 const SmallPtrSetImpl<BasicBlock *> &S) {
133 dbgs() << Message << "\n";
134 for (const BasicBlock *BB : S)
135 dbgs() << "\t" << BB->getName() << "\n";
136 };
Max Kazantsev56a24432018-11-22 12:33:41 +0000137 PrintOutVector("Blocks in which we can constant-fold terminator:",
138 FoldCandidates);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000139 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
140 PrintOutSet("Dead blocks from the original loop:", DeadLoopBlocks);
141 PrintOutSet("Live exit blocks:", LiveExitBlocks);
Max Kazantsev56a24432018-11-22 12:33:41 +0000142 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000143 if (!DeleteCurrentLoop)
144 PrintOutSet("The following blocks will still be part of the loop:",
145 BlocksInLoopAfterFolding);
146 }
147
Max Kazantseva523a212018-12-07 05:44:45 +0000148 /// Whether or not the current loop has irreducible CFG.
149 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
150 assert(DFS.isComplete() && "DFS is expected to be finished");
151 // Index of a basic block in RPO traversal.
152 DenseMap<const BasicBlock *, unsigned> RPO;
153 unsigned Current = 0;
154 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
155 RPO[*I] = Current++;
156
157 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
158 BasicBlock *BB = *I;
159 for (auto *Succ : successors(BB))
160 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
161 // If an edge goes from a block with greater order number into a block
162 // with lesses number, and it is not a loop backedge, then it can only
163 // be a part of irreducible non-loop cycle.
164 return true;
165 }
166 return false;
167 }
168
Max Kazantsevc04b5302018-11-20 05:43:32 +0000169 /// Fill all information about status of blocks and exits of the current loop
170 /// if constant folding of all branches will be done.
171 void analyze() {
172 LoopBlocksDFS DFS(&L);
173 DFS.perform(&LI);
174 assert(DFS.isComplete() && "DFS is expected to be finished");
175
Max Kazantseva523a212018-12-07 05:44:45 +0000176 // TODO: The algorithm below relies on both RPO and Postorder traversals.
177 // When the loop has only reducible CFG inside, then the invariant "all
178 // predecessors of X are processed before X in RPO" is preserved. However
179 // an irreducible loop can break this invariant (e.g. latch does not have to
180 // be the last block in the traversal in this case, and the algorithm relies
181 // on this). We can later decide to support such cases by altering the
182 // algorithms, but so far we just give up analyzing them.
183 if (hasIrreducibleCFG(DFS)) {
184 HasIrreducibleCFG = true;
185 return;
186 }
187
Max Kazantsevc04b5302018-11-20 05:43:32 +0000188 // Collect live and dead loop blocks and exits.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000189 LiveLoopBlocks.insert(L.getHeader());
190 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
191 BasicBlock *BB = *I;
192
193 // If a loop block wasn't marked as live so far, then it's dead.
194 if (!LiveLoopBlocks.count(BB)) {
195 DeadLoopBlocks.insert(BB);
196 continue;
197 }
198
199 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
200
201 // If a block has only one live successor, it's a candidate on constant
202 // folding. Only handle blocks from current loop: branches in child loops
203 // are skipped because if they can be folded, they should be folded during
204 // the processing of child loops.
205 if (TheOnlySucc && LI.getLoopFor(BB) == &L)
206 FoldCandidates.push_back(BB);
207
208 // Handle successors.
Max Kazantsevc04b5302018-11-20 05:43:32 +0000209 for (BasicBlock *Succ : successors(BB))
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000210 if (!TheOnlySucc || TheOnlySucc == Succ) {
211 if (L.contains(Succ))
212 LiveLoopBlocks.insert(Succ);
213 else
214 LiveExitBlocks.insert(Succ);
215 }
Max Kazantsevc04b5302018-11-20 05:43:32 +0000216 }
217
218 // Sanity check: amount of dead and live loop blocks should match the total
219 // number of blocks in loop.
220 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
221 "Malformed block sets?");
222
223 // Now, all exit blocks that are not marked as live are dead.
Max Kazantsevd9f59f82018-11-22 10:48:30 +0000224 SmallVector<BasicBlock *, 8> ExitBlocks;
225 L.getExitBlocks(ExitBlocks);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000226 for (auto *ExitBlock : ExitBlocks)
227 if (!LiveExitBlocks.count(ExitBlock))
Max Kazantsev56a24432018-11-22 12:33:41 +0000228 DeadExitBlocks.push_back(ExitBlock);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000229
230 // Whether or not the edge From->To will still be present in graph after the
231 // folding.
232 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
233 if (!LiveLoopBlocks.count(From))
234 return false;
235 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
236 return !TheOnlySucc || TheOnlySucc == To;
237 };
238
239 // The loop will not be destroyed if its latch is live.
240 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
241
242 // If we are going to delete the current loop completely, no extra analysis
243 // is needed.
244 if (DeleteCurrentLoop)
245 return;
246
247 // Otherwise, we should check which blocks will still be a part of the
248 // current loop after the transform.
249 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
250 // If the loop is live, then we should compute what blocks are still in
251 // loop after all branch folding has been done. A block is in loop if
252 // it has a live edge to another block that is in the loop; by definition,
253 // latch is in the loop.
254 auto BlockIsInLoop = [&](BasicBlock *BB) {
255 return any_of(successors(BB), [&](BasicBlock *Succ) {
256 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
257 });
258 };
259 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
260 BasicBlock *BB = *I;
261 if (BlockIsInLoop(BB))
262 BlocksInLoopAfterFolding.insert(BB);
263 }
264
265 // Sanity check: header must be in loop.
266 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
267 "Header not in loop?");
Max Kazantsevb565e602018-11-22 12:43:27 +0000268 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
269 "All blocks that stay in loop should be live!");
Max Kazantsevc04b5302018-11-20 05:43:32 +0000270 }
271
272 /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
273 /// unconditional branches.
274 void foldTerminators() {
275 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
276
277 for (BasicBlock *BB : FoldCandidates) {
278 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
279 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
280 assert(TheOnlySucc && "Should have one live successor!");
281
282 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
283 << " with an unconditional branch to the block "
284 << TheOnlySucc->getName() << "\n");
285
286 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
287 // Remove all BB's successors except for the live one.
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000288 unsigned TheOnlySuccDuplicates = 0;
Max Kazantsevc04b5302018-11-20 05:43:32 +0000289 for (auto *Succ : successors(BB))
290 if (Succ != TheOnlySucc) {
291 DeadSuccessors.insert(Succ);
Max Kazantsevcb8e2402018-11-23 07:56:47 +0000292 // If our successor lies in a different loop, we don't want to remove
293 // the one-input Phi because it is a LCSSA Phi.
294 bool PreserveLCSSAPhi = !L.contains(Succ);
295 Succ->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000296 if (MSSAU)
297 MSSAU->removeEdge(BB, Succ);
Max Kazantsevc4e4d642018-11-27 06:17:21 +0000298 } else
299 ++TheOnlySuccDuplicates;
300
301 assert(TheOnlySuccDuplicates > 0 && "Should be!");
302 // If TheOnlySucc was BB's successor more than once, after transform it
303 // will be its successor only once. Remove redundant inputs from
304 // TheOnlySucc's Phis.
305 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
306 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
307 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000308 if (MSSAU && TheOnlySuccDuplicates > 1)
309 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000310
311 IRBuilder<> Builder(BB->getContext());
312 Instruction *Term = BB->getTerminator();
313 Builder.SetInsertPoint(Term);
314 Builder.CreateBr(TheOnlySucc);
315 Term->eraseFromParent();
316
317 for (auto *DeadSucc : DeadSuccessors)
318 DTU.deleteEdge(BB, DeadSucc);
319
320 ++NumTerminatorsFolded;
321 }
322 }
323
324public:
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000325 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
326 MemorySSAUpdater *MSSAU)
327 : L(L), LI(LI), DT(DT), MSSAU(MSSAU) {}
Max Kazantsevc04b5302018-11-20 05:43:32 +0000328 bool run() {
329 assert(L.getLoopLatch() && "Should be single latch!");
330
331 // Collect all available information about status of blocks after constant
332 // folding.
333 analyze();
334
335 LLVM_DEBUG(dbgs() << "In function " << L.getHeader()->getParent()->getName()
336 << ": ");
337
Max Kazantseva523a212018-12-07 05:44:45 +0000338 if (HasIrreducibleCFG) {
339 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
340 return false;
341 }
342
Max Kazantsevc04b5302018-11-20 05:43:32 +0000343 // Nothing to constant-fold.
344 if (FoldCandidates.empty()) {
345 LLVM_DEBUG(
346 dbgs() << "No constant terminator folding candidates found in loop "
347 << L.getHeader()->getName() << "\n");
348 return false;
349 }
350
351 // TODO: Support deletion of the current loop.
352 if (DeleteCurrentLoop) {
353 LLVM_DEBUG(
354 dbgs()
355 << "Give up constant terminator folding in loop "
356 << L.getHeader()->getName()
357 << ": we don't currently support deletion of the current loop.\n");
358 return false;
359 }
360
Ilya Biryukovcb5331eb2018-12-06 13:21:01 +0000361 // TODO: Support deletion of dead loop blocks.
362 if (!DeadLoopBlocks.empty()) {
363 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
364 << L.getHeader()->getName()
365 << ": we don't currently"
366 " support deletion of dead in-loop blocks.\n");
367 return false;
368 }
369
Max Kazantsevc04b5302018-11-20 05:43:32 +0000370 // TODO: Support dead loop exits.
371 if (!DeadExitBlocks.empty()) {
372 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
373 << L.getHeader()->getName()
374 << ": we don't currently support dead loop exits.\n");
375 return false;
376 }
377
378 // TODO: Support blocks that are not dead, but also not in loop after the
379 // folding.
Ilya Biryukovcb5331eb2018-12-06 13:21:01 +0000380 if (BlocksInLoopAfterFolding.size() != L.getNumBlocks()) {
Max Kazantsevc04b5302018-11-20 05:43:32 +0000381 LLVM_DEBUG(
382 dbgs() << "Give up constant terminator folding in loop "
383 << L.getHeader()->getName()
384 << ": we don't currently"
385 " support blocks that are not dead, but will stop "
386 "being a part of the loop after constant-folding.\n");
387 return false;
388 }
389
390 // Dump analysis results.
391 LLVM_DEBUG(dump());
392
393 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
394 << " terminators in loop " << L.getHeader()->getName()
395 << "\n");
396
397 // Make the actual transforms.
398 foldTerminators();
399
400#ifndef NDEBUG
401 // Make sure that we have preserved all data structures after the transform.
402 DT.verify();
403 assert(DT.isReachableFromEntry(L.getHeader()));
404 LI.verify(DT);
405#endif
406
407 return true;
408 }
409};
410
411/// Turn branches and switches with known constant conditions into unconditional
412/// branches.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000413static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
414 MemorySSAUpdater *MSSAU) {
Max Kazantseve1c2dc22018-11-23 09:14:53 +0000415 if (!EnableTermFolding)
416 return false;
417
Max Kazantsevc04b5302018-11-20 05:43:32 +0000418 // To keep things simple, only process loops with single latch. We
419 // canonicalize most loops to this form. We can support multi-latch if needed.
420 if (!L.getLoopLatch())
421 return false;
422
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000423 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000424 return BranchFolder.run();
425}
426
Max Kazantsev46955b52018-11-01 09:42:50 +0000427static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
428 LoopInfo &LI, MemorySSAUpdater *MSSAU) {
Fiona Glaserb417d462016-01-29 22:35:36 +0000429 bool Changed = false;
Chijun Sima21a8b602018-08-03 05:08:17 +0000430 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Fiona Glaserb417d462016-01-29 22:35:36 +0000431 // Copy blocks into a temporary array to avoid iterator invalidation issues
432 // as we remove them.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +0000433 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
Fiona Glaserb417d462016-01-29 22:35:36 +0000434
435 for (auto &Block : Blocks) {
436 // Attempt to merge blocks in the trivial case. Don't modify blocks which
437 // belong to other loops.
Fiona Glaser36e82302016-01-29 23:12:52 +0000438 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
Fiona Glaserb417d462016-01-29 22:35:36 +0000439 if (!Succ)
440 continue;
441
442 BasicBlock *Pred = Succ->getSinglePredecessor();
Justin Bognerab6a5132016-05-03 21:47:32 +0000443 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
Fiona Glaserb417d462016-01-29 22:35:36 +0000444 continue;
445
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000446 // Merge Succ into Pred and delete it.
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000447 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
David Greene6a9c242018-06-19 09:43:36 +0000448
Fiona Glaserb417d462016-01-29 22:35:36 +0000449 Changed = true;
450 }
451
452 return Changed;
453}
454
Max Kazantsev46955b52018-11-01 09:42:50 +0000455static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
456 ScalarEvolution &SE, MemorySSAUpdater *MSSAU) {
457 bool Changed = false;
458
Max Kazantsevc04b5302018-11-20 05:43:32 +0000459 // Constant-fold terminators with known constant conditions.
Max Kazantsev9cf417d2018-11-30 10:06:23 +0000460 Changed |= constantFoldTerminators(L, DT, LI, MSSAU);
Max Kazantsevc04b5302018-11-20 05:43:32 +0000461
Max Kazantsev46955b52018-11-01 09:42:50 +0000462 // Eliminate unconditional branches by merging blocks into their predecessors.
463 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
464
465 if (Changed)
466 SE.forgetTopmostLoop(&L);
467
468 return Changed;
469}
470
Chandler Carruth410eaeb2017-01-11 06:23:21 +0000471PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
472 LoopStandardAnalysisResults &AR,
473 LPMUpdater &) {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000474 Optional<MemorySSAUpdater> MSSAU;
475 if (EnableMSSALoopDependency && AR.MSSA)
476 MSSAU = MemorySSAUpdater(AR.MSSA);
477 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
478 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr))
Justin Bognerab6a5132016-05-03 21:47:32 +0000479 return PreservedAnalyses::all();
Chandler Carruthca68a3e2017-01-15 06:32:49 +0000480
Justin Bognerab6a5132016-05-03 21:47:32 +0000481 return getLoopPassPreservedAnalyses();
482}
483
484namespace {
485class LoopSimplifyCFGLegacyPass : public LoopPass {
486public:
487 static char ID; // Pass ID, replacement for typeid
488 LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
489 initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
490 }
491
492 bool runOnLoop(Loop *L, LPPassManager &) override {
493 if (skipLoop(L))
494 return false;
495
496 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
497 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
David Greene6a9c242018-06-19 09:43:36 +0000498 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000499 Optional<MemorySSAUpdater> MSSAU;
500 if (EnableMSSALoopDependency) {
501 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
502 MSSAU = MemorySSAUpdater(MSSA);
503 if (VerifyMemorySSA)
504 MSSA->verifyMemorySSA();
505 }
506 return simplifyLoopCFG(*L, DT, LI, SE,
507 MSSAU.hasValue() ? MSSAU.getPointer() : nullptr);
Justin Bognerab6a5132016-05-03 21:47:32 +0000508 }
509
510 void getAnalysisUsage(AnalysisUsage &AU) const override {
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000511 if (EnableMSSALoopDependency) {
512 AU.addRequired<MemorySSAWrapperPass>();
513 AU.addPreserved<MemorySSAWrapperPass>();
514 }
Chandler Carruth49c22192016-05-12 22:19:39 +0000515 AU.addPreserved<DependenceAnalysisWrapperPass>();
Justin Bognerab6a5132016-05-03 21:47:32 +0000516 getLoopAnalysisUsage(AU);
517 }
518};
519}
520
521char LoopSimplifyCFGLegacyPass::ID = 0;
522INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
523 "Simplify loop CFG", false, false)
524INITIALIZE_PASS_DEPENDENCY(LoopPass)
Alina Sbirlea8b83d682018-08-22 20:10:21 +0000525INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
Justin Bognerab6a5132016-05-03 21:47:32 +0000526INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
527 "Simplify loop CFG", false, false)
528
529Pass *llvm::createLoopSimplifyCFGPass() {
530 return new LoopSimplifyCFGLegacyPass();
Fiona Glaserb417d462016-01-29 22:35:36 +0000531}