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

[X86] Missing use of 8-/16-bit `cmp` for comparing truncated values

Open dzaima opened this issue 6 months ago • 4 comments

Code like:

#include<stdint.h>
void ext(void);
void gt_u8(long a, long b) {
    if ((uint8_t)a > (uint8_t)b) ext();
}

compiled with -O3, compiles to:

gt_u8:
        movzx   eax, dil
        movzx   ecx, sil
        cmp     eax, ecx
        ja      ext@PLT
        ret

but could compile to:

gt_u8:
        cmp     dil, sil
        ja      ext@PLT
        ret

This applies to 8-bit and 16-bit types, and both > and >=.

Also happens with one arg being an immediate (though for the 16-bit case that may be actually undesirable due to slow data16).

https://c.godbolt.org/z/9hKc6shfc

dzaima avatar May 10 '26 18:05 dzaima

Hi, I'd like to work on this.

he-weiwen avatar May 10 '26 18:05 he-weiwen

@llvm/issue-subscribers-backend-x86

Author: dzaima (dzaima)

Code like:
#include&lt;stdint.h&gt;
void ext(void);
void gt_u8(long a, long b) {
    if ((uint8_t)a &gt; (uint8_t)b) ext();
}

compiled with -O3, compiles to:

gt_u8:
        movzx   eax, dil
        movzx   ecx, sil
        cmp     eax, ecx
        ja      ext@<!-- -->PLT
        ret

but could compile to:

gt_u8:
        cmp     dil, sil
        ja      ext@<!-- -->PLT
        ret

This applies to 8-bit and 16-bit types, and both &gt; and &gt;=.

Also happens with one arg being an immediate (though for the 16-bit case that may be actually undesirable due to slow data16).

https://c.godbolt.org/z/9hKc6shfc

Related #195907

GkvJwa avatar May 11 '26 07:05 GkvJwa

Maybe this should be done in instcombine? https://alive2.llvm.org/ce/z/wfVKcc

aengelke avatar May 11 '26 10:05 aengelke