This is an archive of the discontinued LLVM Phabricator instance.

[InstCombine] Transform sub(sext(add(X, Y)), sext(add(X, Z))) to sub(Y, Z) given nsw adds
AcceptedPublic

Authored by dmgreen on Aug 10 2023, 3:34 AM.

Details

Summary

This adds combines for sext(X +nsw Y) - sext(X +nsw Z) -> sext(Y) - sext(Z) and zext(X +nuw Y) - zext(X +nuw Z) -> zext(Y) - zext(Z). This is especially useful when Y and Z are constants.

See https://alive2.llvm.org/ce/z/XEazaS and https://alive2.llvm.org/ce/z/kHGPtU.

Diff Detail

Event Timeline

dmgreen created this revision.Aug 10 2023, 3:34 AM
Herald added a project: Restricted Project. · View Herald TranscriptAug 10 2023, 3:34 AM
dmgreen requested review of this revision.Aug 10 2023, 3:34 AM
Herald added a project: Restricted Project. · View Herald TranscriptAug 10 2023, 3:34 AM
nikic added inline comments.Aug 10 2023, 3:41 AM
llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
2529

This assumes the common operand is on the LHS. This will be the case for constants, but may not hold for non-constants. We should handle the commuted case as well.

2532

It looks like it's legal to transfer the nsw flag to the sub here (https://alive2.llvm.org/ce/z/cYJh4x). But not in the nuw case (https://alive2.llvm.org/ce/z/jHsEcP).

llvm/test/Transforms/InstCombine/sub-ext-add.ll
3–4

Drop data layout.

5–6

Could you please change the variable names to something more meaningful?

565

Please add multi-use tests. I think this fold needs one-use checks.

nikic added inline comments.Aug 10 2023, 3:43 AM
llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
2532

Okay, I see in the tests that the nsw will get inferred anyway, so I guess there's no need to make it explicit.

dmgreen updated this revision to Diff 551909.Aug 21 2023, 12:04 AM
dmgreen marked 5 inline comments as done.

Thanks for the review. Updated for one use checks and commutivity. This might start to get stranger in a followup but this part should hopefully be sensible enough on it's own.

nikic accepted this revision.Aug 23 2023, 5:40 AM

LGTM

llvm/test/Transforms/InstCombine/sub-ext-add.ll
49

This test case looks the same as subaddnuw_c1?

This revision is now accepted and ready to land.Aug 23 2023, 5:40 AM