[llvm] [InstCombine] Sink NOT to be fold into ANDN/ORN/XNOR (PR #131120)

Piotr Fusik via llvm-commits llvm-commits at lists.llvm.org
Thu Mar 13 03:38:52 PDT 2025


https://github.com/pfusik created https://github.com/llvm/llvm-project/pull/131120

Fix #108840

>From 118290aa02020f5323561625e740d6e6515f7c18 Mon Sep 17 00:00:00 2001
From: Piotr Fusik <p.fusik at samsung.com>
Date: Thu, 13 Mar 2025 11:37:22 +0100
Subject: [PATCH] [InstCombine] Sink NOT to be fold into ANDN/ORN/XNOR

Fix #108840
---
 .../InstCombine/InstCombineAndOrXor.cpp       | 21 +++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
index 6cc241781d112..530ab19acd995 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
@@ -4685,6 +4685,24 @@ Instruction *InstCombinerImpl::foldNot(BinaryOperator &I) {
   return nullptr;
 }
 
+static Instruction *sinkNotIntoBitwiseOp(BinaryOperator &I) {
+  if (!match(&I, m_Not(m_Value())))
+    return nullptr;
+  BasicBlock *BB = I.getParent();
+  if (!all_of(I.users(), [BB](const User *U) {
+        auto *UI = dyn_cast<Instruction>(U);
+        // TODO: check if target has ANDN/ORN/XNOR
+        return UI && UI->getParent() != BB && UI->isBitwiseLogicOp();
+      }))
+    return nullptr;
+  for (Use &U : I.uses()) {
+    Instruction *NewNot = I.clone();
+    NewNot->insertBefore(cast<Instruction>(U.getUser())->getIterator());
+    U.set(NewNot);
+  }
+  return &I;
+}
+
 // FIXME: We use commutative matchers (m_c_*) for some, but not all, matches
 // here. We should standardize that construct where it is needed or choose some
 // other way to ensure that commutated variants of patterns are not missed.
@@ -5021,5 +5039,8 @@ Instruction *InstCombinerImpl::visitXor(BinaryOperator &I) {
   if (Instruction *Res = foldBitwiseLogicWithIntrinsics(I, Builder))
     return Res;
 
+  if (Instruction *Res = sinkNotIntoBitwiseOp(I))
+    return Res;
+
   return nullptr;
 }



More information about the llvm-commits mailing list