Skip to content

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

[Cranelift] `(x - y) - x => -y` (#11995)

Bongjun Jangb58cd171c75a
diff --git a/cranelift/codegen/src/opts/arithmetic.isle b/cranelift/codegen/src/opts/arithmetic.isle
index b6c3e00aa8..c728946ff2 100644
--- a/cranelift/codegen/src/opts/arithmetic.isle
+++ b/cranelift/codegen/src/opts/arithmetic.isle
@@ -343,3 +343,7 @@
;; (x + y) - y --> x
(rule (simplify (isub ty (iadd ty x y) x)) y)
(rule (simplify (isub ty (iadd ty x y) y)) x)
+
+;; (x - y) - x => -y
+(rule (simplify (isub ty (isub ty x y) x))(ineg ty y))
+
diff --git a/cranelift/filetests/filetests/egraph/arithmetic.clif b/cranelift/filetests/filetests/egraph/arithmetic.clif
index e45a7e1b84..52d71173a4 100644
--- a/cranelift/filetests/filetests/egraph/arithmetic.clif
+++ b/cranelift/filetests/filetests/egraph/arithmetic.clif
@@ -403,3 +403,15 @@ block0(v0: i32, v1: i32):
; check: v5 = ishl v0, v1
; check: return v5
}
+
+
+;; (x - y) - x => -y
+function %simplify_sub_sub_self(i32, i32) -> i32 {
+block0(v0: i32, v1: i32):
+ v2 = isub v0, v1 ; x - y
+ v3 = isub v2, v0 ; (x - y) - x
+ return v3
+ ; check: v4 = ineg v1
+ ; check: return v4
+}
+
diff --git a/cranelift/filetests/filetests/runtests/arithmetic.clif b/cranelift/filetests/filetests/runtests/arithmetic.clif
index 9c74c1da19..581cc5e96b 100644
--- a/cranelift/filetests/filetests/runtests/arithmetic.clif
+++ b/cranelift/filetests/filetests/runtests/arithmetic.clif
@@ -598,3 +598,13 @@ block0(v0: i32, v1: i32):
; run: %fold_add_sub3(0xdead0000, 0x0000beef) == 0xdead0000
+;; (x - y) - x => -y
+function %simplify_sub_sub_self(i32, i32) -> i32 {
+block0(v0: i32, v1: i32):
+ v2 = isub v0, v1 ; x - y
+ v3 = isub v2, v0 ; (x - y) - x
+ return v3
+}
+
+; run: %simplify_sub_sub_self(42, 5) == -5
+