This is an archive of the discontinued LLVM Phabricator instance.

[InstCombine] Optimize icmp slt signum(x), 1 --> icmp slt x, 1.
ClosedPublic

Authored by sanjoy on Sep 8 2015, 1:33 PM.

Details

Summary

signum(x) is sometimes implemented as (x >> 63) | (-x >>> 63) (for
an i64 x). This change adds a pattern matcher for that pattern, and
adds an instcombine rule to optimize signum(x) s< 1.

Later, we can also consider optimizing:

icmp slt signum(x), 0 --> icmp slt x, 0
icmp sle signum(x), 1 --> true

etc.

Diff Detail

Repository
rL LLVM

Event Timeline

sanjoy updated this revision to Diff 34245.Sep 8 2015, 1:33 PM
sanjoy retitled this revision from to [InstCombine] Optimize icmp slt signum(x), 1 --> icmp sle x, 0..
sanjoy updated this object.
sanjoy added a reviewer: majnemer.
sanjoy added a subscriber: llvm-commits.
majnemer added inline comments.Sep 8 2015, 3:21 PM
include/llvm/IR/PatternMatch.h
1281–1284 ↗(On Diff #34245)

Could you use getScalarSizeInBits? My thinking is that this would enable the transform to hack on vectors of integers. The only caveat is that you need to fail if it gives you back zero, this could happen if its a vector of pointers.

sanjoy updated this revision to Diff 34295.Sep 8 2015, 9:27 PM

I changed the patternmatch to use to use getScalarSizeInBits, but
that does not work with vectors as-is since
visitICmpInstWithInstAndIntCst only looks at ConstantInts and not
ConstantVectors. I'm slightly hesitant to add untested code like
this, but given that this is at least partially tested (via the scalar
tests), I'm fine with checking this in if you are.

majnemer edited edge metadata.Sep 16 2015, 10:41 AM

Test cases seem a little bigger than they need to be. Why not just have the functions return the i1 result.

include/llvm/IR/PatternMatch.h
1289–1293 ↗(On Diff #34295)

We don't use the terminology >>> in LLVM. I think it is more common to see >>u.

sanjoy updated this revision to Diff 34913.Sep 16 2015, 12:26 PM
sanjoy edited edge metadata.
  • address David's review
sanjoy retitled this revision from [InstCombine] Optimize icmp slt signum(x), 1 --> icmp sle x, 0. to [InstCombine] Optimize icmp slt signum(x), 1 --> icmp slt x, 1..Sep 16 2015, 12:32 PM
majnemer accepted this revision.Sep 16 2015, 12:47 PM
majnemer edited edge metadata.

LGTM

This revision is now accepted and ready to land.Sep 16 2015, 12:47 PM
This revision was automatically updated to reflect the committed changes.
sanjoy marked an inline comment as done.