[llvm] [InstCombine] Simplification for (-a * b) / (a * b) and (a - b) / (b - a). (PR #71768)

via llvm-commits llvm-commits at lists.llvm.org
Mon Nov 13 04:02:15 PST 2023


https://github.com/Z572 updated https://github.com/llvm/llvm-project/pull/71768

>From c467c7533a56d5546b46fb4cd8f9c8a106f43a96 Mon Sep 17 00:00:00 2001
From: Zheng Junjie <zhengjunjie at iscas.ac.cn>
Date: Wed, 8 Nov 2023 11:25:15 +0800
Subject: [PATCH] [InstCombine] Simplification for (-a * b) / (a * b)

---
 .../InstCombine/InstCombineMulDivRem.cpp      |  7 ++++
 llvm/test/Transforms/InstCombine/div.ll       | 41 +++++++++++++++++++
 2 files changed, 48 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
index db0804380855e3a..7780d478f0f2edf 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
@@ -1544,6 +1544,13 @@ Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) {
     }
   }
 
+  // -(X * Y) / (X * Y) --> -1
+  if ((match(Op0, m_NSWNeg(m_c_Mul(m_Value(X), m_Value(Y)))) &&
+       match(Op1, m_c_Mul(m_Specific(X), m_Specific(Y)))) ||
+      (match(Op0, m_Mul(m_Value(X), m_Value(Y))) &&
+       match(Op1, m_NSWNeg(m_c_Mul(m_Specific(X), m_Specific(Y)))))) {
+    return replaceInstUsesWith(I, ConstantInt::getAllOnesValue(Ty));
+  };
   return nullptr;
 }
 
diff --git a/llvm/test/Transforms/InstCombine/div.ll b/llvm/test/Transforms/InstCombine/div.ll
index 1f0081befb07dba..70d570a70562405 100644
--- a/llvm/test/Transforms/InstCombine/div.ll
+++ b/llvm/test/Transforms/InstCombine/div.ll
@@ -1432,6 +1432,47 @@ define <2 x i8> @sdiv_sdiv_mul_nsw(<2 x i8> %x, <2 x i8> %y, <2 x i8> %z) {
   ret <2 x i8> %r
 }
 
+; -(X * Y) / (X * Y) --> -1
+define i32 @sdiv_neg_mul_mul(i32 %0, i32 %1) {
+; CHECK-LABEL: @sdiv_neg_mul_mul(
+; CHECK-NEXT:    ret i32 -1
+  %3 = mul nsw i32 %1, %0
+  %4 = sub nsw i32 0, %3
+  %5 = sdiv i32 %4, %3
+  ret i32 %5
+}
+
+define i32 @sdiv_neg_mul_mul2(i32 %x, i32 %y) {
+; CHECK-LABEL: @sdiv_neg_mul_mul2(
+; CHECK-NEXT:    [[M:%.*]] = mul i32 [[Y:%.*]], [[X:%.*]]
+; CHECK-NEXT:    [[D:%.*]] = sub i32 0, [[M:%.*]]
+; CHECK-NEXT:    [[R:%.*]] = sdiv i32 [[D:%.*]], [[M:%.*]]
+; CHECK-NEXT:    ret i32 [[R:%.*]]
+  %m = mul i32 %y, %x
+  %d = sub i32 0, %m
+  %r = sdiv i32 %d, %m
+  ret i32 %r
+}
+
+; (X * Y) / -(X * Y) --> -1
+define i32 @sdiv_mul_neg_mul(i32 %x, i32 %y) {
+; CHECK-LABEL: @sdiv_mul_neg_mul(
+; CHECK-NEXT:    ret i32 -1
+  %m = mul i32 %y, %x
+  %n = sub nsw i32 0, %m
+  %d = sdiv i32 %m, %n
+  ret i32 %d
+}
+
+define i32 @sdiv_mul_neg_mul2(i32 %x, i32 %y) {
+; CHECK-LABEL: @sdiv_mul_neg_mul2(
+; CHECK-NEXT:    ret i32 -1
+  %m = mul nsw i32 %y, %x
+  %n = sub nsw i32 0, %m
+  %d = sdiv i32 %m, %n
+  ret i32 %d
+}
+
 ; exact propagates
 
 define i8 @sdiv_sdiv_mul_nsw_exact_exact(i8 %x, i8 %y, i8 %z) {



More information about the llvm-commits mailing list