[Mlir-commits] [mlir] 8761f5e - [mlir][Support] Avoid multiplication in floorDiv / ceilDiv

Stephan Herhut llvmlistbot at llvm.org
Tue Dec 21 02:51:03 PST 2021


Author: Stephan Herhut
Date: 2021-12-21T11:50:40+01:00
New Revision: 8761f5ebf754fbcedb25c023c30492e60ff3c19d

URL: https://github.com/llvm/llvm-project/commit/8761f5ebf754fbcedb25c023c30492e60ff3c19d
DIFF: https://github.com/llvm/llvm-project/commit/8761f5ebf754fbcedb25c023c30492e60ff3c19d.diff

LOG: [mlir][Support] Avoid multiplication in floorDiv / ceilDiv

Using comparisons instead avoids potential overflow.

Differential Revision: https://reviews.llvm.org/D116096

Added: 
    

Modified: 
    mlir/include/mlir/Support/MathExtras.h
    mlir/unittests/Support/MathExtrasTest.cpp

Removed: 
    


################################################################################
diff  --git a/mlir/include/mlir/Support/MathExtras.h b/mlir/include/mlir/Support/MathExtras.h
index 622a7d33480c4..ca1d431c9718f 100644
--- a/mlir/include/mlir/Support/MathExtras.h
+++ b/mlir/include/mlir/Support/MathExtras.h
@@ -24,7 +24,8 @@ inline int64_t ceilDiv(int64_t lhs, int64_t rhs) {
   assert(rhs != 0);
   // C/C++'s integer division rounds towards 0.
   int64_t x = (rhs > 0) ? -1 : 1;
-  return (lhs * rhs > 0) ? ((lhs + x) / rhs) + 1 : -(-lhs / rhs);
+  return ((lhs != 0) && (lhs > 0) == (rhs > 0)) ? ((lhs + x) / rhs) + 1
+                                                : -(-lhs / rhs);
 }
 
 /// Returns the result of MLIR's floordiv operation on constants. The RHS is
@@ -33,7 +34,8 @@ inline int64_t floorDiv(int64_t lhs, int64_t rhs) {
   assert(rhs != 0);
   // C/C++'s integer division rounds towards 0.
   int64_t x = (rhs < 0) ? 1 : -1;
-  return (lhs * rhs < 0) ? -((-lhs + x) / rhs) - 1 : lhs / rhs;
+  return ((lhs != 0) && ((lhs < 0) != (rhs < 0))) ? -((-lhs + x) / rhs) - 1
+                                                  : lhs / rhs;
 }
 
 /// Returns MLIR's mod operation on constants. MLIR's mod operation yields the

diff  --git a/mlir/unittests/Support/MathExtrasTest.cpp b/mlir/unittests/Support/MathExtrasTest.cpp
index 304b353d4167d..6ece2dc560837 100644
--- a/mlir/unittests/Support/MathExtrasTest.cpp
+++ b/mlir/unittests/Support/MathExtrasTest.cpp
@@ -17,6 +17,8 @@ TEST(MathExtrasTest, CeilDivTest) {
   EXPECT_THAT(ceilDiv(14, -3), Eq(-4));
   EXPECT_THAT(ceilDiv(-14, -3), Eq(5));
   EXPECT_THAT(ceilDiv(-14, 3), Eq(-4));
+  EXPECT_THAT(ceilDiv(0, 3), Eq(0));
+  EXPECT_THAT(ceilDiv(0, -3), Eq(0));
 }
 
 TEST(MathExtrasTest, FloorDivTest) {
@@ -24,4 +26,6 @@ TEST(MathExtrasTest, FloorDivTest) {
   EXPECT_THAT(floorDiv(14, -3), Eq(-5));
   EXPECT_THAT(floorDiv(-14, -3), Eq(4));
   EXPECT_THAT(floorDiv(-14, 3), Eq(-5));
+  EXPECT_THAT(floorDiv(0, 3), Eq(0));
+  EXPECT_THAT(floorDiv(0, -3), Eq(0));
 }


        


More information about the Mlir-commits mailing list