[llvm] [llvm][Transforms] Reduce the expression (a^c1)&(a^c2) to zero, if possible (PR #76637)

via llvm-commits llvm-commits at lists.llvm.org
Sat Dec 30 13:49:38 PST 2023


https://github.com/ChipsSpectre created https://github.com/llvm/llvm-project/pull/76637

Changes the InstCombine pass of the LLVM optimizer, such that the aforementioned expression is reduced to zero if c2==~c1.

Fixes: https://github.com/llvm/llvm-project/issues/75692.

>From be993cda7b5f05125e8782fea8d0d7b20e9428cc Mon Sep 17 00:00:00 2001
From: ChipsSpectre <maximilian.hornung at tum.de>
Date: Sat, 30 Dec 2023 22:26:51 +0100
Subject: [PATCH] [llvm][Transforms] Reduce the expression (a^c1)&(a^c2) to
 zero, if possible.

Changes the InstCombine pass of the LLVM optimizer, such that the
aforementioned expression is reduced to zero if c2==~c1.

Fixes: https://github.com/llvm/llvm-project/issues/75692.
---
 .../Transforms/InstCombine/InstCombineAndOrXor.cpp    |  7 +++++++
 llvm/test/Transforms/InstCombine/and-xor-merge.ll     | 11 +++++++++++
 2 files changed, 18 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
index c03f50d75814d8..a2e614998c4795 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAndOrXor.cpp
@@ -2553,6 +2553,13 @@ Instruction *InstCombinerImpl::visitAnd(BinaryOperator &I) {
     if (match(Op1, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
         match(Op0, m_c_Xor(m_Specific(A), m_Specific(B))))
       return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
+
+    ConstantInt *C1, *C2;
+    // (A ^ C1) & (A ^ C2) -> -1, if and only if C1 is inverted value of C2.
+    if (match(Op0, m_c_Xor(m_Value(A), m_ConstantInt(C1))) &&
+        match(Op1, m_c_Xor(m_Specific(A), m_ConstantInt(C2))) &&
+        C1->getValue() == ~C2->getValue())
+      return replaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
   }
 
   {
diff --git a/llvm/test/Transforms/InstCombine/and-xor-merge.ll b/llvm/test/Transforms/InstCombine/and-xor-merge.ll
index 543336468ff0a6..22c5a6737a55f4 100644
--- a/llvm/test/Transforms/InstCombine/and-xor-merge.ll
+++ b/llvm/test/Transforms/InstCombine/and-xor-merge.ll
@@ -40,3 +40,14 @@ define i32 @PR38781(i32 %a, i32 %b) {
   %and = and i32 %b.lobit.not, %a.lobit.not
   ret i32 %and
 }
+
+; (a ^ 4) & (a ^ ~4) -> 0
+define i32 @PR75692(i32 %x) {
+; CHECK-LABEL: @PR75692
+; CHECK-NEXT:  ret i32 0
+;
+  %t2 = xor i32 %x, 4
+  %t3 = xor i32 %x, -5
+  %t4 = and i32 %t2, %t3
+  ret i32 %t4
+}



More information about the llvm-commits mailing list