[llvm] [APInt] Add APIntOps::absdiff to compute the absolute difference of 2 unsigned values (PR #82255)
via llvm-commits
llvm-commits at lists.llvm.org
Mon Feb 19 07:23:23 PST 2024
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-llvm-adt
Author: Simon Pilgrim (RKSimon)
<details>
<summary>Changes</summary>
Equivalent to "umax(A, B) - umin(A, B)"
First step towards adding knownbits support for absdiff patterns for #<!-- -->81765
---
Full diff: https://github.com/llvm/llvm-project/pull/82255.diff
2 Files Affected:
- (modified) llvm/include/llvm/ADT/APInt.h (+5)
- (modified) llvm/unittests/ADT/APIntTest.cpp (+34)
``````````diff
diff --git a/llvm/include/llvm/ADT/APInt.h b/llvm/include/llvm/ADT/APInt.h
index 6f2f25548cc84b..ef7e1878f303ba 100644
--- a/llvm/include/llvm/ADT/APInt.h
+++ b/llvm/include/llvm/ADT/APInt.h
@@ -2187,6 +2187,11 @@ inline const APInt &umax(const APInt &A, const APInt &B) {
return A.ugt(B) ? A : B;
}
+/// Determine the absolute difference of two APInts considered to be unsigned.
+inline const APInt absdiff(const APInt &A, const APInt &B) {
+ return umax(A, B) - umin(A, B);
+}
+
/// Compute GCD of two unsigned APInt values.
///
/// This function returns the greatest common divisor of the two APInt values
diff --git a/llvm/unittests/ADT/APIntTest.cpp b/llvm/unittests/ADT/APIntTest.cpp
index 3b909f8f7d14e2..2fe59f05ca753a 100644
--- a/llvm/unittests/ADT/APIntTest.cpp
+++ b/llvm/unittests/ADT/APIntTest.cpp
@@ -2497,6 +2497,40 @@ TEST(APIntTest, clearLowBits) {
EXPECT_EQ(16u, i32hi16.popcount());
}
+TEST(APIntTest, AbsDiff) {
+ using APIntOps::absdiff;
+
+ APInt MaxU1(1, 1, false);
+ APInt MinU1(1, 0, false);
+ EXPECT_EQ(1u, absdiff(MaxU1, MinU1).getZExtValue());
+ EXPECT_EQ(1u, absdiff(MinU1, MaxU1).getZExtValue());
+
+ APInt MaxU4(4, 15, false);
+ APInt MinU4(4, 0, false);
+ EXPECT_EQ(15u, absdiff(MaxU4, MinU4).getZExtValue());
+ EXPECT_EQ(15u, absdiff(MinU4, MaxU4).getZExtValue());
+
+ APInt MaxS8(8, 127, true);
+ APInt MinS8(8, -128, true);
+ EXPECT_EQ(1u, absdiff(MaxS8, MinS8).getZExtValue());
+ EXPECT_EQ(1u, absdiff(MinS8, MaxS8).getZExtValue());
+
+ APInt MaxU16(16, 65535, false);
+ APInt MinU16(16, 0, false);
+ EXPECT_EQ(65535u, absdiff(MaxU16, MinU16).getZExtValue());
+ EXPECT_EQ(65535u, absdiff(MinU16, MaxU16).getZExtValue());
+
+ APInt MaxS16(16, 32767, true);
+ APInt MinS16(16, -32768, true);
+ APInt ZeroS16(16, 0, true);
+ EXPECT_EQ(1u, absdiff(MaxS16, MinS16).getZExtValue());
+ EXPECT_EQ(1u, absdiff(MinS16, MaxS16).getZExtValue());
+ EXPECT_EQ(32768u, absdiff(ZeroS16, MinS16));
+ EXPECT_EQ(32768u, absdiff(MinS16, ZeroS16));
+ EXPECT_EQ(32767u, absdiff(ZeroS16, MaxS16));
+ EXPECT_EQ(32767u, absdiff(MaxS16, ZeroS16));
+}
+
TEST(APIntTest, GCD) {
using APIntOps::GreatestCommonDivisor;
``````````
</details>
https://github.com/llvm/llvm-project/pull/82255
More information about the llvm-commits
mailing list