llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[X86] Reuse sub flags for conditional subtraction x - (x >= q ? q : 0)

Open chfast opened this issue 2 months ago • 2 comments

x >= q ? x - q : x is canonicalized by InstCombine to x - (x < q ? 0 : q), which X86 lowers to xor + cmp + cmov + sub. The equivalent select of the difference is lowered to sub + cmov, reusing the flags of the sub.

The same was done for AArch64 in #223391.

https://godbolt.org/z/PWYE5fK9Y

unsigned long cond_sub(unsigned long x, unsigned long q) { return x >= q ? x - q : x; }
define i64 @sel_zero(i64 %x, i64 %q) {
  %c = icmp ult i64 %x, %q
  %s = select i1 %c, i64 0, i64 %q
  %r = sub i64 %x, %s
  ret i64 %r
}

define i64 @sel_diff(i64 %x, i64 %q) {
  %c = icmp ult i64 %x, %q
  %d = sub i64 %x, %q
  %r = select i1 %c, i64 %x, i64 %d
  ret i64 %r
}

llc -O2:

sel_zero:
        movq    %rdi, %rax
        xorl    %ecx, %ecx
        cmpq    %rsi, %rdi
        cmovaeq %rsi, %rcx
        subq    %rcx, %rax
        retq

sel_diff:
        movq    %rdi, %rax
        subq    %rsi, %rax
        cmovbq  %rdi, %rax
        retq

The other conditions and the i32 cases from llvm/test/CodeGen/AArch64/conditional-subtract.ll look the same on X86.

Reproduces with LLVM 23.0.0 (090308199b30) and trunk (eb7c25df7553).

chfast avatar Oct 01 '26 12:10 chfast

@llvm/issue-subscribers-backend-x86

Author: Paweł Bylica (chfast)

`x >= q ? x - q : x` is canonicalized by InstCombine to `x - (x < q ? 0 : q)`, which X86 lowers to `xor` + `cmp` + `cmov` + `sub`. The equivalent `select` of the difference is lowered to `sub` + `cmov`, reusing the flags of the `sub`.

The same was done for AArch64 in #223391.

https://godbolt.org/z/PWYE5fK9Y

unsigned long cond_sub(unsigned long x, unsigned long q) { return x &gt;= q ? x - q : x; }
define i64 @<!-- -->sel_zero(i64 %x, i64 %q) {
  %c = icmp ult i64 %x, %q
  %s = select i1 %c, i64 0, i64 %q
  %r = sub i64 %x, %s
  ret i64 %r
}

define i64 @<!-- -->sel_diff(i64 %x, i64 %q) {
  %c = icmp ult i64 %x, %q
  %d = sub i64 %x, %q
  %r = select i1 %c, i64 %x, i64 %d
  ret i64 %r
}

llc -O2:

sel_zero:
        movq    %rdi, %rax
        xorl    %ecx, %ecx
        cmpq    %rsi, %rdi
        cmovaeq %rsi, %rcx
        subq    %rcx, %rax
        retq

sel_diff:
        movq    %rdi, %rax
        subq    %rsi, %rax
        cmovbq  %rdi, %rax
        retq

The other conditions and the i32 cases from llvm/test/CodeGen/AArch64/conditional-subtract.ll look the same on X86.

Reproduces with LLVM 23.0.0 (090308199b30) and trunk (eb7c25df7553).

Hi, I would like to work on this issue. Could you assign it to me?

ChrisLee02 avatar Oct 04 '26 07:10 ChrisLee02