Skip to content

[WebAssembly] Incorporate SCCs into WebAssemblyFixIrreducibleControlFlow - #181755

Merged
QuantumSegfault merged 4 commits into
llvm:mainfrom
QuantumSegfault:wasm-fix-irreducible-cfg-fix
Feb 27, 2026
Merged

QuantumSegfault merged 4 commits into
llvm:mainfrom
QuantumSegfault:wasm-fix-irreducible-cfg-fix

Conversation

@QuantumSegfault

Copy link
Copy Markdown
Member

Rather than mapping out full "reachability" between blocks in a region to find loops and using LoopBlocks to find the bodies of said loops, use SCCs (strongly-connected components) to provide this information.

This brings in LLVM's generic SCCIterator (which uses Tarjan's algorithm) as the implementation for sorting the basic blocks of the CFG into their SCCs.

This PR greatly reduces the compile-time footprint of the pass, making memory use and time taken negliable where it might have previously caused stalls and OOM before (e.g. #47793, usagi-coffee/tree-sitter-abl#114)


Supersedes #179722

Fixes #47793
Fixes #165041 (probably)

Thanks to @jkbz64 for the initial investigations (w/ AI; see #179722) into why this pass was slow and memory consuming and showing that SCCs were the key.

Also thanks to the Cheerp compiler project for bringing SCCIterator to light in this context (blog post, implementation).

@llvmbot

llvmbot commented Feb 16, 2026

Copy link
Copy Markdown
Member

@llvm/pr-subscribers-backend-webassembly

Author: Demetrius Kanios (QuantumSegfault)

Changes

Rather than mapping out full "reachability" between blocks in a region to find loops and using LoopBlocks to find the bodies of said loops, use SCCs (strongly-connected components) to provide this information.

This brings in LLVM's generic SCCIterator (which uses Tarjan's algorithm) as the implementation for sorting the basic blocks of the CFG into their SCCs.

This PR greatly reduces the compile-time footprint of the pass, making memory use and time taken negliable where it might have previously caused stalls and OOM before (e.g. #47793, usagi-coffee/tree-sitter-abl#114)


Supersedes #179722

Fixes #47793
Fixes #165041 (probably)

Thanks to @jkbz64 for the initial investigations (w/ AI; see #179722) into why this pass was slow and memory consuming and showing that SCCs were the key.

Also thanks to the Cheerp compiler project for bringing SCCIterator to light in this context (blog post, implementation).


Full diff: https://github.com/llvm/llvm-project/pull/181755.diff

1 Files Affected:

  • (modified) llvm/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp (+140-118)
diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp b/llvm/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp
index 07171d472dc2d..90a8a0fe5fcf6 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyFixIrreducibleControlFlow.cpp
@@ -55,9 +55,12 @@
 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
 #include "WebAssembly.h"
 #include "WebAssemblySubtarget.h"
+#include "llvm/ADT/SCCIterator.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
 #include "llvm/CodeGen/MachineFunctionPass.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/Support/Debug.h"
+#include <limits>
 using namespace llvm;
 
 #define DEBUG_TYPE "wasm-fix-irreducible-control-flow"
@@ -78,9 +81,17 @@ static BlockVector getSortedEntries(const BlockSet &Entries) {
   return SortedEntries;
 }
 
-// Calculates reachability in a region. Ignores branches to blocks outside of
-// the region, and ignores branches to the region entry (for the case where
-// the region is the inner part of a loop).
+class ReachabilityGraph;
+
+struct ReachabilityNode {
+  MachineBasicBlock *MBB;
+  SmallVector<ReachabilityNode *, 4> Succs;
+  unsigned SCCId = std::numeric_limits<unsigned>::max();
+};
+
+// Analyzes the SCC (strongly-connected component) structure in a region.
+// Ignores branches to blocks outside of the region, and ignores branches to the
+// region entry (for the case where the region is the inner part of a loop).
 class ReachabilityGraph {
 public:
   ReachabilityGraph(MachineBasicBlock *Entry, const BlockSet &Blocks)
@@ -98,137 +109,144 @@ class ReachabilityGraph {
     calculate();
   }
 
-  bool canReach(MachineBasicBlock *From, MachineBasicBlock *To) const {
-    assert(inRegion(From) && inRegion(To));
-    auto I = Reachable.find(From);
-    if (I == Reachable.end())
-      return false;
-    return I->second.count(To);
-  }
-
-  // "Loopers" are blocks that are in a loop. We detect these by finding blocks
-  // that can reach themselves.
-  const BlockSet &getLoopers() const { return Loopers; }
-
   // Get all blocks that are loop entries.
   const BlockSet &getLoopEntries() const { return LoopEntries; }
+  const BlockSet &getLoopEntriesForSCC(unsigned SCCId) const {
+    return LoopEntriesBySCC[SCCId];
+  }
 
-  // Get all blocks that enter a particular loop from outside.
-  const BlockSet &getLoopEnterers(MachineBasicBlock *LoopEntry) const {
-    assert(inRegion(LoopEntry));
-    auto I = LoopEnterers.find(LoopEntry);
-    assert(I != LoopEnterers.end());
-    return I->second;
+  unsigned getSCCId(MachineBasicBlock *MBB) const {
+    return getNode(MBB)->SCCId;
   }
 
+  friend struct GraphTraits<ReachabilityGraph *>;
+
 private:
   MachineBasicBlock *Entry;
   const BlockSet &Blocks;
 
-  BlockSet Loopers, LoopEntries;
-  DenseMap<MachineBasicBlock *, BlockSet> LoopEnterers;
+  BlockSet LoopEntries;
+  SmallVector<BlockSet, 0> LoopEntriesBySCC;
 
   bool inRegion(MachineBasicBlock *MBB) const { return Blocks.count(MBB); }
 
-  // Maps a block to all the other blocks it can reach.
-  DenseMap<MachineBasicBlock *, BlockSet> Reachable;
+  SmallVector<ReachabilityNode, 0> Nodes;
+  DenseMap<MachineBasicBlock *, ReachabilityNode *> MBBToNodeMap;
 
-  void calculate() {
-    // Reachability computation work list. Contains pairs of recent additions
-    // (A, B) where we just added a link A => B.
-    using BlockPair = std::pair<MachineBasicBlock *, MachineBasicBlock *>;
-    SmallVector<BlockPair, 4> WorkList;
+  ReachabilityNode *getNode(MachineBasicBlock *MBB) const {
+    auto It = MBBToNodeMap.find(MBB);
+    assert(It != MBBToNodeMap.end());
+    return It->second;
+  }
 
-    // Add all relevant direct branches.
-    for (auto *MBB : Blocks) {
-      for (auto *Succ : MBB->successors()) {
-        if (Succ != Entry && inRegion(Succ)) {
-          Reachable[MBB].insert(Succ);
-          WorkList.emplace_back(MBB, Succ);
-        }
-      }
-    }
+  void calculate();
+};
+} // end anonymous namespace
 
-    while (!WorkList.empty()) {
-      MachineBasicBlock *MBB, *Succ;
-      std::tie(MBB, Succ) = WorkList.pop_back_val();
-      assert(inRegion(MBB) && Succ != Entry && inRegion(Succ));
-      if (MBB != Entry) {
-        // We recently added MBB => Succ, and that means we may have enabled
-        // Pred => MBB => Succ.
-        for (auto *Pred : MBB->predecessors()) {
-          if (Reachable[Pred].insert(Succ).second) {
-            WorkList.emplace_back(Pred, Succ);
-          }
-        }
-      }
-    }
+namespace llvm {
+template <> struct GraphTraits<ReachabilityGraph *> {
+  typedef ReachabilityNode NodeType;
+  typedef NodeType *NodeRef;
+  typedef SmallVectorImpl<NodeRef>::iterator ChildIteratorType;
 
-    // Blocks that can return to themselves are in a loop.
-    for (auto *MBB : Blocks) {
-      if (canReach(MBB, MBB)) {
-        Loopers.insert(MBB);
-      }
-    }
-    assert(!Loopers.count(Entry));
-
-    // Find the loop entries - loopers reachable from blocks not in that loop -
-    // and those outside blocks that reach them, the "loop enterers".
-    for (auto *Looper : Loopers) {
-      for (auto *Pred : Looper->predecessors()) {
-        // Pred can reach Looper. If Looper can reach Pred, it is in the loop;
-        // otherwise, it is a block that enters into the loop.
-        if (!canReach(Looper, Pred)) {
-          LoopEntries.insert(Looper);
-          LoopEnterers[Looper].insert(Pred);
-        }
-      }
-    }
+  static NodeRef getEntryNode(ReachabilityGraph *G) {
+    return G->getNode(G->Entry);
+  }
+
+  static inline ChildIteratorType child_begin(NodeRef N) {
+    return N->Succs.begin();
+  }
+
+  static inline ChildIteratorType child_end(NodeRef N) {
+    return N->Succs.end();
   }
 };
+} // end namespace llvm
 
-// Finds the blocks in a single-entry loop, given the loop entry and the
-// list of blocks that enter the loop.
-class LoopBlocks {
-public:
-  LoopBlocks(MachineBasicBlock *Entry, const BlockSet &Enterers)
-      : Entry(Entry), Enterers(Enterers) {
-    calculate();
+namespace {
+
+void ReachabilityGraph::calculate() {
+  auto NumBlocks = Blocks.size();
+  Nodes.assign(NumBlocks, {});
+
+  MBBToNodeMap.clear();
+  MBBToNodeMap.reserve(NumBlocks);
+
+  // Initialize mappings.
+  unsigned MBBIdx = 0;
+  for (auto *MBB : Blocks) {
+    auto &Node = Nodes[MBBIdx++];
+
+    Node.MBB = MBB;
+    MBBToNodeMap[MBB] = &Node;
   }
 
-  BlockSet &getBlocks() { return Blocks; }
+  // Add all relevant direct branches.
+  MBBIdx = 0;
+  for (auto *MBB : Blocks) {
+    auto &Node = Nodes[MBBIdx++];
 
-private:
-  MachineBasicBlock *Entry;
-  const BlockSet &Enterers;
+    for (auto *Succ : MBB->successors()) {
+      if (Succ != Entry && inRegion(Succ)) {
+        Node.Succs.push_back(getNode(Succ));
+      }
+    }
+  }
 
-  BlockSet Blocks;
+  unsigned CurrSCCIdx = 0;
+  for (auto &SCC : make_range(scc_begin(this), scc_end(this))) {
+    LoopEntriesBySCC.push_back({});
+    auto &SCCLoopEntries = LoopEntriesBySCC[CurrSCCIdx];
 
-  void calculate() {
-    // Going backwards from the loop entry, if we ignore the blocks entering
-    // from outside, we will traverse all the blocks in the loop.
-    BlockVector WorkList;
-    BlockSet AddedToWorkList;
-    Blocks.insert(Entry);
-    for (auto *Pred : Entry->predecessors()) {
-      if (!Enterers.count(Pred)) {
-        WorkList.push_back(Pred);
-        AddedToWorkList.insert(Pred);
+    for (auto *Node : SCC) {
+      // Make sure nodes are only ever assigned one SCC
+      assert(Node->SCCId == std::numeric_limits<unsigned>::max());
+
+      Node->SCCId = CurrSCCIdx;
+    }
+
+    bool SelfLoop = false;
+    if (SCC.size() == 1) {
+      auto &Node = SCC[0];
+
+      if (Node->MBB != Entry) {
+        for (auto *Succ : Node->Succs) {
+          if (Succ == Node) {
+            SelfLoop = true;
+            break;
+          }
+        }
       }
     }
 
-    while (!WorkList.empty()) {
-      auto *MBB = WorkList.pop_back_val();
-      assert(!Enterers.count(MBB));
-      if (Blocks.insert(MBB).second) {
-        for (auto *Pred : MBB->predecessors()) {
-          if (AddedToWorkList.insert(Pred).second)
-            WorkList.push_back(Pred);
+    // Blocks outside any (multi-block) loop will be isolated in their own
+    // single-element SCC. Thus blocks that are in a loop are those in
+    // multi-element SCCs or are self-looping.
+    if (SCC.size() > 1 || SelfLoop) {
+      // Find the loop entries - loop body blocks with predecessors outside
+      // their SCC
+      for (auto *Node : SCC) {
+        if (Node->MBB == Entry)
+          continue;
+
+        for (auto *Pred : Node->MBB->predecessors()) {
+          // This test is accurate despite not having assigned all nodes an SCC
+          // yet. We only care if a node has been assigned into this SCC or not.
+          if (getSCCId(Pred) != CurrSCCIdx) {
+            LoopEntries.insert(Node->MBB);
+            SCCLoopEntries.insert(Node->MBB);
+          }
         }
       }
     }
+    ++CurrSCCIdx;
   }
-};
+
+  // Make sure all nodes have been processed
+  for (auto &Node : Nodes) {
+    assert(Node.SCCId != std::numeric_limits<unsigned>::max());
+  }
+}
 
 class WebAssemblyFixIrreducibleControlFlow final : public MachineFunctionPass {
   StringRef getPassName() const override {
@@ -240,7 +258,7 @@ class WebAssemblyFixIrreducibleControlFlow final : public MachineFunctionPass {
   bool processRegion(MachineBasicBlock *Entry, BlockSet &Blocks,
                      MachineFunction &MF);
 
-  void makeSingleEntryLoop(BlockSet &Entries, BlockSet &Blocks,
+  void makeSingleEntryLoop(const BlockSet &Entries, BlockSet &Blocks,
                            MachineFunction &MF, const ReachabilityGraph &Graph);
 
 public:
@@ -261,7 +279,7 @@ bool WebAssemblyFixIrreducibleControlFlow::processRegion(
     for (auto *LoopEntry : getSortedEntries(Graph.getLoopEntries())) {
       // Find mutual entries - all entries which can reach this one, and
       // are reached by it (that always includes LoopEntry itself). All mutual
-      // entries must be in the same loop, so if we have more than one, then we
+      // entries must be in the same SCC, so if we have more than one, then we
       // have irreducible control flow.
       //
       // (Note that we need to sort the entries here, as otherwise the order can
@@ -284,15 +302,8 @@ bool WebAssemblyFixIrreducibleControlFlow::processRegion(
       // a group of blocks all of whom can reach each other. (We'll see the
       // irreducibility after removing branches to the top of that enclosing
       // loop.)
-      BlockSet MutualLoopEntries;
-      MutualLoopEntries.insert(LoopEntry);
-      for (auto *OtherLoopEntry : Graph.getLoopEntries()) {
-        if (OtherLoopEntry != LoopEntry &&
-            Graph.canReach(LoopEntry, OtherLoopEntry) &&
-            Graph.canReach(OtherLoopEntry, LoopEntry)) {
-          MutualLoopEntries.insert(OtherLoopEntry);
-        }
-      }
+      auto &MutualLoopEntries =
+          Graph.getLoopEntriesForSCC(Graph.getSCCId(LoopEntry));
 
       if (MutualLoopEntries.size() > 1) {
         makeSingleEntryLoop(MutualLoopEntries, Blocks, MF, Graph);
@@ -301,6 +312,7 @@ bool WebAssemblyFixIrreducibleControlFlow::processRegion(
         break;
       }
     }
+
     // Only go on to actually process the inner loops when we are done
     // removing irreducible control flow and changing the graph. Modifying
     // the graph as we go is possible, and that might let us avoid looking at
@@ -312,14 +324,22 @@ bool WebAssemblyFixIrreducibleControlFlow::processRegion(
     }
 
     for (auto *LoopEntry : Graph.getLoopEntries()) {
-      LoopBlocks InnerBlocks(LoopEntry, Graph.getLoopEnterers(LoopEntry));
+      BlockSet InnerBlocks;
+
+      auto EntrySCCId = Graph.getSCCId(LoopEntry);
+      for (auto *Block : Blocks) {
+        if (EntrySCCId == Graph.getSCCId(Block)) {
+          InnerBlocks.insert(Block);
+        }
+      }
+
       // Each of these calls to processRegion may change the graph, but are
       // guaranteed not to interfere with each other. The only changes we make
       // to the graph are to add blocks on the way to a loop entry. As the
       // loops are disjoint, that means we may only alter branches that exit
       // another loop, which are ignored when recursing into that other loop
       // anyhow.
-      if (processRegion(LoopEntry, InnerBlocks.getBlocks(), MF)) {
+      if (processRegion(LoopEntry, InnerBlocks, MF)) {
         Changed = true;
       }
     }
@@ -335,7 +355,7 @@ bool WebAssemblyFixIrreducibleControlFlow::processRegion(
 // ReachabilityGraph; this will be updated in the caller of this function as
 // needed.
 void WebAssemblyFixIrreducibleControlFlow::makeSingleEntryLoop(
-    BlockSet &Entries, BlockSet &Blocks, MachineFunction &MF,
+    const BlockSet &Entries, BlockSet &Blocks, MachineFunction &MF,
     const ReachabilityGraph &Graph) {
   assert(Entries.size() >= 2);
 
@@ -401,10 +421,12 @@ void WebAssemblyFixIrreducibleControlFlow::makeSingleEntryLoop(
   // This set stores predecessors within this loop.
   DenseSet<MachineBasicBlock *> InLoop;
   for (auto *Pred : AllPreds) {
+    auto PredSCCId = Graph.getSCCId(Pred);
+
     for (auto *Entry : Pred->successors()) {
       if (!Entries.count(Entry))
         continue;
-      if (Graph.canReach(Entry, Pred)) {
+      if (Graph.getSCCId(Entry) == PredSCCId) {
         InLoop.insert(Pred);
         break;
       }

@QuantumSegfault

Copy link
Copy Markdown
Member Author

Requesting review

@dschuff @kripken @ppenzin @aheejin @jkbz64

@QuantumSegfault

Copy link
Copy Markdown
Member Author

I checked this against the reproducer in #47793 as another test (diff between output before and after PR), and it looks good.

Goes from over 10 GB RAM usage and 35 seconds spent in the pass vs keeping under 150 MB and spending less than 10 ms in the pass.

Pretty significant difference. Even for programs with little or no irreducible control flow, programs with functions containing large numbers of blocks would bring this pass to it's knees. Reachable was probably the culprit...mapping each block in a region to every other block it can transitively reach. Compounded by large nested loops.

@ppenzin

ppenzin commented Feb 17, 2026 •

Copy link
Copy Markdown
Contributor

Kudos on using SCCIterator! I think we need to co-credit @jkbz64 for proving that this would work in a hand-written SCC implementation.

@dschuff dschuff left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I didn't quite get through reviewing yet this but here are a few comments.

@nikic

nikic commented Feb 18, 2026

Copy link
Copy Markdown
Contributor

Just as a FYI, LLVM nowadays also has CycleInfo, which is like LoopInfo but supporting irreducible cycles. Not sure whether that is useful here or not as I'm not familiar with the requirements of this code.

@QuantumSegfault

Copy link
Copy Markdown
Member Author

Just as a FYI, LLVM nowadays also has CycleInfo, which is like LoopInfo but supporting irreducible cycles. Not sure whether that is useful here or not as I'm not familiar with the requirements of this code.

I took a quick look and it COULD work... but I think it would require an even more invasive change than this. The way I see it the main benefit is that we could detect all the cycles from the start, and actually update the graph (GenericCycle::setSingleEntry) in-place rather than recalculate the whole thing each time we fix some irreduciblity. But I hesitate to try that when we have something here that works, and that already is a MAJOR performance boost. But I suppose experimenting with it couldn't hurt (I don't have anything better to work on ATM).

The other thing is getting the generated code to be the exact same is going to be difficult? We currently sort to process the loops in a stable order. CycleInfo is probably determinstic, but iterating over them seems likely to happen in a different, unspecified order. Might be able to compensate though.

@QuantumSegfault

Copy link
Copy Markdown
Member Author

Hmmm.... #101386

Looks like the core FixIrreducible pass moved from SCC to CycleInfo as well. I guess I'll see how that goes for us.

@QuantumSegfault

Copy link
Copy Markdown
Member Author

Okay. The MachineCycleInfo option is ready. #182237

@dschuff

dschuff commented Feb 19, 2026

Copy link
Copy Markdown
Member

I was going to reply on #182237 but let's keep the discussion all in one place.
Looking at this new discussion and CycleInfo and #101386 made me realize that all of that (including FixIrreducible itself) is newer than our current implementation which means that another option potentially on the table is to just not use any of this custom code at all and just use FixIrreducible (I tried this with #182384). Looking at the CFG images you posted on that PR, FixIrreducible itself gives still a different result for that function (see below) which looks sort of close to what you got in #182237 but not quite exactly.

image

However it turns out that it doesn't pass all of the emscripten tests; there is at least one where the FixIrreducible pass itself fails, and another where WebAssemblyCFGSort fails after it. I haven't looked into why; perhaps WebAssemblyCFGSort is implicitly depending on some property beyond just reducibility, although the FixIrreducible failures are slightly more surprising.

#182237 does pass the Emscripten tests though.

@QuantumSegfault

Copy link
Copy Markdown
Member Author

FixIrreducible itself gives still a different result for that function (see below) which looks sort of close to what you got in #182237 but not quite exactly.

It seems nearly the same, except for the extra Routing blocks added by our version of the pass.

there is at least one where the FixIrreducible pass itself fails, and another where WebAssemblyCFGSort fails after it. I haven't looked into why; perhaps WebAssemblyCFGSort is implicitly depending on some property beyond just reducibility, although the FixIrreducible failures are slightly more surprising.

The FixIrreducible failure is possibly because:

// Limitation: The pass cannot handle switch statements and indirect
//             branches. Both must be lowered to plain branches first.

I'm not sure why WebAssemblyCFGSort is tripping up, but I was planning to investigate the pass anyway since it is another surprisingly expensive one.

@dschuff

dschuff commented Feb 20, 2026

Copy link
Copy Markdown
Member

If you are interested into looking more into the wild and complex world of LLVM Wasm control flow, maybe it would make sense to start with this version of the change, since it uses the same algorithm that we currently have, basically a faster version of the same thing. And we've already done some vetting on it, so we can get some immediate benefits.
Then we can look more deeply into other options and consider things like the interactions between the passes (including the EH restructuring code, which also is split between IR passes and WebAssemblyCFGSort/Stackify). Maybe there are further simplifications or performance improvements, but changes would likely be higher risk, and we can take our time with them.

@QuantumSegfault

QuantumSegfault commented Feb 20, 2026 •

Copy link
Copy Markdown
Member Author

I think that makes sense. Merge this major fix in, since it's all upsides (faster compilation with the same results). Then worry the rest later.


I've never even looked at Wasm EH, but I guess it's about time to learn since it's been finalized in the spec.

Maybe it's time to start pouring through the various control-flow related TODOs scattered about and start acting on them...since nobody else has (unless somebody has?).

WebAssemblyCFGSort is my next focus as that seems to be taking an absurd amount of time when trying to compile @jkbz64's tree sitter parser/grammer (92% of the compile; 44 seconds).

@aheejin

aheejin commented Feb 20, 2026 •

Copy link
Copy Markdown
Member

+1 on merging this one first. #182237 might be fine, but I am worried there might be code size effect. We have some comments in the code, which is possibly related (written by @sunfishcode):

/// Note that LLVM has a generic pass that lowers irreducible control flow, but
/// it linearizes control flow, turning diamonds into two triangles, which is
/// both unnecessary and undesirable for WebAssembly.


The reason #182384 fails some tests can be the ones @QuantumSegfault mentioned, or because it is an IR pass. We run many common MIR passes after isel, and while I can't think of any pass that would intentionally create irreducible CFGs, it is not impossible. So I think it is safer to remove all irreducible CFG at the very end of the backend pipeline (like now).


@QuantumSegfault In case you are looking into EH related code, it is a bit of a mess (especially CFGStackify) because we currently support two different proposals for historical reasons.

We implemented the legacy proposal first, and shipped it before standardizing it (for some reasons), and then we changed the proposal, and implemented the new proposal. But because the legacy proposal had been already shipped in web engines, we weren't able to just remove it from the web without due process. Currently most browsers and LLVM / binaryen toolchains support both.

(I don't have anything better to work on ATM)

I appreciate you willing to look into CFGSort. I wasn't aware that was very slow.

In case you are looking for something else to work on, and in case this interests you, we have a known bug related to EH and FixIrreducibleControlFlow (#63182): We currently don't handle irreducible CFGs created by unwind edges, because we can't use br_table for unwind edges. (It looks #49292 is a duplicate automatically created when we migrated from Bugzilla to Github issues. #63183 might be a the same or a separate bug.)

EDIT: The first version of this comment swapped the standardized and legacy links. I've fixed them now.

@QuantumSegfault

Copy link
Copy Markdown
Member Author

#182237 might be fine, but I am worried there might be code size effect.

That seems to be the basic tradeoff. SCC based approach can save us some code-size, vs CycleInfo preserves loop nesting better (rather than flattening things out a lot) which might help e.g. JIT optimizers track things better and emit more optimal code.

I appreciate you willing to look into CFGSort. I wasn't aware that was very slow.

The only reason it came to my attention is the same reason the ball started rolling on this. There's something about the parser...probably the sheer size of the small handful of functions that helped bring these problems to light.

There may not be any actual issue with CFGSort, might be just about as optimal as it gets, but I'll investigate.


Thanks for the info!

@aheejin

aheejin commented Feb 20, 2026

Copy link
Copy Markdown
Member

cc @kripken in case you have comments

@QuantumSegfault

QuantumSegfault commented Feb 20, 2026 •

Copy link
Copy Markdown
Member Author

Hmmm...okay, semi-false alarm.

The sort itself is fast. It's the verification (which only happens on LLVM assertions builds) afterwards that's the extremely slow part (when run on nearly 120,000 blocks within a single MF)

@aheejin aheejin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM % a few questions

@dschuff

dschuff commented Feb 20, 2026

Copy link
Copy Markdown
Member

+1 on merging this one first. #182237 might be fine, but I am worried there might be code size effect. We have some comments in the code, which is possibly related (written by @sunfishcode):

/// Note that LLVM has a generic pass that lowers irreducible control flow, but
/// it linearizes control flow, turning diamonds into two triangles, which is
/// both unnecessary and undesirable for WebAssembly.

Yeah this part in particular was what I was thinking might possibly be obsolete. The current FixIrreducible pass dates from 2020 whereas that comment is probably from 2016. But it still may be true that other parts of LLVM that want reducible control flow (e.g. AMDGPU who introduced FixIrreducible) have different requirements or goals than we do.
Now that I think about it, I do seem to recall discussing with @kripken back when he wrote this current version that we might prefer code size over speed since it would be slow anyway. But having said that, we can certainly re-evaluate the tradeoffs, especially if we have known use cases that we can actually measure performance for. Irreducible CFGs are fairly uncommon anyway.

Anyway we can move this one forward. Let's address any last feedback and nits and then I'll get this one run through our internal test again before we land it.

@kripken

kripken commented Feb 28, 2026

Copy link
Copy Markdown
Member

Actually I found enough time to get a testcase:

https://gist.githubusercontent.com/kripken/a82416c4a69e3a8ac4ef3b01b7f10f06/raw/dd9bab839cd9713995718f56bc1e14f700489fec/testcase.cpp

(big cpp file with all of libc++ headers in it...)

This crashes with

clang++ -target wasm32-unknown-emscripten -fignore-exceptions -mllvm -combiner-global-alias-analysis=false -mllvm -enable-emscripten-sjlj -mllvm -disable-lsr -DEMSCRIPTEN -Werror -c b.cpp

QuantumSegfault added a commit to QuantumSegfault/llvm-project that referenced this pull request Feb 28, 2026
QuantumSegfault added a commit to QuantumSegfault/llvm-project that referenced this pull request Feb 28, 2026
@QuantumSegfault

Copy link
Copy Markdown
Member Author

Revert at #183872

Do I wait for CI, or just merge immediately?

@QuantumSegfault

This comment was marked as outdated.

QuantumSegfault added a commit that referenced this pull request Feb 28, 2026
…ControlFlow (#181755)" (#183872)

This reverts commit c05e323.

Changes failed Emscripten tests.
@QuantumSegfault

Copy link
Copy Markdown
Member Author

Well, it took me a long time to remember that llc defaults to -O2 while clang -cc1 defaults to -O0, but I've finally got it boiled down:

target triple = "wasm32-unknown-unknown"

define hidden void @test() {
entry:
 switch i32 poison, label %b [
    i32 0, label %a
  ]

a:
  ret void

b:
    unreachable
}

For some reason the very specific case of having an unreachable instruction as the direct default target of a switch at -O0 causes the assertion to fail. Moving the unreachable inside the switch doesn't do it. Inserting another instruction between the unreachable and b doesn't do it. Any other optimization level doesn't do it.

@QuantumSegfault

Copy link
Copy Markdown
Member Author

Ah. Wow...

Some part of the IR => ISelDAG (also happens for IR => gMIR [GISel]) takes the switch, sees the default is "unreachable", and actually skips emitting a branch target for it. the switch becomes a unconditional branch to %a, which leaves %b as dead code...and since there's no way to get to %b it will never be seen by the SCC and be left unassigned.

There's no actual bug or issue with the implementation itself... it's my assertion that's wrong.

@QuantumSegfault

Copy link
Copy Markdown
Member Author

Options at this point are:

A. Remove the assertion and assume the SCC iteration works correctly (i.e. there will, by definition, be a block reachable from the region entry without an SCC) and adjust anything needed to guard against these isolated blocks
B. Do a DFS at the very beginning of the pass to to search for all reachable blocks from the MF entry, ignoring dead blocks
C. As an extension to B, eliminate any dead blocks
D. Modify the IR translator to clean up after itself and not leave the dangling dead blocks

Any opinions?

sahas3 pushed a commit to sahas3/llvm-project that referenced this pull request Mar 4, 2026
…ControlFlow (llvm#181755)" (llvm#183872)

This reverts commit c05e323.

Changes failed Emscripten tests.
sujianIBM pushed a commit to sujianIBM/llvm-project that referenced this pull request Mar 5, 2026
…low (llvm#181755)

Rather than mapping out full "reachability" between blocks in a region
to find loops and using `LoopBlocks` to find the bodies of said loops,
use SCCs (strongly-connected components) to provide this information.

This brings in LLVM's generic `SCCIterator` (which uses Tarjan's
algorithm) as the implementation for sorting the basic blocks of the CFG
into their SCCs.

This PR greatly reduces the compile-time footprint of the pass, making
memory use and time taken negliable where it might have previously
caused stalls and OOM before (e.g. llvm#47793,
usagi-coffee/tree-sitter-abl#114)

------

Supersedes llvm#179722

Fixes llvm#47793
Fixes llvm#165041 (probably)

Thanks to @jkbz64 for the initial investigations (w/ AI; see llvm#179722)
into why this pass was slow and memory consuming and showing that SCCs
were the key.

Also thanks to the Cheerp compiler project for bringing `SCCIterator` to
light in this context ([blog
post](https://cheerp.io/blog/control-flow#fix-the-irreducible-control-flow),
[implementation](https://github.com/leaningtech/cheerp-compiler/blob/master/llvm/lib/CheerpUtils/FixIrreducibleControlFlow.cpp)).
sujianIBM pushed a commit to sujianIBM/llvm-project that referenced this pull request Mar 5, 2026
This variable ends up being unused in builds without assertions. Mark it
[[maybe_unused]] per the coding standards.
sujianIBM pushed a commit to sujianIBM/llvm-project that referenced this pull request Mar 5, 2026
…ControlFlow (llvm#181755)" (llvm#183872)

This reverts commit c05e323.

Changes failed Emscripten tests.
QuantumSegfault added a commit that referenced this pull request Mar 5, 2026
…yFixIrreducibleControlFlow" (#181755) (#184441)

Re-application of #181755.

Includes fixes to issues found after the original's merge.
ro-i pushed a commit that referenced this pull request Jul 20, 2026
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](#181755 (comment))).

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`.
llvm-sync Bot pushed a commit to arm/arm-toolchain that referenced this pull request Jul 20, 2026
… (#206567)

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](llvm/llvm-project#181755 (comment))).

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`.
llvm-upstreamsync Bot pushed a commit to qualcomm/cpullvm-toolchain that referenced this pull request Jul 20, 2026
… (#206567)

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](llvm/llvm-project#181755 (comment))).

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`.
kjanat pushed a commit to kjanat/zed-editor that referenced this pull request Sep 9, 2026
# Objective

Bumps `wasi-sdk` to v34 that is based on LLVM 23.1 which includes [a
compile time and memory usage
fix](llvm/llvm-project#181755) for tree-sitter
grammars. It speeds up every grammar's compile time and reduces compile
memory usage unlocking big grammars that were impossible to compile
before to be submitted to Zed extensions.

Drive-by added additional wasi-sdk targets for the rest of the supported
architectures (by wasi-sdk), if riscv is unwanted I can remove it but it
should not create any problems (I think).

Also noticed the `download-wasi-sdk` script had `OS=mingw` which wasn't
even in the artifact name on v25.

## Testing

Compiled, ran and compiled my [big
grammar](https://github.com/usagi-coffee/tree-sitter-abl) on it, that
wouldn't compile at all pre-llvm 23.

## Self-Review Checklist:

- [X] I've reviewed my own diff for quality, security, and reliability

---

Release Notes:

- Fixed compiling dev extensions with big Tree-sitter grammars.
- Fixed compiling dev extensions on Windows ARM64.
- Added wasi-sdk installation invalidation.

---------

Co-authored-by: Kirill Bulatov <[email protected]>
leandrocp added a commit to leandrocp/lumis that referenced this pull request Oct 17, 2026
The Tree-sitter 0.26 CLI compiles through WASI SDK 29 (LLVM 21), whose
WebAssembly Fix Irreducible Control Flow pass needs about 24 GB on
tree-sitter-llvm's lexer, a single function of 4654 states. An
ubuntu-latest runner has 16 GB and 3 GB of swap, and shuts down when both
run out. 16 GB more swap lets the build finish. LLVM 23 fixes the pass
(llvm/llvm-project#181755) and ships with the Tree-sitter 0.27 CLI, so the
step goes with that move.
leandrocp added a commit to leandrocp/lumis that referenced this pull request Oct 17, 2026
The Tree-sitter 0.26 CLI compiles through WASI SDK 29 (LLVM 21), whose
WebAssembly Fix Irreducible Control Flow pass needs about 24 GB on
tree-sitter-llvm's lexer, a single function of 4654 states. An
ubuntu-latest runner has 16 GB and 3 GB of swap, and shuts down when both
run out. 16 GB more swap lets the build finish. LLVM 23 fixes the pass
(llvm/llvm-project#181755) and ships with the Tree-sitter 0.27 CLI, so the
step goes with that move.
leandrocp added a commit to leandrocp/lumis that referenced this pull request Oct 17, 2026
The Tree-sitter 0.26 CLI compiles through WASI SDK 29 (LLVM 21), whose
WebAssembly Fix Irreducible Control Flow pass needs about 24 GB on
tree-sitter-llvm's lexer, a single function of 4654 states. An
ubuntu-latest runner has 16 GB and 3 GB of swap, and shuts down when both
run out. 16 GB more swap lets the build finish. LLVM 23 fixes the pass
(llvm/llvm-project#181755) and ships with the Tree-sitter 0.27 CLI, so the
step goes with that move.
leandrocp added a commit to leandrocp/lumis that referenced this pull request Oct 17, 2026
The Tree-sitter 0.26 CLI compiles through WASI SDK 29 (LLVM 21), whose
Fix Irreducible Control Flow pass needs about 24 GB on tree-sitter-llvm's
lexer. A runner has 19 GB with swap, so the release build ran out of
memory, and 16 GB more swap left it at 15 minutes or past the 30-minute
timeout. LLVM 23 fixes the pass (llvm/llvm-project#181755).

`dev build-wasm` now downloads WASI SDK 34.0, the one Tree-sitter 0.27
pins, checks its SHA-256 and hands it to the CLI through
TREE_SITTER_WASI_SDK_PATH. The CLI stays at 0.26. It targets
`wasm32-unknown-wasi`, which SDK 34 only ships as `wasm32-wasip1`, so the
install links one to the other. The SDK is part of the toolchain id, so
parsers cached from SDK 29 are rebuilt, and the workflows cache it under
a key that follows its pin. The swap step goes.

llvm now builds in under a minute in about 450 MB.
leandrocp added a commit to leandrocp/lumis that referenced this pull request Oct 17, 2026
The Tree-sitter 0.26 CLI compiles through WASI SDK 29 (LLVM 21), whose
Fix Irreducible Control Flow pass needs about 24 GB on tree-sitter-llvm's
lexer. A runner has 19 GB with swap, so the release build ran out of
memory, and 16 GB more swap left it at 15 minutes or past the 30-minute
timeout. LLVM 23 fixes the pass (llvm/llvm-project#181755).

`dev build-wasm` now downloads WASI SDK 34.0, the one Tree-sitter 0.27
pins, checks its SHA-256 and hands it to the CLI through
TREE_SITTER_WASI_SDK_PATH. The CLI stays at 0.26. It targets
`wasm32-unknown-wasi`, which SDK 34 only ships as `wasm32-wasip1`, so the
install links one to the other. The SDK is part of the toolchain id, so
parsers cached from SDK 29 are rebuilt, and the workflows cache it under
a key that follows its pin. The swap step goes.

llvm now builds in under a minute in about 450 MB.
Hyp3rSon1X pushed a commit to Hyp3rSon1X/llvm-project that referenced this pull request Nov 23, 2026
…yFixIrreducibleControlFlow" (llvm#181755) (llvm#184441)

Re-application of llvm#181755.

Includes fixes to issues found after the original's merge.

(cherry picked from commit 0a76568)
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.

WebAssembly backend stalls on massive autogenerated C file "WebAssembly Fix Irreducible Control Flow" pass OOMs on a huge function

9 participants