Compiler should optimize some comparisons with -1
by 'lagprogramming`.
The compiler should optimize some comparisons with -1 the same way it optimizes the comparisons with 0 and 1. With other words, if result>-1 should produce a code as efficient as if result>=0, and if result<=-1 should produce a code as efficient as if result<0. It should be trivial for FPC developers to complete these near-zero optimizations.
function foo(const param:sizeint):sizeint;
begin
result:=param;
if result>-1 then dec(result);
if result<1 then inc(result);
if result<=-1 then dec(result);
if result>=1 then inc(result);
if result<0 then dec(result);
if result>0 then inc(result);
end;
The code produced is
.section .text.n_unit1_$$_foo$int64$$int64,"ax"
.balign 16,0x90
.globl UNIT1_$$_FOO$INT64$$INT64
.hidden UNIT1_$$_FOO$INT64$$INT64
.type UNIT1_$$_FOO$INT64$$INT64,@function
UNIT1_$$_FOO$INT64$$INT64:
.Lc2:
.Ll1:
# [unit1.pas]
# [33] begin
movq %rdi,%rax
# Var param located in register rax
# Var $result located in register rax
# Var param located in register rax
.Ll2:
# [35] if result>-1 then dec(result);
cmpq $-1,%rdi
setg %cl
movzbl %cl,%ecx
subq %rcx,%rax
.Ll3:
# [36] if result<1 then inc(result);
testq %rax,%rax
setle %cl
movzbl %cl,%ecx
addq %rcx,%rax
.Ll4:
# [37] if result<=-1 then dec(result);
cmpq $-1,%rax
setle %cl
movzbl %cl,%ecx
subq %rcx,%rax
.Ll5:
# [38] if result>=1 then inc(result);
testq %rax,%rax
setnle %cl
movzbl %cl,%ecx
addq %rcx,%rax
.Ll6:
# [39] if result<0 then dec(result);
testq %rax,%rax
setl %cl
movzbl %cl,%ecx
subq %rcx,%rax
.Ll7:
# [40] if result>0 then inc(result);
testq %rax,%rax
setg %cl
movzbl %cl,%ecx
addq %rcx,%rax
.Lc3:
.Ll8:
# [41] end;
ret
.Lc1:
.Lt1:
.Le0:
.size UNIT1_$$_FOO$INT64$$INT64, .Le0 - UNIT1_$$_FOO$INT64$$INT64
.Ll9:
I think the compiler should replace the two cmp instructions with test ones. Comparisons with 0 and 1 are ok so it should be trivial to modify the compiler in order to optimize these -1 comparisons. Probably the compiler developer who implemented this kind of optimization forgot about the -1 scenario.