Skip to content

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

[Cranelift] fold shifts over bitwise-and (#11637)

Bongjun Jang19bb05224e39
diff --git a/cranelift/codegen/src/opts/shifts.isle b/cranelift/codegen/src/opts/shifts.isle
index 37935fa8eb..82992c26c6 100644
--- a/cranelift/codegen/src/opts/shifts.isle
+++ b/cranelift/codegen/src/opts/shifts.isle
@@ -310,3 +310,5 @@
(rule (simplify (isub ty (ishl ty x z) (ishl ty y z))) (ishl ty (isub ty x y) z))
(rule (simplify (iadd ty (ishl ty x z) (ishl ty y z))) (ishl ty (iadd ty x y) z))
+(rule (simplify (ushr ty (band ty (ishl ty x y) z) y)) (band ty x (ushr ty z y)))
+
diff --git a/cranelift/filetests/filetests/egraph/shifts2.clif b/cranelift/filetests/filetests/egraph/shifts2.clif
new file mode 100644
index 0000000000..cffc6622ae
--- /dev/null
+++ b/cranelift/filetests/filetests/egraph/shifts2.clif
@@ -0,0 +1,34 @@
+test optimize precise-output
+set opt_level=speed
+target x86_64
+
+function %fold_shifts_over_and1(i32, i32, i32) -> i32 {
+block0(v0: i32, v1: i32, v3: i32):
+ v2 = ishl v0, v1
+ v4 = band v2, v3
+ v5 = ushr v4, v1
+ return v5
+}
+
+; function %fold_shifts_over_and1(i32, i32, i32) -> i32 fast {
+; block0(v0: i32, v1: i32, v3: i32):
+; v6 = ushr v3, v1
+; v7 = band v0, v6
+; return v7
+; }
+
+function %fold_shifts_over_and2(i64, i64, i64) -> i64 {
+block0(v0: i64, v1: i64, v3: i64):
+ v2 = ishl v0, v1
+ v4 = band v2, v3
+ v5 = ushr v4, v1
+ return v5
+}
+
+; function %fold_shifts_over_and2(i64, i64, i64) -> i64 fast {
+; block0(v0: i64, v1: i64, v3: i64):
+; v6 = ushr v3, v1
+; v7 = band v0, v6
+; return v7
+; }
+
diff --git a/cranelift/filetests/filetests/runtests/shifts.clif b/cranelift/filetests/filetests/runtests/shifts.clif
index da0817f855..9ff5bbe6f2 100644
--- a/cranelift/filetests/filetests/runtests/shifts.clif
+++ b/cranelift/filetests/filetests/runtests/shifts.clif
@@ -807,3 +807,15 @@ block0(v0: i8):
return v1
}
; run: %sshr_i8_const(0x40) == 0x20
+
+function %fold_shifts_over_and1(i32, i32, i32) -> i32 {
+block0(v0: i32, v1: i32, v3: i32):
+ v2 = ishl v0, v1
+ v4 = band v2, v3
+ v5 = ushr v4, v1
+ return v5
+}
+
+; run: %fold_shifts_over_and1(0, 0, 0) == 0
+; run: %fold_shifts_over_and1(1, 31, 0x80000000) == 1
+