Skip to content

[FixIrreducible][UnifyLoopExits] Support switch statements - #206567

Merged
ro-i merged 5 commits into
llvm:mainfrom
hertelukas:fix-irreducible-switches
Jul 20, 2026
Merged

ro-i merged 5 commits into
llvm:mainfrom
hertelukas:fix-irreducible-switches

Conversation

@hertelukas

Copy link
Copy Markdown
Contributor

This builds on #149308, which implemented callbr support.

The same approach of splitting multi-branch edges entering irreducible loops can be used for switches. It does not introduce any new switch statements, but alleviates the requirement of having to run the LowerSwitch pass first. This makes the pass usable for users other than AMDGPU, which can handle switch statements (e.g., WebAssembly, see here).

I'm also implementing a flag into the ControlFlowHub to support switches as well, for which I will open a separate PR. Currently the ControlFlowHub creates a branch-sled, mimicking a switch (a series of blocks consisting only of conditional branches, selectively entering an irreducible loop at a certain point or continuing to the next potential entry point). If the target can support switches, that should be the clear goal here, as shown in the image below. This PR implements the step from (a) to (b), whereas extending the ControlFlowHub represents the step from (b) to (c). ((c) to (d) already exists through SwitchToLookup and SwitchToArithmetic).

image

The test cases in switch.ll were adapted from the callbr.ll tests using an LLM to ensure equivalent coverage. I've manually reviewed the control flow and conditions for every case, and the final assertions were generated using update_test_checks.py.

@github-actions

Copy link
Copy Markdown

Hello @hertelukas 👋

Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.

  • All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
  • The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
  • Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.

Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.


Frequently asked questions

How do I add reviewers?

This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.

You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.

What if there are no comments?

If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.

Are any special GitHub settings required to contribute to LLVM?

We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.


If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.

Thank you,
The LLVM Community

@llvmorg-github-actions

Copy link
Copy Markdown

@llvm/pr-subscribers-llvm-transforms

Author: Lukas (hertelukas)

Changes

This builds on #149308, which implemented callbr support.

The same approach of splitting multi-branch edges entering irreducible loops can be used for switches. It does not introduce any new switch statements, but alleviates the requirement of having to run the LowerSwitch pass first. This makes the pass usable for users other than AMDGPU, which can handle switch statements (e.g., WebAssembly, see here).

I'm also implementing a flag into the ControlFlowHub to support switches as well, for which I will open a separate PR. Currently the ControlFlowHub creates a branch-sled, mimicking a switch (a series of blocks consisting only of conditional branches, selectively entering an irreducible loop at a certain point or continuing to the next potential entry point). If the target can support switches, that should be the clear goal here, as shown in the image below. This PR implements the step from (a) to (b), whereas extending the ControlFlowHub represents the step from (b) to (c). ((c) to (d) already exists through SwitchToLookup and SwitchToArithmetic).

<img width="1055" height="432" alt="image" src="https://github.com/user-attachments/assets/780b7894-1895-4137-8148-b2bbc7f73a8f" />

The test cases in switch.ll were adapted from the callbr.ll tests using an LLM to ensure equivalent coverage. I've manually reviewed the control flow and conditions for every case, and the final assertions were generated using update_test_checks.py.


Patch is 57.96 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/206567.diff

6 Files Affected:

  • (modified) llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h (+11-12)
  • (modified) llvm/lib/Transforms/Utils/BasicBlockUtils.cpp (+27-27)
  • (modified) llvm/lib/Transforms/Utils/FixIrreducible.cpp (+29-23)
  • (modified) llvm/lib/Transforms/Utils/UnifyLoopExits.cpp (+21-17)
  • (modified) llvm/test/Transforms/FixIrreducible/switch.ll (+933-27)
  • (modified) llvm/test/Transforms/FixIrreducible/unsupported-terminator.ll (+11-14)
diff --git a/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h b/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h
index f9bfff09673f0..abf19177bd7da 100644
--- a/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h
+++ b/llvm/include/llvm/Transforms/Utils/BasicBlockUtils.h
@@ -267,18 +267,17 @@ LLVM_ABI BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
                                MemorySSAUpdater *MSSAU = nullptr,
                                const Twine &BBName = "");
 
-/// \brief Create a new intermediate target block for a callbr edge.
+/// \brief Create a new intermediate target block for a callbr and switch edges.
 ///
-/// Create a new basic block between a callbr instruction and one of its
-/// successors. The new block replaces the original successor in the callbr
-/// instruction and unconditionally branches to the original successor. This
-/// is useful for normalizing control flow, e.g., when transforming
-/// irreducible loops.
+/// Create a new basic block between a callbr or switch instruction and one of
+/// its successors. The new block replaces the original successor in the
+/// callbr/switch instruction and unconditionally branches to the original
+/// successor. This is useful for normalizing control flow, e.g., when
+/// transforming irreducible loops.
 ///
-/// \param CallBrBlock    block containing the callbr instruction
+/// \param MultiBrBlock   block containing the callbr or switch instruction
 /// \param Succ           original successor block
-/// \param SuccIdx        index of the original successor in the callbr
-///                       instruction
+/// \param SuccIdx        index of the original successor in the terminator
 /// \param DTU            optional \p DomTreeUpdater for updating the
 ///                       dominator tree
 /// \param CI             optional \p CycleInfo for updating cycle membership
@@ -291,9 +290,9 @@ LLVM_ABI BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To,
 /// \note This function updates PHI nodes, dominator tree, loop info, and
 /// cycle info as needed.
 LLVM_ABI BasicBlock *
-SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ, unsigned SuccIdx,
-                DomTreeUpdater *DTU = nullptr, CycleInfo *CI = nullptr,
-                LoopInfo *LI = nullptr, bool *UpdatedLI = nullptr);
+SplitMultiBrEdge(BasicBlock *MultiBrBlock, BasicBlock *Succ, unsigned SuccIdx,
+                 DomTreeUpdater *DTU = nullptr, CycleInfo *CI = nullptr,
+                 LoopInfo *LI = nullptr, bool *UpdatedLI = nullptr);
 
 /// Sets the unwind edge of an instruction to a particular successor.
 LLVM_ABI void setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ);
diff --git a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
index 425faf57f8b63..fbc0ba71b37de 100644
--- a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
+++ b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp
@@ -725,47 +725,47 @@ static bool updateCycleLoopInfo(TI *LCI, BasicBlock *CallBrBlock,
   return true;
 }
 
-BasicBlock *llvm::SplitCallBrEdge(BasicBlock *CallBrBlock, BasicBlock *Succ,
-                                  unsigned SuccIdx, DomTreeUpdater *DTU,
-                                  CycleInfo *CI, LoopInfo *LI,
-                                  bool *UpdatedLI) {
-  CallBrInst *CallBr = dyn_cast<CallBrInst>(CallBrBlock->getTerminator());
-  assert(CallBr && "expected callbr terminator");
-  assert(SuccIdx < CallBr->getNumSuccessors() &&
-         Succ == CallBr->getSuccessor(SuccIdx) && "invalid successor index");
-
-  // Create a new block between callbr and the specified successor.
+BasicBlock *llvm::SplitMultiBrEdge(BasicBlock *MultiBrBlock, BasicBlock *Succ,
+                                   unsigned SuccIdx, DomTreeUpdater *DTU,
+                                   CycleInfo *CI, LoopInfo *LI,
+                                   bool *UpdatedLI) {
+  Instruction *Term = MultiBrBlock->getTerminator();
+  assert(Term && "expected terminator");
+  assert(SuccIdx < Term->getNumSuccessors() &&
+         Succ == Term->getSuccessor(SuccIdx) && "invalid successor index");
+
+  // Create a new block between terminator and the specified successor.
   // splitBlockBefore cannot be re-used here since it cannot split if the split
   // point is a PHI node (because BasicBlock::splitBasicBlockBefore cannot
   // handle that). But we don't need to rewire every part of a potential PHI
-  // node. We only care about the edge between CallBrBlock and the original
+  // node. We only care about the edge between MultiBrBlock and the original
   // successor.
-  BasicBlock *CallBrTarget =
-      BasicBlock::Create(CallBrBlock->getContext(),
-                         CallBrBlock->getName() + ".target." + Succ->getName(),
-                         CallBrBlock->getParent());
+  BasicBlock *BrTarget =
+      BasicBlock::Create(MultiBrBlock->getContext(),
+                         MultiBrBlock->getName() + ".target." + Succ->getName(),
+                         MultiBrBlock->getParent());
   // Rewire control flow from the new target block to the original successor.
-  Succ->replacePhiUsesWith(CallBrBlock, CallBrTarget);
-  // Rewire control flow from callbr to the new target block.
-  CallBr->setSuccessor(SuccIdx, CallBrTarget);
+  Succ->replacePhiUsesWith(MultiBrBlock, BrTarget);
+  // Rewire control flow from the MultiBrBlock to the new target block.
+  Term->setSuccessor(SuccIdx, BrTarget);
   // Jump from the new target block to the original successor.
-  UncondBrInst::Create(Succ, CallBrTarget);
+  UncondBrInst::Create(Succ, BrTarget);
 
   bool Updated =
-      updateCycleLoopInfo<LoopInfo, Loop>(LI, CallBrBlock, CallBrTarget, Succ);
+      updateCycleLoopInfo<LoopInfo, Loop>(LI, MultiBrBlock, BrTarget, Succ);
   if (UpdatedLI)
     *UpdatedLI = Updated;
-  updateCycleLoopInfo<CycleInfo, Cycle>(CI, CallBrBlock, CallBrTarget, Succ);
+  updateCycleLoopInfo<CycleInfo, Cycle>(CI, MultiBrBlock, BrTarget, Succ);
   if (DTU) {
-    DTU->applyUpdates({{DominatorTree::Insert, CallBrBlock, CallBrTarget}});
-    if (DTU->getDomTree().dominates(CallBrBlock, Succ)) {
-      if (!is_contained(successors(CallBrBlock), Succ))
-        DTU->applyUpdates({{DominatorTree::Delete, CallBrBlock, Succ}});
-      DTU->applyUpdates({{DominatorTree::Insert, CallBrTarget, Succ}});
+    DTU->applyUpdates({{DominatorTree::Insert, MultiBrBlock, BrTarget}});
+    if (DTU->getDomTree().dominates(MultiBrBlock, Succ)) {
+      if (!is_contained(successors(MultiBrBlock), Succ))
+        DTU->applyUpdates({{DominatorTree::Delete, MultiBrBlock, Succ}});
+      DTU->applyUpdates({{DominatorTree::Insert, BrTarget, Succ}});
     }
   }
 
-  return CallBrTarget;
+  return BrTarget;
 }
 
 void llvm::setUnwindEdgeTo(Instruction *TI, BasicBlock *Succ) {
diff --git a/llvm/lib/Transforms/Utils/FixIrreducible.cpp b/llvm/lib/Transforms/Utils/FixIrreducible.cpp
index ead39f5991081..3b445492dc564 100644
--- a/llvm/lib/Transforms/Utils/FixIrreducible.cpp
+++ b/llvm/lib/Transforms/Utils/FixIrreducible.cpp
@@ -76,16 +76,15 @@
 // a PHINode in a header. Hence the above handling of PHINodes is sufficient and
 // no further processing is required to restore SSA.
 //
-// Limitation: The pass cannot handle switch statements and indirect
-//             branches. Both must be lowered to plain branches first.
+// Limitation: The pass cannot handle indirect branches. They must be lowered to
+//             plain branches first.
 //
-// CallBr support: CallBr is handled as a more general branch instruction which
-// can have multiple successors. The pass redirects the edges to intermediate
-// target blocks that unconditionally branch to the original callbr target
-// blocks. This allows the control flow hub to know to which of the original
-// target blocks to jump to.
-// Example input CFG:
-//                        Entry (callbr)
+// CallBr and Switch support: CallBr and Switch terminators are handled as a
+// more general branch instruction which can have multiple successors. The pass
+// redirects the edges to intermediate target blocks that unconditionally branch
+// to the original target blocks. This allows the control flow hub to know to
+// which of the original target blocks to jump to. Example input CFG:
+//                        Entry (callbr/switch)
 //                       /     \
 //                      v       v
 //                      H ----> B
@@ -95,7 +94,7 @@
 //                             Exit
 //
 // becomes:
-//                        Entry (callbr)
+//                        Entry (callbr/switch)
 //                       /     \
 //                      v       v
 //                 target.H   target.B
@@ -110,7 +109,7 @@
 // Note
 // OUTPUT CFG: Converted to a natural loop with a new header N.
 //
-//                        Entry (callbr)
+//                        Entry (callbr/switch)
 //                       /     \
 //                      v       v
 //                 target.H   target.B
@@ -132,6 +131,7 @@
 #include "llvm/Analysis/CycleAnalysis.h"
 #include "llvm/Analysis/DomTreeUpdater.h"
 #include "llvm/Analysis/LoopInfo.h"
+#include "llvm/IR/Instructions.h"
 #include "llvm/InitializePasses.h"
 #include "llvm/Pass.h"
 #include "llvm/Support/ErrorHandling.h"
@@ -309,20 +309,23 @@ static bool fixIrreducible(Cycle &C, CycleInfo &CI, DominatorTree &DT,
                         << " -> " << printBasicBlock(Succ0)
                         << (Succ0 && Succ1 ? " " : "") << printBasicBlock(Succ1)
                         << '\n');
-    } else if (CallBrInst *CallBr = dyn_cast<CallBrInst>(P->getTerminator())) {
-      for (unsigned I = 0; I < CallBr->getNumSuccessors(); ++I) {
-        BasicBlock *Succ = CallBr->getSuccessor(I);
+    } else if (isa<CallBrInst>(P->getTerminator()) ||
+               isa<SwitchInst>(P->getTerminator())) {
+      Instruction *Term = P->getTerminator();
+      for (unsigned I = 0; I < Term->getNumSuccessors(); ++I) {
+        BasicBlock *Succ = Term->getSuccessor(I);
         if (Succ != Header)
           continue;
-        BasicBlock *NewSucc = SplitCallBrEdge(P, Succ, I, &DTU, &CI, LI);
+        BasicBlock *NewSucc = SplitMultiBrEdge(P, Succ, I, &DTU, &CI, LI);
         CHub.addBranch(NewSucc, Succ);
         LLVM_DEBUG(dbgs() << "Added internal branch: "
                           << printBasicBlock(NewSucc) << " -> "
                           << printBasicBlock(Succ) << '\n');
       }
     } else {
-      reportFatalUsageError("unsupported block terminator: fix-irreducible "
-                            "only supports br and callbr instructions");
+      reportFatalUsageError(
+          "unsupported block terminator: fix-irreducible "
+          "only supports br, callbr, and switch instructions");
     }
   }
 
@@ -354,20 +357,23 @@ static bool fixIrreducible(Cycle &C, CycleInfo &CI, DominatorTree &DT,
                         << " -> " << printBasicBlock(Succ0)
                         << (Succ0 && Succ1 ? " " : "") << printBasicBlock(Succ1)
                         << '\n');
-    } else if (CallBrInst *CallBr = dyn_cast<CallBrInst>(P->getTerminator())) {
-      for (unsigned I = 0; I < CallBr->getNumSuccessors(); ++I) {
-        BasicBlock *Succ = CallBr->getSuccessor(I);
+    } else if (isa<CallBrInst>(P->getTerminator()) ||
+               isa<SwitchInst>(P->getTerminator())) {
+      Instruction *Term = P->getTerminator();
+      for (unsigned I = 0; I < Term->getNumSuccessors(); ++I) {
+        BasicBlock *Succ = Term->getSuccessor(I);
         if (!C.contains(Succ))
           continue;
-        BasicBlock *NewSucc = SplitCallBrEdge(P, Succ, I, &DTU, &CI, LI);
+        BasicBlock *NewSucc = SplitMultiBrEdge(P, Succ, I, &DTU, &CI, LI);
         CHub.addBranch(NewSucc, Succ);
         LLVM_DEBUG(dbgs() << "Added external branch: "
                           << printBasicBlock(NewSucc) << " -> "
                           << printBasicBlock(Succ) << '\n');
       }
     } else {
-      reportFatalUsageError("unsupported block terminator: fix-irreducible "
-                            "only supports br and callbr instructions");
+      reportFatalUsageError(
+          "unsupported block terminator: fix-irreducible "
+          "only supports br, callbr, and switch instructions");
     }
   }
 
diff --git a/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp b/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp
index 6947cb4f92723..657f407c020a5 100644
--- a/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp
+++ b/llvm/lib/Transforms/Utils/UnifyLoopExits.cpp
@@ -13,10 +13,10 @@
 // Limitation: This assumes that all terminators in the CFG are direct branches
 //             (the "br" instruction). The presence of any other control flow
 //             such as indirectbr or switch will cause an assert.
-//             The callbr terminator is supported by creating intermediate
-//             target blocks that unconditionally branch to the original target
-//             blocks. These intermediate target blocks can then be redirected
-//             through the ControlFlowHub as usual.
+//             The callbr and switch terminators are supported by creating
+//             intermediate target blocks that unconditionally branch to the
+//             original target blocks. These intermediate target blocks can then
+//             be redirected through the ControlFlowHub as usual.
 //
 //===----------------------------------------------------------------------===//
 
@@ -26,6 +26,7 @@
 #include "llvm/Analysis/LoopInfo.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/Dominators.h"
+#include "llvm/IR/Instructions.h"
 #include "llvm/InitializePasses.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Transforms/Utils.h"
@@ -159,7 +160,7 @@ static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) {
     return false;
 
   DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
-  SmallVector<BasicBlock *, 8> CallBrTargetBlocksToFix;
+  SmallVector<BasicBlock *, 8> MultiBrTargetBlocksToFix;
 
   // Redirect exiting edges through a control flow hub.
   ControlFlowHub CHub;
@@ -186,27 +187,30 @@ static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) {
                         << " -> " << printBasicBlock(Succ0)
                         << (Succ0 && Succ1 ? " " : "") << printBasicBlock(Succ1)
                         << '\n');
-    } else if (CallBrInst *CallBr = dyn_cast<CallBrInst>(BB->getTerminator())) {
-      for (unsigned J = 0; J < CallBr->getNumSuccessors(); ++J) {
-        BasicBlock *Succ = CallBr->getSuccessor(J);
+    } else if (isa<CallBrInst>(BB->getTerminator()) ||
+               isa<SwitchInst>(BB->getTerminator())) {
+      Instruction *Term = BB->getTerminator();
+      for (unsigned J = 0; J < Term->getNumSuccessors(); ++J) {
+        BasicBlock *Succ = Term->getSuccessor(J);
         if (L->contains(Succ))
           continue;
         bool UpdatedLI = false;
         BasicBlock *NewSucc =
-            SplitCallBrEdge(BB, Succ, J, &DTU, nullptr, &LI, &UpdatedLI);
-        // SplitCallBrEdge modifies the CFG because it creates an intermediate
+            SplitMultiBrEdge(BB, Succ, J, &DTU, nullptr, &LI, &UpdatedLI);
+        // SplitMultiBrEdge modifies the CFG because it creates an intermediate
         // block. So we need to set the changed flag no matter what the
         // ControlFlowHub is going to do later.
         Changed = true;
-        // Even if CallBr and Succ do not have a common parent loop, we need to
-        // add the new target block to the parent loop of the current loop.
+        // Even if the terminator and Succ do not have a common parent loop, we
+        // need to add the new target block to the parent loop of the current
+        // loop.
         if (!UpdatedLI)
-          CallBrTargetBlocksToFix.push_back(NewSucc);
+          MultiBrTargetBlocksToFix.push_back(NewSucc);
         // ExitingBlocks is later used to restore SSA, so we need to make sure
         // that the blocks used for phi nodes in the guard blocks match the
-        // predecessors of the guard blocks, which, in the case of callbr, are
-        // the new intermediate target blocks instead of the callbr blocks
-        // themselves.
+        // predecessors of the guard blocks, which, in the case of a callbr or
+        // switch terminator, are the new intermediate target blocks instead of
+        // the blocks themselves.
         ExitingBlocks[I] = NewSucc;
         CHub.addBranch(NewSucc, Succ);
         LLVM_DEBUG(dbgs() << "Added exiting branch: "
@@ -248,7 +252,7 @@ static bool unifyLoopExits(DominatorTree &DT, LoopInfo &LI, Loop *L) {
     for (auto *G : GuardBlocks) {
       ParentLoop->addBasicBlockToLoop(G, LI);
     }
-    for (auto *C : CallBrTargetBlocksToFix) {
+    for (auto *C : MultiBrTargetBlocksToFix) {
       ParentLoop->addBasicBlockToLoop(C, LI);
     }
     ParentLoop->verifyLoop();
diff --git a/llvm/test/Transforms/FixIrreducible/switch.ll b/llvm/test/Transforms/FixIrreducible/switch.ll
index 4d3d9498b284d..0da0a0d28735c 100644
--- a/llvm/test/Transforms/FixIrreducible/switch.ll
+++ b/llvm/test/Transforms/FixIrreducible/switch.ll
@@ -1,31 +1,145 @@
-; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
-; RUN: opt < %s -lowerswitch -fix-irreducible --verify-loop-info -S | FileCheck %s
-; RUN: opt < %s -passes='lower-switch,fix-irreducible,verify<loops>' -S | FileCheck %s
-; RUN: opt < %s -passes='lower-switch,verify<loops>,fix-irreducible,verify<loops>' -S | FileCheck %s
-
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 5
+; RUN: opt < %s -passes='fix-irreducible,verify<loops>' -S | FileCheck %s
+; RUN: opt < %s -passes='verify<loops>,fix-irreducible,verify<loops>' -S | FileCheck %s
+; RUN: opt < %s -passes='print<cycles>' -disable-output 2>&1 | FileCheck %s --check-prefix CYCLES-BEFORE
+; RUN: opt < %s -passes='fix-irreducible,print<cycles>' -disable-output 2>&1 | FileCheck %s --check-prefix CYCLES-AFTER
+; CYCLES-BEFORE:      CycleInfo for function: loop_1
+; CYCLES-BEFORE-NEXT:    depth=1: entries(B A)
+; CYCLES-AFTER:       CycleInfo for function: loop_1
+; CYCLES-AFTER-NEXT:     depth=1: entries(irr.guard) B A B.target.B
+;
+; CYCLES-BEFORE-NEXT: CycleInfo for function: switch_entry
+; CYCLES-BEFORE-NEXT:    depth=1: entries(indirect fallthrough)
+; CYCLES-AFTER-NEXT:  CycleInfo for function: switch_entry
+; CYCLES-AFTER-NEXT:     depth=1: entries(irr.guard) indirect fallthrough
+;
+; CYCLES-BEFORE-NEXT: CycleInfo for function: switch_entry_targets_with_phi_nodes
+; CYCLES-BEFORE-NEXT:    depth=1: entries(block1 block)
+; CYCLES-AFTER-NEXT:  CycleInfo for function: switch_entry_targets_with_phi_nodes
+; CYCLES-AFTER-NEXT:     depth=1: entries(irr.guard) block1 block
+;
+; CYCLES-BEFORE-NEXT: CycleInfo for function: switch_entry_multiple_targets
+; CYCLES-BEFORE-NEXT:    depth=1: entries(indirect fallthrough)
+; CYCLES-AFTER-NEXT:  CycleInfo for function: switch_entry_multiple_targets
+; CYCLES-AFTER-NEXT:     depth=1: entries(irr.guard) indirect fallthrough
+;
+; CYCLES-BEFORE-NEXT: CycleInfo for function: switch_entry_multiple_targets1
+; CYCLES-BEFORE-NEXT:    depth=1: entries(indirect1 indirect fallthrough)
+; CYCLES-BEFORE-NEXT:        depth=2: entries(indirect fallthrough)
+; CYCLES-AFTER-NEXT:  CycleInfo for function: switch_entry_multiple_targets1
+; CYCLES-AFTER-NEXT:     depth=1: entries(irr.guard) indirect1 indirect fallthrough irr.guard1 irr.guard2
+; CYCLES-AFTER-NEXT:         depth=2: entries(irr.guard2) indirect fallthrough
+;
+; CYCLES-BEFORE-NEXT: CycleInfo for function: switch_header_no_indirect
+; CYCLES-BEFORE-NEXT:    depth=1: entries(fallthrough switch_bb)
+; CYCLES-AFTER-NEXT:  CycleInfo for function: switch_header_no_indirect
+; CYCLES-AFTER-NEXT:     depth=1: entries(irr.guard) fallthrough switch_bb switch_bb.target.fallthrough
+;
+; CYCLES-BEFORE-NEXT: CycleInfo for function: switch_header
+; CYCLES-BEFORE-NEXT:    depth=1: entries(fallthrough switch_bb)
+; CYCLES-AFTER-NEXT:  CycleInfo for function: switch_header
+; CYCLES-AFTER-NEXT:     depth=1: entries(irr.guard) fallthrough switch_bb switch_bb.target.fallthrough
+;
+; CYCLES-BEFORE-NEXT: CycleInfo for function: switch_header_multiple_targets
+; CYCLES-BEFORE-NEXT:    depth=1: entries(fallthrough switch_bb) indirect1
+; CYCLES-BEFORE-NEXT:        depth=2: entries(switch_bb) i...
[truncated]

@aengelke
aengelke requested a review from ro-i June 29, 2026 19:22

@ro-i ro-i left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work. I left some first comments about stuff I noticed.
Since you're also covering UnifyLoopExits, you should mention that in the PR title and especially also adapt the existing test + add new ones

// predecessors of the guard blocks, which, in the case of a callbr or
// switch terminator, are the new intermediate target blocks instead of
// the blocks themselves.
ExitingBlocks[I] = NewSucc;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if this is an issue, a bit like what we had in FixIrreducible (which is fixed by the PR I linked). Again, probably more for switch than for callbr, which is used rather restrictively

@hertelukas hertelukas changed the title [FixIrreducible] Support switch statements [FixIrreducible][UnifyLoopExits] Support switch statements Jun 30, 2026
ro-i pushed a commit that referenced this pull request Jul 12, 2026
)

This fixes a bug where splitting `callbr` multiedges corrupts the
successor's PHI nodes.

Originally, the first split edge would replace all incoming edges from
the `callbr` block with the newly introduced target block by using
`replacePhiUsesWith`. Later edges would create new target blocks and
would try to update their edge's PHI as well, but would not find it,
leading to a corrupted PHI node.

To fix this, it is theoretically only necessary to ensure that exactly
one PHI argument is replaced per split edge. However, as all the PHI
nodes must have the same argument for every edge from one predecessor, a
single target block suffices, through which all traffic can be routed,
which will be especially useful for switches, where multiedges are
common.

[Trunk crashing](https://godbolt.org/z/4MM5eMrW5)

Found while working on PR #206567, cc @ro-i.
@hertelukas
hertelukas force-pushed the fix-irreducible-switches branch from ab0ee81 to 265ce1d Compare July 12, 2026 18:19
@github-actions

github-actions Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

🐧 Linux x64 Test Results

  • 200526 tests passed
  • 5455 tests skipped

✅ The build succeeded and all tests passed.

@github-actions

github-actions Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

🪟 Windows x64 Test Results

  • 138684 tests passed
  • 3564 tests skipped

✅ The build succeeded and all tests passed.

@ro-i ro-i left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few (tiny) nits, but overall, this looks good

// SplitCallBrEdge modifies the CFG because it creates an intermediate
// block. So we need to set the changed flag no matter what the
// ControlFlowHub is going to do later.
// SplitMutliBrEdge modifies the CFG because it creates an

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// SplitMutliBrEdge modifies the CFG because it creates an
// SplitMultiBrEdge modifies the CFG because it creates an

// predecessors of the guard blocks, which, in the case of callbr or
// switch terminator, are the new intermediate target blocks instead
// of themselves. If only one exiting block is generated, the
// branchning block itself is overwritten, while further blocks are

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// branchning block itself is overwritten, while further blocks are
// branching block itself is overwritten, while further blocks are

assert(BBIdx != -1 && "expected incoming value form callbr block");
PN.setIncomingBlock(BBIdx, CallBrTarget);
int BBIdx = PN.getBasicBlockIndex(MultiBrBlock);
assert(BBIdx != -1 && "expected incoming value form MultiBrBlock");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
assert(BBIdx != -1 && "expected incoming value form MultiBrBlock");
assert(BBIdx != -1 && "expected incoming value from MultiBrBlock");

<< (Succ0 && Succ1 ? " " : "") << printBasicBlock(Succ1)
<< '\n');
} else if (CallBrInst *CallBr = dyn_cast<CallBrInst>(P->getTerminator())) {
} else if (isa<CallBrInst>(P->getTerminator()) ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could get the terminator once before the if and then re-use it

BasicBlock *NewSucc = nullptr;
for (unsigned I = 0; I < CallBr->getNumSuccessors(); ++I) {
BasicBlock *Succ = CallBr->getSuccessor(I);
Instruction *Term = P->getTerminator();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(also here)

SmallDenseMap<BasicBlock *, BasicBlock *> CallBrTargets;
for (unsigned J = 0; J < CallBr->getNumSuccessors(); ++J) {
BasicBlock *Succ = CallBr->getSuccessor(J);
} else if (isa<CallBrInst>(BB->getTerminator()) ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same potential of hoisting BB->getTerminator() before the if

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could use the same reportFatalUsageError as for FixIrreducible (was changed in #205244) if you like - since you already updated the error message there

DomTreeUpdater *DTU, CycleInfo *CI,
LoopInfo *LI, bool *UpdatedLI) {
Instruction *Term = MultiBrBlock->getTerminator();
assert(Term && "expected terminator");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe we could keep checking for the specific terminators we want to handle here? Aka, Switch/Callbr now instead of only Callbr before.

pedroMVicente pushed a commit to pedroMVicente/llvm-project that referenced this pull request Jul 15, 2026
…#207598)

This fixes a bug where splitting `callbr` multiedges corrupts the
successor's PHI nodes.

Originally, the first split edge would replace all incoming edges from
the `callbr` block with the newly introduced target block by using
`replacePhiUsesWith`. Later edges would create new target blocks and
would try to update their edge's PHI as well, but would not find it,
leading to a corrupted PHI node.

To fix this, it is theoretically only necessary to ensure that exactly
one PHI argument is replaced per split edge. However, as all the PHI
nodes must have the same argument for every edge from one predecessor, a
single target block suffices, through which all traffic can be routed,
which will be especially useful for switches, where multiedges are
common.

[Trunk crashing](https://godbolt.org/z/4MM5eMrW5)

Found while working on PR llvm#206567, cc @ro-i.

@ro-i ro-i left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM
Just needs some merge conflict fixed that popped up

@hertelukas
hertelukas force-pushed the fix-irreducible-switches branch from 5bc79b5 to 606679f Compare July 16, 2026 18:47
@hertelukas

Copy link
Copy Markdown
Contributor Author

Done, thanks for the review. I also changed the FixIrreducible/switch.ll test, as the order of the cycles has changed when printing, so I removed the CYCLES-* test.s

@ro-i

ro-i commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

The tests aren't unstable, I think. The order changed due to recent changes of the Cycle implementation. The pre-existing callbr tests have been adapted by the author that made the Cycle change: 3f6af3b#diff-ab0d464ef41d4c58e8587e39a58067a8e67a64cbf13b4b64b202c25557d47962
So, you would probably only need to reorder some labels, afaict?

@hertelukas
hertelukas force-pushed the fix-irreducible-switches branch 2 times, most recently from 9d080fd to aff4261 Compare July 17, 2026 16:42
@hertelukas

Copy link
Copy Markdown
Contributor Author

Ah, true, my oversight; yes, I had to change exactly the same lines corresponding to the callbr.ll test. I rebased twice now due to merge conflicts, as there seems to be going on a lot with Cycles, but should be good to go now. I also ran with -DLLVM_ENABLE_EXPENSIVE_CHECKS=ON locally, and everything passed.

Reuse the approach for callbr terminators for switches. Branches,
entering irreducible loops through switches, are split and replaced
with unconditional branches into the loop.

Assisted-by: LLM (Adapted callbr test structure to switch)
@hertelukas
hertelukas force-pushed the fix-irreducible-switches branch from aff4261 to 9704bf2 Compare July 19, 2026 18:42
@ro-i
ro-i merged commit 9d2e7e6 into llvm:main Jul 20, 2026
10 checks passed
@github-actions

Copy link
Copy Markdown

@hertelukas Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@ro-i

ro-i commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants