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

via llvm-commits llvm-commits at lists.llvm.org
Sun Jun 28 19:19:02 PDT 2026


Author: Jinjie Huang
Date: 2026-06-29T10:18:57+08:00
New Revision: e568ab3b0fceeeba1b43400b199ab07f719b1092

URL: https://github.com/llvm/llvm-project/commit/e568ab3b0fceeeba1b43400b199ab07f719b1092
DIFF: https://github.com/llvm/llvm-project/commit/e568ab3b0fceeeba1b43400b199ab07f719b1092.diff

LOG: [CodeGen] Search predecessors from the back in removePredecessor() (#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.

So this patch tries to change the search logic to a reverse search to
better align with the majority of actual CFG manipulation scenarios.
And 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.

---------

Co-authored-by: Reid Kleckner <rkleckner at nvidia.com>

Added: 
    

Modified: 
    llvm/lib/CodeGen/MachineBasicBlock.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/lib/CodeGen/MachineBasicBlock.cpp b/llvm/lib/CodeGen/MachineBasicBlock.cpp
index ad0742bf49292..2870bf404644c 100644
--- a/llvm/lib/CodeGen/MachineBasicBlock.cpp
+++ b/llvm/lib/CodeGen/MachineBasicBlock.cpp
@@ -936,9 +936,12 @@ 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);
+  // 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!");
+  Predecessors.erase(std::prev(RI.base()));
 }
 
 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {


        


More information about the llvm-commits mailing list