Skip to content

Optimize comparisons of adjusted values #5008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
kripken opened this issue Sep 2, 2022 · 4 comments
Open

Optimize comparisons of adjusted values #5008

kripken opened this issue Sep 2, 2022 · 4 comments
Assignees

Comments

@kripken
Copy link
Member

kripken commented Sep 2, 2022

E.g.

  (i32.gt_u
   (i32.shr_u
    (local.get $0)
    (i32.const 1)
   )
   (i32.const 100)
  )
 =->
  (i32.gt_u
   (local.get $0)
   (i32.const 201)
  )

Instead of dividing by 2 and then comparing, we can compare the original value.

More variations: add a constant, or both add and multiply/divide.

Found by the superoptimizer #4994 (for comparison to other findings: rule #8, benefit 30492).

@kripken
Copy link
Member Author

kripken commented Sep 2, 2022

Another example from rule #10:

(i32.lt_s
 (i32.shr_s
  (local.get $0)
  (i32.const 1)
 )
 (i32.const 12)
)
 =->
(i32.lt_s
 (local.get $0)
 (i32.const 24)
)

@kripken
Copy link
Member Author

kripken commented Sep 2, 2022

This also happens with floats, though there we may need fast-math, e.g.

(f32.ge
 (f32.add
  (local.get $0)
  (f32.const -9.99999993922529e-09)
 )
 (f32.const 0)
)
 =->
(f32.gt
 (local.get $0)
 (f32.const 9.99999905104687e-09)
)

(rule #21)

@kripken
Copy link
Member Author

kripken commented Sep 6, 2022

Another example:

 (i32.gt_u
  (i32.add
   (i32.shr_u
    (local.get $0)
    (i32.const 1)
   )
   (i32.const 8)
  )
  (i32.const 65535)
 )

The add's left operand is less than 32 bits, so it cannot overflow even with an added 8, and so x + 8 >= 65535 can be turned into x >= 65527.

edit: This and related things seem to be the top superoptimizer finding for Java and Dart, followed by #5008 (comment)

@kripken kripken self-assigned this Sep 9, 2022
kripken added a commit that referenced this issue Sep 9, 2022
E.g.

x + C1 > C2  ==>  x > (C2-C1)

We do need to be careful of overflows in either the add on the left or
the proposed subtract on the right. In the latter case, we can at least do

x + C1 > C2  ==>  x + (C1-C2) > 0

Helps #5008 (but more patterns remain).

Found by the superoptimizer #4994. This was the top suggestion for Java and Dart.
@kripken
Copy link
Member Author

kripken commented Sep 13, 2022

All comparisons <, >=, etc should be handled with +. That leaves things like shifts, and float operations, as mentioned above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant