Skip to content

Improve the SBB trick.

Rika requested to merge runewalsh/source:sbb into main

Fixes #40214 (closed) and improves the trick used by GCC for if (a != b) return 2 * (a > b) - 1;. GCC compiled it as

cmp b, a      ; carry = 1 if b < a, else 0
je  .GoOn
sbb rax, rax  ; rax = -1 if b < a, else 0
and rax, 2    ; rax = 2 if b < a, else 0
sub rax, 1    ; rax = 1 if b < a, else -1
ret
.GoOn:

but glibc’s memcmp versions use more clever

cmp a, b      ; carry = 1 if a < b, else 0
je  .GoOn
sbb rax, rax  ; rax = -1 if a < b, else 0
or  rax, 1    ; rax = -1 if a < b, else 1
ret
.GoOn:
Edited by Rika

Merge request reports