LLVM 24.0.0git
LoopSimplifyCFG.cpp
Go to the documentation of this file.
1//===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//
2//
3// 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
6//
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
18#include "llvm/ADT/Statistic.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/IRBuilder.h"
33#include <optional>
34using namespace llvm;
35
36#define DEBUG_TYPE "loop-simplifycfg"
37
38static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
39 cl::init(true));
40
41STATISTIC(NumTerminatorsFolded,
42 "Number of terminators folded to unconditional branches");
43STATISTIC(NumLoopBlocksDeleted,
44 "Number of loop blocks deleted");
45STATISTIC(NumLoopExitsDeleted,
46 "Number of loop exiting edges deleted");
47
48/// If \p BB is a switch or a conditional branch, but only one of its successors
49/// can be reached from this block in runtime, return this successor. Otherwise,
50/// return nullptr.
52 Instruction *TI = BB->getTerminator();
53 if (CondBrInst *BI = dyn_cast<CondBrInst>(TI)) {
54 if (BI->getSuccessor(0) == BI->getSuccessor(1))
55 return BI->getSuccessor(0);
56 ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
57 if (!Cond)
58 return nullptr;
59 return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
60 }
61
63 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
64 if (!CI)
65 return nullptr;
66 for (auto Case : SI->cases())
67 if (Case.getCaseValue() == CI)
68 return Case.getCaseSuccessor();
69 return SI->getDefaultDest();
70 }
71
72 return nullptr;
73}
74
75/// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
76static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
77 Loop *LastLoop = nullptr) {
78 assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
79 "First loop is supposed to be inside of last loop!");
80 for (Loop *Current = FirstLoop; Current != LastLoop;
81 Current = Current->getParentLoop())
82 Current->removeBlockFromLoop(BB);
83}
84
85/// Find innermost loop that contains at least one block from \p BBs and
86/// contains the header of loop \p L.
88 Loop &L, LoopInfo &LI) {
89 Loop *Innermost = nullptr;
90 for (BasicBlock *BB : BBs) {
91 Loop *BBL = LI.getLoopFor(BB);
92 while (BBL && !BBL->contains(L.getHeader()))
93 BBL = BBL->getParentLoop();
94 if (BBL == &L)
95 BBL = BBL->getParentLoop();
96 if (!BBL)
97 continue;
98 if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
99 Innermost = BBL;
100 }
101 return Innermost;
102}
103
104namespace {
105/// Helper class that can turn branches and switches with constant conditions
106/// into unconditional branches.
107class ConstantTerminatorFoldingImpl {
108private:
109 Loop &L;
110 LoopInfo &LI;
111 DominatorTree &DT;
112 ScalarEvolution &SE;
113 MemorySSAUpdater *MSSAU;
114 LoopBlocksDFS DFS;
115 DomTreeUpdater DTU;
117
118 // Whether or not the current loop has irreducible CFG.
119 bool HasIrreducibleCFG = false;
120 // Whether or not the current loop will still exist after terminator constant
121 // folding will be done. In theory, there are two ways how it can happen:
122 // 1. Loop's latch(es) become unreachable from loop header;
123 // 2. Loop's header becomes unreachable from method entry.
124 // In practice, the second situation is impossible because we only modify the
125 // current loop and its preheader and do not affect preheader's reachibility
126 // from any other block. So this variable set to true means that loop's latch
127 // has become unreachable from loop header.
128 bool DeleteCurrentLoop = false;
129 // Whether or not we enter the loop through an indirectbr.
130 bool HasIndirectEntry = false;
131
132 // The blocks of the original loop that will still be reachable from entry
133 // after the constant folding.
134 SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
135 // The blocks of the original loop that will become unreachable from entry
136 // after the constant folding.
137 SmallVector<BasicBlock *, 8> DeadLoopBlocks;
138 // The exits of the original loop that will still be reachable from entry
139 // after the constant folding.
140 SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
141 // The exits of the original loop that will become unreachable from entry
142 // after the constant folding.
143 SmallVector<BasicBlock *, 8> DeadExitBlocks;
144 // The blocks that will still be a part of the current loop after folding.
145 SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
146 // The blocks that have terminators with constant condition that can be
147 // folded. Note: fold candidates should be in L but not in any of its
148 // subloops to avoid complex LI updates.
149 SmallVector<BasicBlock *, 8> FoldCandidates;
150
151 void dump() const {
152 dbgs() << "Constant terminator folding for loop " << L << "\n";
153 dbgs() << "After terminator constant-folding, the loop will";
154 if (!DeleteCurrentLoop)
155 dbgs() << " not";
156 dbgs() << " be destroyed\n";
157 auto PrintOutVector = [&](const char *Message,
158 const SmallVectorImpl<BasicBlock *> &S) {
159 dbgs() << Message << "\n";
160 for (const BasicBlock *BB : S)
161 dbgs() << "\t" << BB->getName() << "\n";
162 };
163 auto PrintOutSet = [&](const char *Message,
164 const SmallPtrSetImpl<BasicBlock *> &S) {
165 dbgs() << Message << "\n";
166 for (const BasicBlock *BB : S)
167 dbgs() << "\t" << BB->getName() << "\n";
168 };
169 PrintOutVector("Blocks in which we can constant-fold terminator:",
170 FoldCandidates);
171 PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
172 PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
173 PrintOutSet("Live exit blocks:", LiveExitBlocks);
174 PrintOutVector("Dead exit blocks:", DeadExitBlocks);
175 if (!DeleteCurrentLoop)
176 PrintOutSet("The following blocks will still be part of the loop:",
177 BlocksInLoopAfterFolding);
178 }
179
180 /// Whether or not the current loop has irreducible CFG.
181 bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
182 assert(DFS.isComplete() && "DFS is expected to be finished");
183 // Index of a basic block in RPO traversal.
184 DenseMap<const BasicBlock *, unsigned> RPO;
185 unsigned Current = 0;
186 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
187 RPO[*I] = Current++;
188
189 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
190 BasicBlock *BB = *I;
191 for (auto *Succ : successors(BB))
192 if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
193 // If an edge goes from a block with greater order number into a block
194 // with lesses number, and it is not a loop backedge, then it can only
195 // be a part of irreducible non-loop cycle.
196 return true;
197 }
198 return false;
199 }
200
201 /// Fill all information about status of blocks and exits of the current loop
202 /// if constant folding of all branches will be done.
203 void analyze() {
204 DFS.perform(&LI);
205 assert(DFS.isComplete() && "DFS is expected to be finished");
206
207 // TODO: The algorithm below relies on both RPO and Postorder traversals.
208 // When the loop has only reducible CFG inside, then the invariant "all
209 // predecessors of X are processed before X in RPO" is preserved. However
210 // an irreducible loop can break this invariant (e.g. latch does not have to
211 // be the last block in the traversal in this case, and the algorithm relies
212 // on this). We can later decide to support such cases by altering the
213 // algorithms, but so far we just give up analyzing them.
214 if (hasIrreducibleCFG(DFS)) {
215 HasIrreducibleCFG = true;
216 return;
217 }
218
219 // We need a loop preheader to split in handleDeadExits(). If LoopSimplify
220 // wasn't able to form one because the loop can be entered through an
221 // indirectbr we cannot continue.
222 if (!L.getLoopPreheader()) {
223 assert(any_of(predecessors(L.getHeader()),
224 [&](BasicBlock *Pred) {
225 return isa<IndirectBrInst>(Pred->getTerminator());
226 }) &&
227 "Loop should have preheader if it is not entered indirectly");
228 HasIndirectEntry = true;
229 return;
230 }
231
232 // Collect live and dead loop blocks and exits.
233 LiveLoopBlocks.insert(L.getHeader());
234 for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
235 BasicBlock *BB = *I;
236
237 // If a loop block wasn't marked as live so far, then it's dead.
238 if (!LiveLoopBlocks.count(BB)) {
239 DeadLoopBlocks.push_back(BB);
240 continue;
241 }
242
243 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
244
245 // If a block has only one live successor, it's a candidate on constant
246 // folding. Only handle blocks from current loop: branches in child loops
247 // are skipped because if they can be folded, they should be folded during
248 // the processing of child loops.
249 bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
250 if (TakeFoldCandidate)
251 FoldCandidates.push_back(BB);
252
253 // Handle successors.
254 for (BasicBlock *Succ : successors(BB))
255 if (!TakeFoldCandidate || TheOnlySucc == Succ) {
256 if (L.contains(Succ))
257 LiveLoopBlocks.insert(Succ);
258 else
259 LiveExitBlocks.insert(Succ);
260 }
261 }
262
263 // Amount of dead and live loop blocks should match the total number of
264 // blocks in loop.
265 assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
266 "Malformed block sets?");
267
268 // Now, all exit blocks that are not marked as live are dead, if all their
269 // predecessors are in the loop. This may not be the case, as the input loop
270 // may not by in loop-simplify/canonical form.
271 SmallVector<BasicBlock *, 8> ExitBlocks;
272 L.getExitBlocks(ExitBlocks);
273 SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
274 for (auto *ExitBlock : ExitBlocks)
275 if (!LiveExitBlocks.count(ExitBlock) &&
276 UniqueDeadExits.insert(ExitBlock).second &&
277 all_of(predecessors(ExitBlock),
278 [this](BasicBlock *Pred) { return L.contains(Pred); }))
279 DeadExitBlocks.push_back(ExitBlock);
280
281 // Whether or not the edge From->To will still be present in graph after the
282 // folding.
283 auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
284 if (!LiveLoopBlocks.count(From))
285 return false;
286 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
287 return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
288 };
289
290 // The loop will not be destroyed if its latch is live.
291 DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
292
293 // If we are going to delete the current loop completely, no extra analysis
294 // is needed.
295 if (DeleteCurrentLoop)
296 return;
297
298 // Otherwise, we should check which blocks will still be a part of the
299 // current loop after the transform.
300 BlocksInLoopAfterFolding.insert(L.getLoopLatch());
301 // If the loop is live, then we should compute what blocks are still in
302 // loop after all branch folding has been done. A block is in loop if
303 // it has a live edge to another block that is in the loop; by definition,
304 // latch is in the loop.
305 auto BlockIsInLoop = [&](BasicBlock *BB) {
306 return any_of(successors(BB), [&](BasicBlock *Succ) {
307 return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
308 });
309 };
310 for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
311 BasicBlock *BB = *I;
312 if (BlockIsInLoop(BB))
313 BlocksInLoopAfterFolding.insert(BB);
314 }
315
316 assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
317 "Header not in loop?");
318 assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
319 "All blocks that stay in loop should be live!");
320 }
321
322 /// We need to preserve static reachibility of all loop exit blocks (this is)
323 /// required by loop pass manager. In order to do it, we make the following
324 /// trick:
325 ///
326 /// preheader:
327 /// <preheader code>
328 /// br label %loop_header
329 ///
330 /// loop_header:
331 /// ...
332 /// br i1 false, label %dead_exit, label %loop_block
333 /// ...
334 ///
335 /// We cannot simply remove edge from the loop to dead exit because in this
336 /// case dead_exit (and its successors) may become unreachable. To avoid that,
337 /// we insert the following fictive preheader:
338 ///
339 /// preheader:
340 /// <preheader code>
341 /// switch i32 0, label %preheader-split,
342 /// [i32 1, label %dead_exit_1],
343 /// [i32 2, label %dead_exit_2],
344 /// ...
345 /// [i32 N, label %dead_exit_N],
346 ///
347 /// preheader-split:
348 /// br label %loop_header
349 ///
350 /// loop_header:
351 /// ...
352 /// br i1 false, label %dead_exit_N, label %loop_block
353 /// ...
354 ///
355 /// Doing so, we preserve static reachibility of all dead exits and can later
356 /// remove edges from the loop to these blocks.
357 void handleDeadExits() {
358 // If no dead exits, nothing to do.
359 if (DeadExitBlocks.empty())
360 return;
361
362 // Construct split preheader and the dummy switch to thread edges from it to
363 // dead exits.
364 BasicBlock *Preheader = L.getLoopPreheader();
365 BasicBlock *NewPreheader = llvm::SplitBlock(
366 Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
367
368 IRBuilder<> Builder(Preheader->getTerminator());
369 SwitchInst *DummySwitch =
370 Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
371 Preheader->getTerminator()->eraseFromParent();
372
373 unsigned DummyIdx = 1;
374 for (BasicBlock *BB : DeadExitBlocks) {
375 // Eliminate all Phis and LandingPads from dead exits.
376 // TODO: Consider removing all instructions in this dead block.
377 SmallVector<Instruction *, 4> DeadInstructions(
379
380 if (auto *LandingPad = dyn_cast<LandingPadInst>(BB->getFirstNonPHIIt()))
381 DeadInstructions.emplace_back(LandingPad);
382
383 for (Instruction *I : DeadInstructions) {
384 SE.forgetValue(I);
385 I->replaceAllUsesWith(PoisonValue::get(I->getType()));
386 I->eraseFromParent();
387 }
388
389 assert(DummyIdx != 0 && "Too many dead exits!");
390 DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
391 DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
392 ++NumLoopExitsDeleted;
393 }
394 // We don't really need to add branch weights to DummySwitch, because all
395 // but one branches are just a temporary artifact - see the comment on top
396 // of this function. But, it's easy to estimate the weights, and it helps
397 // maintain a property of the overall compiler - that the branch weights
398 // don't "just get dropped" accidentally (i.e. profcheck)
399 if (DummySwitch->getParent()->getParent()->hasProfileData()) {
400 SmallVector<uint32_t> DummyBranchWeights(1 + DummySwitch->getNumCases());
401 // default. 100% probability, the rest are dead.
402 DummyBranchWeights[0] = 1;
403 setBranchWeights(*DummySwitch, DummyBranchWeights, /*IsExpected=*/false);
404 }
405
406 assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
407 if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
408 // When we break dead edges, the outer loop may become unreachable from
409 // the current loop. We need to fix loop info accordingly. For this, we
410 // find the most nested loop that still contains L and remove L from all
411 // loops that are inside of it.
412 Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
413
414 // Okay, our loop is no longer in the outer loop (and maybe not in some of
415 // its parents as well). Make the fixup.
416 if (StillReachable != OuterLoop) {
417 LI.changeLoopFor(NewPreheader, StillReachable);
418 removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
419 for (auto *BB : L.blocks())
420 removeBlockFromLoops(BB, OuterLoop, StillReachable);
421 OuterLoop->removeChildLoop(&L);
422 if (StillReachable)
423 StillReachable->addChildLoop(&L);
424 else
425 LI.addTopLevelLoop(&L);
426
427 // Some values from loops in [OuterLoop, StillReachable) could be used
428 // in the current loop. Now it is not their child anymore, so such uses
429 // require LCSSA Phis.
430 Loop *FixLCSSALoop = OuterLoop;
431 while (FixLCSSALoop->getParentLoop() != StillReachable)
432 FixLCSSALoop = FixLCSSALoop->getParentLoop();
433 assert(FixLCSSALoop && "Should be a loop!");
434 // We need all DT updates to be done before forming LCSSA.
435 if (MSSAU)
436 MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
437 else
438 DTU.applyUpdates(DTUpdates);
439 DTUpdates.clear();
440 formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
441 SE.forgetBlockAndLoopDispositions();
442 }
443 }
444
445 if (MSSAU) {
446 // Clear all updates now. Facilitates deletes that follow.
447 MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
448 DTUpdates.clear();
449 if (VerifyMemorySSA)
450 MSSAU->getMemorySSA()->verifyMemorySSA();
451 }
452 }
453
454 /// Delete loop blocks that have become unreachable after folding. Make all
455 /// relevant updates to DT and LI.
456 void deleteDeadLoopBlocks() {
457 if (MSSAU) {
458 SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
459 DeadLoopBlocks.end());
460 MSSAU->removeBlocks(DeadLoopBlocksSet);
461 }
462
463 // The function LI.erase has some invariants that need to be preserved when
464 // it tries to remove a loop which is not the top-level loop. In particular,
465 // it requires loop's preheader to be strictly in loop's parent. We cannot
466 // just remove blocks one by one, because after removal of preheader we may
467 // break this invariant for the dead loop. So we detatch and erase all dead
468 // loops beforehand.
469 for (auto *BB : DeadLoopBlocks)
470 if (LI.isLoopHeader(BB)) {
471 assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
472 Loop *DL = LI.getLoopFor(BB);
473 if (!DL->isOutermost()) {
474 for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
475 for (auto *BB : DL->getBlocks())
476 PL->removeBlockFromLoop(BB);
477 DL->getParentLoop()->removeChildLoop(DL);
478 LI.addTopLevelLoop(DL);
479 }
480 LI.erase(DL);
481 }
482
483 for (auto *BB : DeadLoopBlocks) {
484 assert(BB != L.getHeader() &&
485 "Header of the current loop cannot be dead!");
486 LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
487 << "\n");
488 LI.removeBlock(BB);
489 }
490
491 detachDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
492 DTU.applyUpdates(DTUpdates);
493 DTUpdates.clear();
494 for (auto *BB : DeadLoopBlocks)
495 DTU.deleteBB(BB);
496
497 NumLoopBlocksDeleted += DeadLoopBlocks.size();
498 }
499
500 /// Constant-fold terminators of blocks accumulated in FoldCandidates into the
501 /// unconditional branches.
502 void foldTerminators() {
503 for (BasicBlock *BB : FoldCandidates) {
504 assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
505 BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
506 assert(TheOnlySucc && "Should have one live successor!");
507
508 LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
509 << " with an unconditional branch to the block "
510 << TheOnlySucc->getName() << "\n");
511
512 SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
513 // Remove all BB's successors except for the live one.
514 unsigned TheOnlySuccDuplicates = 0;
515 for (auto *Succ : successors(BB))
516 if (Succ != TheOnlySucc) {
517 DeadSuccessors.insert(Succ);
518 // If our successor lies in a different loop, we don't want to remove
519 // the one-input Phi because it is a LCSSA Phi.
520 bool PreserveLCSSAPhi = !L.contains(Succ);
521 Succ->removePredecessor(BB, PreserveLCSSAPhi);
522 if (MSSAU)
523 MSSAU->removeEdge(BB, Succ);
524 } else
525 ++TheOnlySuccDuplicates;
526
527 assert(TheOnlySuccDuplicates > 0 && "Should be!");
528 // If TheOnlySucc was BB's successor more than once, after transform it
529 // will be its successor only once. Remove redundant inputs from
530 // TheOnlySucc's Phis.
531 bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
532 for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
533 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
534 if (MSSAU && TheOnlySuccDuplicates > 1)
535 MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
536
538 IRBuilder<> Builder(Term);
539 Builder.CreateBr(TheOnlySucc);
540 Term->eraseFromParent();
541
542 for (auto *DeadSucc : DeadSuccessors)
543 DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
544
545 ++NumTerminatorsFolded;
546 }
547 }
548
549public:
550 ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
551 ScalarEvolution &SE,
552 MemorySSAUpdater *MSSAU)
553 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
554 DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
555 bool run() {
556 assert(L.getLoopLatch() && "Should be single latch!");
557
558 // Collect all available information about status of blocks after constant
559 // folding.
560 analyze();
561 BasicBlock *Header = L.getHeader();
562 (void)Header;
563
564 LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
565 << ": ");
566
567 if (HasIrreducibleCFG) {
568 LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
569 return false;
570 }
571
572 if (HasIndirectEntry) {
573 LLVM_DEBUG(dbgs() << "Loops which can be entered indirectly are not"
574 " supported!\n");
575 return false;
576 }
577
578 // Nothing to constant-fold.
579 if (FoldCandidates.empty()) {
581 dbgs() << "No constant terminator folding candidates found in loop "
582 << Header->getName() << "\n");
583 return false;
584 }
585
586 // TODO: Support deletion of the current loop.
587 if (DeleteCurrentLoop) {
589 dbgs()
590 << "Give up constant terminator folding in loop " << Header->getName()
591 << ": we don't currently support deletion of the current loop.\n");
592 return false;
593 }
594
595 // TODO: Support blocks that are not dead, but also not in loop after the
596 // folding.
597 if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
598 L.getNumBlocks()) {
600 dbgs() << "Give up constant terminator folding in loop "
601 << Header->getName() << ": we don't currently"
602 " support blocks that are not dead, but will stop "
603 "being a part of the loop after constant-folding.\n");
604 return false;
605 }
606
607 // TODO: Tokens may breach LCSSA form by default. However, the transform for
608 // dead exit blocks requires LCSSA form to be maintained for all values,
609 // tokens included, otherwise it may break use-def dominance (see PR56243).
610 if (!DeadExitBlocks.empty() && !L.isLCSSAForm(DT, /*IgnoreTokens*/ false)) {
611 assert(L.isLCSSAForm(DT, /*IgnoreTokens*/ true) &&
612 "LCSSA broken not by tokens?");
613 LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "
614 << Header->getName()
615 << ": tokens uses potentially break LCSSA form.\n");
616 return false;
617 }
618
619 SE.forgetTopmostLoop(&L);
620 // Dump analysis results.
621 LLVM_DEBUG(dump());
622
623 LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
624 << " terminators in loop " << Header->getName() << "\n");
625
626 if (!DeadLoopBlocks.empty())
627 SE.forgetBlockAndLoopDispositions();
628
629 // Make the actual transforms.
630 handleDeadExits();
631 foldTerminators();
632
633 if (!DeadLoopBlocks.empty()) {
634 LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
635 << " dead blocks in loop " << Header->getName() << "\n");
636 deleteDeadLoopBlocks();
637 } else {
638 // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
639 DTU.applyUpdates(DTUpdates);
640 DTUpdates.clear();
641 }
642
643 if (MSSAU && VerifyMemorySSA)
644 MSSAU->getMemorySSA()->verifyMemorySSA();
645
646#ifndef NDEBUG
647 // Make sure that we have preserved all data structures after the transform.
648#if defined(EXPENSIVE_CHECKS)
649 assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
650 "DT broken after transform!");
651#else
652 assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
653 "DT broken after transform!");
654#endif
655 assert(DT.isReachableFromEntry(Header));
656 LI.verify();
657#endif
658
659 return true;
660 }
661
662 bool foldingBreaksCurrentLoop() const {
663 return DeleteCurrentLoop;
664 }
665};
666} // namespace
667
668/// Turn branches and switches with known constant conditions into unconditional
669/// branches.
671 ScalarEvolution &SE,
672 MemorySSAUpdater *MSSAU,
673 bool &IsLoopDeleted) {
675 return false;
676
677 // To keep things simple, only process loops with single latch. We
678 // canonicalize most loops to this form. We can support multi-latch if needed.
679 if (!L.getLoopLatch())
680 return false;
681
682 ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
683 bool Changed = BranchFolder.run();
684 IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
685 return Changed;
686}
687
689 LoopInfo &LI, MemorySSAUpdater *MSSAU,
690 ScalarEvolution &SE) {
691 bool Changed = false;
692 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
693 // Copy blocks into a temporary array to avoid iterator invalidation issues
694 // as we remove them.
695 SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
696
697 for (auto &Block : Blocks) {
698 // Attempt to merge blocks in the trivial case. Don't modify blocks which
699 // belong to other loops.
701 if (!Succ)
702 continue;
703
704 BasicBlock *Pred = Succ->getSinglePredecessor();
705 if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
706 continue;
707
708 // Merge Succ into Pred and delete it.
709 MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
710
711 if (MSSAU && VerifyMemorySSA)
712 MSSAU->getMemorySSA()->verifyMemorySSA();
713
714 Changed = true;
715 }
716
717 if (Changed)
719
720 return Changed;
721}
722
725 bool &IsLoopDeleted) {
726 bool Changed = false;
727
728 // Constant-fold terminators with known constant conditions.
729 Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);
730
731 if (IsLoopDeleted)
732 return true;
733
734 // Eliminate unconditional branches by merging blocks into their predecessors.
735 Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU, SE);
736
737 if (Changed)
738 SE.forgetTopmostLoop(&L);
739
740 return Changed;
741}
742
745 LPMUpdater &LPMU) {
746 std::optional<MemorySSAUpdater> MSSAU;
747 if (AR.MSSA)
748 MSSAU = MemorySSAUpdater(AR.MSSA);
749 bool DeleteCurrentLoop = false;
750 if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE, MSSAU ? &*MSSAU : nullptr,
751 DeleteCurrentLoop))
752 return PreservedAnalyses::all();
753
754 if (DeleteCurrentLoop)
755 LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
756
758 if (AR.MSSA)
759 PA.preserve<MemorySSAAnalysis>();
760 return PA;
761}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
static BasicBlock * getOnlyLiveSuccessor(BasicBlock *BB)
If BB is a switch or a conditional branch, but only one of its successors can be reached from this bl...
static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE, MemorySSAUpdater *MSSAU, bool &IsLoopDeleted)
Turn branches and switches with known constant conditions into unconditional branches.
static Loop * getInnermostLoopFor(SmallPtrSetImpl< BasicBlock * > &BBs, Loop &L, LoopInfo &LI)
Find innermost loop that contains at least one block from BBs and contains the header of loop L.
static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU, ScalarEvolution &SE)
static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE, MemorySSAUpdater *MSSAU, bool &IsLoopDeleted)
static cl::opt< bool > EnableTermFolding("enable-loop-simplifycfg-term-folding", cl::init(true))
static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop, Loop *LastLoop=nullptr)
Removes BB from all loops from [FirstLoop, LastLoop) in parent chain.
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:515
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Conditional Branch instruction.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within this loop.
BlockT * getHeader() const
unsigned getLoopDepth() const
Return the nesting level of this loop.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
LoopT * getParentLoop() const
Return the parent loop if it exists or nullptr for top level loops.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:922
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
LLVM_ABI void verifyMemorySSA(VerificationLevel=VerificationLevel::Fast) const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
The main scalar evolution driver.
LLVM_ABI void forgetTopmostLoop(const Loop *L)
LLVM_ABI void forgetBlockAndLoopDispositions(Value *V=nullptr)
Called when the client has changed the disposition of values in a loop or block.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Multiway switch.
LLVM_ABI void addCase(ConstantInt *OnVal, BasicBlock *Dest)
Add an entry to the switch instruction.
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
const ParentTy * getParent() const
Definition ilist_node.h:34
Changed
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
initializer< Ty > init(const Ty &Val)
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI void detachDeadBlocks(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool formLCSSARecursively(Loop &L, const DominatorTree &DT, const LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition LCSSA.cpp:469
auto cast_or_null(const Y &Val)
Definition Casting.h:714
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
IRBuilder(LLVMContext &, FolderTy, InserterTy) -> IRBuilder< FolderTy, InserterTy >
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:85
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
Definition iterator.h:368
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...