[llvm] [WIP] Fold (bitwiseop X, (add (not Y), Z)) -> (bitwiseop X, (not (sub Y, Z))). (PR #141476)

Xu Zhang via llvm-commits llvm-commits at lists.llvm.org
Mon May 26 04:19:15 PDT 2025


https://github.com/simonzgx created https://github.com/llvm/llvm-project/pull/141476

None

>From 2d7659b36868cff0b7918d0af3a0ee463b48be9a Mon Sep 17 00:00:00 2001
From: Xu Zhang <simonzgx at gmail.com>
Date: Mon, 26 May 2025 19:17:50 +0800
Subject: [PATCH] [DAG] Fold (bitwiseop X, (add (not Y), Z)) -> (bitwiseop X,
 (not (sub Y, Z))).

---
 llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
index efaa8bd4a7950..31fbab23e4fcf 100644
--- a/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
+++ b/llvm/lib/CodeGen/SelectionDAG/DAGCombiner.cpp
@@ -7528,6 +7528,13 @@ SDValue DAGCombiner::visitAND(SDNode *N) {
       return DAG.getNode(ISD::AND, DL, VT, X,
                          DAG.getNOT(DL, DAG.getNode(Opc, DL, VT, Y, Z), VT));
 
+  // a bitwiseop (~b + c) -> a bitwiseop ~(b - c).
+  // Fold (and X, (add (not Y), Z)) -> (and X, (not (sub Y, Z)))
+  if (sd_match(N, m_And(m_Value(X), m_Add(m_Value(NotY), m_Value(Z)))) &&
+      sd_match(NotY, m_Not(m_Value(Y))) &&
+      (TLI.hasAndNot(SDValue(N, 0)) || NotY->hasOneUse())) {
+		return DAG.getNode(ISD::AND, DL, VT, X, DAG.getNOT(DL, DAG.getNode(ISD::SUB, DL, VT, Y, Z), VT));
+  }
   // Fold (and (srl X, C), 1) -> (srl X, BW-1) for signbit extraction
   // If we are shifting down an extended sign bit, see if we can simplify
   // this to shifting the MSB directly to expose further simplifications.



More information about the llvm-commits mailing list