llvm/llvm-project

[x86][armv8] Failure to use flag in unsigned underflow compare idiom

Open

#161.036 geöffnet am 28. Sept. 2025

Auf GitHub ansehen
 (14 Kommentare) (0 Reaktionen) (1 zugewiesene Person)C++ (10.782 Forks)batch import
good first issuellvm:SelectionDAGmissed-optimization

Repository-Metriken

Stars
 (26.378 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 1T 2h) (1.000 gemergte PRs in 30 T)

Beschreibung

It is a common idiom to check for unsigned underflow by doing a greater than compare between the difference and minuend:

#include <stdint.h>

uint64_t subIfNoUnderflow_clang(uint64_t a, uint64_t b) {
    uint64_t diff = a - b;
    return (diff > a)? a : diff;
}

Instead of using the carry flag, which is set by the subtraction, clang emits a compare instruction:

https://godbolt.org/z/ex5554M6P

subIfNoUnderflow_clang:
        mov     rax, rdi
        sub     rax, rsi
        cmp     rax, rdi
        cmovae  rax, rdi
        ret

Ideally it should produce:

subIfNoUnderflow_ideal:
        mov     rax, rdi
        sub     rax, rsi
        cmovb   rax, rdi
        ret

Related issues

#53432 #62696 #73847

Contributor Guide