[InstCombine] reduce icmp(ashr X, C1), C2 to sign-bit test
authorSanjay Patel <spatel@rotateright.com>
Mon, 11 Jan 2021 20:36:22 +0000 (15:36 -0500)
committerSanjay Patel <spatel@rotateright.com>
Mon, 11 Jan 2021 20:53:39 +0000 (15:53 -0500)
commit288f3fc5dfee0c51fc00fe10a985f93c505073eb
tree5d2c53d3d5e32eac771fd3f1c614f9a722aab0fc
parent110775809ad114e190132290657a86b2c292a878
[InstCombine] reduce icmp(ashr X, C1), C2 to sign-bit test

This is a more basic pattern that we should handle before trying to solve:
https://llvm.org/PR48640

There might be a better way to think about this because the pre-condition
that I came up with (number of sign bits in the compare constant) misses a
potential transform for each of ugt and ult as commented on in the test file.

Tried to model this is in Alive:
https://rise4fun.com/Alive/juX1
...but I couldn't get the ComputeNumSignBits() pre-condition to work as
expected, so replaced with leading 0/1 preconditions instead.

  Name: ugt
  Pre: countLeadingZeros(C2) <= C1 && countLeadingOnes(C2) <= C1
  %a = ashr %x, C1
  %r = icmp ugt i8 %a, C2
    =>
  %r = icmp slt i8 %x, 0

  Name: ult
  Pre: countLeadingZeros(C2) <= C1 && countLeadingOnes(C2) <= C1
  %a = ashr %x, C1
  %r = icmp ult i4 %a, C2
    =>
  %r = icmp sgt i4 %x, -1

Also approximated in Alive2:
https://alive2.llvm.org/ce/z/u5hCcz
https://alive2.llvm.org/ce/z/__szVL

Differential Revision: https://reviews.llvm.org/D94014
llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
llvm/test/Transforms/InstCombine/icmp-shr.ll