This is an archive of the discontinued LLVM Phabricator instance.

[InstCombine] Don't propagate nsw for A*B+A*C => A*(B+C).
ClosedPublic

Authored by sanjoy on May 8 2015, 4:22 PM.

Details

Summary

InstCombine transform A *nsw B +nsw A *nsw C to A *nsw (B + C).
This is incorrect -- e.g. if A = -1, B = 1, C = INT_SMAX. Then
nothing in the LHS overflows, but the multiplication in RHS overflows.

I'll have to admit that this proposed fix is a bit heavy-handed -- if
you think this will materially affect optimization then we can try to do
this transform for cases where we can prove correctness. For instance,
I *think* (but have not proved) that we can transform `(A +nsw A) +nsw
A` to A *nsw 3.

Diff Detail

Repository
rL LLVM

Event Timeline

sanjoy updated this revision to Diff 25386.May 8 2015, 4:22 PM
sanjoy retitled this revision from to [InstCombine] Don't propagate nsw for A*B+A*C => A*(B+C)..
sanjoy updated this object.
sanjoy edited the test plan for this revision. (Show Details)
sanjoy added reviewers: majnemer, IlyaKrotov.
sanjoy added a subscriber: Unknown Object (MLST).
majnemer added inline comments.May 8 2015, 11:28 PM
test/Transforms/InstCombine/add2.ll
209–213 ↗(On Diff #25386)

This transform is correct, would it be hard to keep it from breaking?

218–222 ↗(On Diff #25386)

Yep. This transform would give us back poison if '8' were replaced with '32767'. However, it is safe to do (%x *nsw C) + %x => %x *nsw (C+1) if we know that (C != ((1 << (width(%x) - 1)) - 1))

246–261 ↗(On Diff #25386)

A *nsw B+A *nsw C => A *nsw (B+C) is safe when ((B + C) != -(1 << (width(%a) - 1))) How hard would this be to implement?

sanjoy added inline comments.May 11 2015, 11:17 AM
test/Transforms/InstCombine/add2.ll
209–213 ↗(On Diff #25386)

No, it won't be hard.

I have to admit I was lazier than usual when making this change. I'll send in a more aggressive version soon.

246–261 ↗(On Diff #25386)

How hard would this be to implement?

I guess we can just ask ValueTracking on what the constraints on the values feeding in to the expression are. I'm not sure how effective ValueTracking will be at discovering these ranges though, in practice.

This revision was automatically updated to reflect the committed changes.