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

via llvm-commits llvm-commits at lists.llvm.org
Mon Nov 13 06:40:17 PST 2023


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

>From 192489c7bf869d639dc052fc72cda227d4cc30ec 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      |  4 ++
 llvm/test/Transforms/InstCombine/div.ll       | 41 +++++++++++++++++++
 2 files changed, 45 insertions(+)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
index db0804380855e3a..c2c439d33d24be2 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineMulDivRem.cpp
@@ -1544,6 +1544,10 @@ Instruction *InstCombinerImpl::visitSDiv(BinaryOperator &I) {
     }
   }
 
+  // -(X * Y) / (X * Y) --> -1
+  if (isKnownNegation(Op0,Op1,true)) {
+    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