Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

[Cranelift] `(x | y) ^ (x & y) --> (x ^ y)` (#11527)

Bongjun Jang73b1e317f11d
diff --git a/cranelift/codegen/src/opts/bitops.isle b/cranelift/codegen/src/opts/bitops.isle
index a1a4a99124..b3069ca34e 100644
--- a/cranelift/codegen/src/opts/bitops.isle
+++ b/cranelift/codegen/src/opts/bitops.isle
@@ -189,3 +189,5 @@
(iconst_u ty 0xff00))
(ushr ty x (iconst_u ty 56))))))
(bswap ty x))
+
+(rule (simplify (bxor ty (bor ty x y) (band ty x y))) (bxor ty x y))
diff --git a/cranelift/filetests/filetests/egraph/bitops.clif b/cranelift/filetests/filetests/egraph/bitops.clif
index 93ddafec4e..62fc056bba 100644
--- a/cranelift/filetests/filetests/egraph/bitops.clif
+++ b/cranelift/filetests/filetests/egraph/bitops.clif
@@ -412,3 +412,33 @@ block0(v0: i8, v1: i8):
; check: v5 = bor v0, v1
; check: return v5
}
+
+function %test_bxor_bor_band_i64(i64, i64) -> i64 {
+block0(v0: i64, v1: i64):
+ v2 = bor v0, v1
+ v3 = band v0, v1
+ v4 = bxor v2, v3
+ return v4
+ ; check: v5 = bxor v0, v1
+ ; check: return v5
+}
+
+function %test_bxor_bor_band_i32(i32, i32) -> i32 {
+block0(v0: i32, v1: i32):
+ v2 = bor v0, v1
+ v3 = band v0, v1
+ v4 = bxor v2, v3
+ return v4
+ ; check: v5 = bxor v0, v1
+ ; check: return v5
+}
+
+function %test_bxor_bor_band_i16(i16, i16) -> i16 {
+block0(v0: i16, v1: i16):
+ v2 = bor v0, v1
+ v3 = band v0, v1
+ v4 = bxor v2, v3
+ return v4
+ ; check: v5 = bxor v0, v1
+ ; check: return v5
+}
diff --git a/cranelift/filetests/filetests/runtests/bitops.clif b/cranelift/filetests/filetests/runtests/bitops.clif
index 1757c870df..381e1996c4 100644
--- a/cranelift/filetests/filetests/runtests/bitops.clif
+++ b/cranelift/filetests/filetests/runtests/bitops.clif
@@ -111,3 +111,18 @@ block0(v0: i64, v1: i64):
return v4
}
; run: %a64_extr_i64_12_swap(0x0102_0304_0506_0708, 0x090a_0b0c_0d0e_0f00) == 0x708_090a_0b0c_0d0e_0
+
+;; (x | y) ^ (x & y) is optimized to (x ^ y)
+function %test_bxor_bor_band_i64(i64, i64) -> i64 {
+block0(v0: i64, v1: i64):
+ v2 = bor v0, v1
+ v3 = band v0, v1
+ v4 = bxor v2, v3
+ return v4
+}
+
+; run: %test_bxor_bor_band_i64(0, 0) == 0
+; run: %test_bxor_bor_band_i64(0, 1) == 1
+; run: %test_bxor_bor_band_i64(1, 0) == 1
+; run: %test_bxor_bor_band_i64(1, 1) == 0
+; run: %test_bxor_bor_band_i64(7879, 7879) == 0