Skip to content
Permalink
Browse files

cmd/compile: optimize signed n % c == 0

While we're here, also convert a - b == 0 to a == b.

Fixes golang#15806

Change-Id: I41f6f154cb9607d335a79542e05c2e19ce10f3dc
  • Loading branch information...
josharian committed May 10, 2017
1 parent 7b7a854 commit fff2bf7fe35a5177a02a9cf5431b83f2b6689961
Showing with 16 additions and 0 deletions.
  1. +16 −0 src/cmd/compile/internal/ssa/gen/generic.rules
@@ -1072,6 +1072,22 @@
(Mod64u <t> x (Const64 [c])) && x.Op != OpConst64 && c > 0 && umagicOK(64,c)
-> (Sub64 x (Mul64 <t> (Div64u <t> x (Const64 <t> [c])) (Const64 <t> [c])))

// Signed x % c == 0 is special, since we don't care whether x % c is negative or positive.
// Rewrite it to unsigned x % c == 0, which is much more efficient to compute. Issue 15806.
// Unfortunately, we don't get an opportunity to see these before the Mod gets rewritten,
// (see https://github.com/golang/go/issues/19013#issuecomment-278756847),
// so instead of matching (Eq (Mod x y) (Const [0])), match the expanded expression.
(Eq8 z:(Const8 [0]) (Sub8 x (Mul8 <t> d:(Div8 x (Const8 [c])) (Const8 <t> [c])))) && d.Uses == 1
-> (Eq8 z (Mod8u <t.ToUnsigned()> x (Const8 <t> [c])))
(Eq16 z:(Const16 [0]) (Sub16 x (Mul16 <t> d:(Div16 x (Const16 [c])) (Const16 <t> [c])))) && d.Uses == 1
-> (Eq16 z (Mod16u <t.ToUnsigned()> x (Const16 <t> [c])))
(Eq32 z:(Const32 [0]) (Sub32 x (Mul32 <t> d:(Div32 x (Const32 [c])) (Const32 <t> [c])))) && d.Uses == 1
-> (Eq32 z (Mod32u <t.ToUnsigned()> x (Const32 <t> [c])))
(Eq64 z:(Const64 [0]) (Sub64 x (Mul64 <t> d:(Div64 x (Const64 [c])) (Const64 <t> [c])))) && d.Uses == 1
-> (Eq64 z (Mod64u <t.ToUnsigned()> x (Const64 <t> [c])))

// These Eq and Neq simplifications are delayed because they must
// occur after the signed x % c == 0 optimization.
(Eq(8|16|32|64) s:(Sub(8|16|32|64) x y) (Const(8|16|32|64) [0])) && s.Uses == 1 -> (Eq(8|16|32|64) x y)
(Neq(8|16|32|64) s:(Sub(8|16|32|64) x y) (Const(8|16|32|64) [0])) && s.Uses == 1 -> (Neq(8|16|32|64) x y)

0 comments on commit fff2bf7

Please sign in to comment.
You can’t perform that action at this time.