[llvm] [CodeGen] Search predecessors from the back in removePredecessor() (PR #206070)
Jinjie Huang via llvm-commits
llvm-commits at lists.llvm.org
Fri Jun 26 20:58:04 PDT 2026
Jinjie-Huang wrote:
> I don't understand why this is beneficial. Please provide more context.
@nikic Thanks for taking a look.
During the BranchFolder pass ([OptimizeBlock()](https://github.com/llvm/llvm-project/blob/main/llvm/lib/CodeGen/BranchFolding.cpp#L1403-L1406)), it linearly iterates to remove empty MBBs by bridging their predecessors to their successors. This triggers predecessor removals through the process: ReplaceUsesOfBlockWith() -> [replaceSuccessor](https://github.com/llvm/llvm-project/blob/llvmorg-23-init/llvm/lib/CodeGen/MachineBasicBlock.cpp#L884)() -> removePredecessor().
The outer loop in BranchFolder pops predecessors from back to front. However, removePredecessor performs a forward find on the Predecessors vector. When an empty BB has a massive number of predecessors, combining this outer loop with the inner linear forward search degrades the time complexity to O(N^2). Consequently, changing the internal find to a reverse search significantly improves efficiency, because the target predecessor being removed is essentially always located at the very end of the Predecessors vector. I think this back-to-front removal pattern is quite common. Though the optimization may not be noticeable in standard cases with few predecessors, it provides a speedup in the scenario I encountered with 8~16k predecessors(this happens because when BranchFolder collapses long chains of empty BBs filled with PSEUDO_PROBEs, it forwards all their predecessors to the next block. This creates a snowball effect where the accumulated predecessor list grows increasingly larger...).
https://github.com/llvm/llvm-project/pull/206070
More information about the llvm-commits
mailing list