Repository navigation
[WebAssembly] Incorporate SCCs into WebAssemblyFixIrreducibleControlFlow - #181755
Conversation
|
@llvm/pr-subscribers-backend-webassembly Author: Demetrius Kanios (QuantumSegfault) ChangesRather than mapping out full "reachability" between blocks in a region to find loops and using This brings in LLVM's generic 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 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 1 Files Affected:
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;
}
|
|
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. |
|
Kudos on using |
dschuff
left a comment
There was a problem hiding this comment.
I didn't quite get through reviewing yet this but here are a few comments.
|
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 ( 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. |
|
Hmmm.... #101386 Looks like the core |
|
Okay. The |
|
I was going to reply on #182237 but let's keep the discussion all in one place.
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. |
It seems nearly the same, except for the extra
The // Limitation: The pass cannot handle switch statements and indirect
// branches. Both must be lowered to plain branches first.I'm not sure why |
|
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. |
|
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). |
|
+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): 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 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 EDIT: The first version of this comment swapped the standardized and legacy links. I've fixed them now. |
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.
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! |
|
cc @kripken in case you have comments |
|
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) |
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. 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. |
|
Actually I found enough time to get a testcase: (big cpp file with all of libc++ headers in it...) This crashes with |
This reverts commit c2f66f2.
…ControlFlow (llvm#181755)" This reverts commit c05e323.
|
Revert at #183872 Do I wait for CI, or just merge immediately? |
This comment was marked as outdated.
This comment was marked as outdated.
|
Well, it took me a long time to remember that 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 |
|
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. |
|
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 Any opinions? |
…ControlFlow (llvm#181755)" (llvm#183872) This reverts commit c05e323. Changes failed Emscripten tests.
…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)).
This variable ends up being unused in builds without assertions. Mark it [[maybe_unused]] per the coding standards.
…ControlFlow (llvm#181755)" (llvm#183872) This reverts commit c05e323. Changes failed Emscripten tests.
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`.
… (#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`.
… (#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`.
# 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]>
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.
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.
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.
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.
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.
…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)

Rather than mapping out full "reachability" between blocks in a region to find loops and using
LoopBlocksto 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
SCCIteratorto light in this context (blog post, implementation).