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

Reid Kleckner via llvm-commits llvm-commits at lists.llvm.org
Fri Jun 26 21:18:41 PDT 2026


https://github.com/rnk updated https://github.com/llvm/llvm-project/pull/206070

>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 1/2] 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) {

>From 5e7862f5c315c874fc82c6caa7f2313d7e194996 Mon Sep 17 00:00:00 2001
From: Reid Kleckner <rkleckner at nvidia.com>
Date: Fri, 26 Jun 2026 21:18:32 -0700
Subject: [PATCH 2/2] Update llvm/lib/CodeGen/MachineBasicBlock.cpp

---
 llvm/lib/CodeGen/MachineBasicBlock.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/llvm/lib/CodeGen/MachineBasicBlock.cpp b/llvm/lib/CodeGen/MachineBasicBlock.cpp
index 3315d47566e5a..2870bf404644c 100644
--- a/llvm/lib/CodeGen/MachineBasicBlock.cpp
+++ b/llvm/lib/CodeGen/MachineBasicBlock.cpp
@@ -936,6 +936,8 @@ void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
 }
 
 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
+  // This is often called on many predecessors in reverse order.
+  // Do a reverse search and removal to avoid quadratic behavior in such cases.
   auto RI = llvm::find(reverse(Predecessors), Pred);
   assert(RI != Predecessors.rend() &&
          "Pred is not a predecessor of this block!");



More information about the llvm-commits mailing list