[llvm] [CodeGen] Search predecessors from the back in MachineBasicBlock::removePredecessor (PR #206070)

Jinjie Huang via llvm-commits llvm-commits at lists.llvm.org
Fri Jun 26 07:04:50 PDT 2026


https://github.com/Jinjie-Huang created https://github.com/llvm/llvm-project/pull/206070

In many passes involving CFG updates, it is a common pattern to process the Predecessors vector from back to front for efficiency. However, the current forward search in removePredecessor often results in an O(N) complexity.

This patch changes the search logic to a reverse search to better align with the majority of actual CFG manipulation scenarios. In a real-world case (with ~16k predecessors), this modification can help to reduce the execution time of the BranchFolder pass from 166.4951s to 6.0717s.

>From 73303ed4f988a484c6d07b726e3885debbc86397 Mon Sep 17 00:00:00 2001
From: huangjinjie <huangjinjie at bytedance.com>
Date: Fri, 26 Jun 2026 21:51:23 +0800
Subject: [PATCH] Search predecessors from the back in
 MachineBasicBlock::removePredecessor

---
 llvm/lib/CodeGen/MachineBasicBlock.cpp | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/CodeGen/MachineBasicBlock.cpp b/llvm/lib/CodeGen/MachineBasicBlock.cpp
index ad0742bf49292..3315d47566e5a 100644
--- a/llvm/lib/CodeGen/MachineBasicBlock.cpp
+++ b/llvm/lib/CodeGen/MachineBasicBlock.cpp
@@ -936,9 +936,10 @@ void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
 }
 
 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
-  pred_iterator I = find(Predecessors, Pred);
-  assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
-  Predecessors.erase(I);
+  auto RI = llvm::find(reverse(Predecessors), Pred);
+  assert(RI != Predecessors.rend() &&
+         "Pred is not a predecessor of this block!");
+  Predecessors.erase(std::prev(RI.base()));
 }
 
 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {



More information about the llvm-commits mailing list