Skip to content

Instantly share code, notes, and snippets.

@ewxrjk
Created April 30, 2017 10:21
Show Gist options
  • Select an option

  • Save ewxrjk/10345dc7b3460109a95155bd1c0df2ef to your computer and use it in GitHub Desktop.

Select an option

Save ewxrjk/10345dc7b3460109a95155bd1c0df2ef to your computer and use it in GitHub Desktop.
Missed optimization
richard@deodand:~$ cat t.c
unsigned long f();
unsigned long h() {
unsigned long x = f();
return x == (unsigned long)-1 ? 0 : x + 1;
}
richard@deodand:~$ gcc -O3 -S t.c && cat t.s
.file "t.c"
.text
.p2align 4,,15
.globl h
.type h, @function
h:
.LFB0:
.cfi_startproc
subq $8, %rsp
.cfi_def_cfa_offset 16
xorl %eax, %eax
call f@PLT
leaq 1(%rax), %rdx
cmpq $-1, %rax
movl $0, %eax
cmovne %rdx, %rax
addq $8, %rsp
.cfi_def_cfa_offset 8
ret
.cfi_endproc
.LFE0:
.size h, .-h
.ident "GCC: (Debian 6.3.0-14) 6.3.0 20170415"
.section .note.GNU-stack,"",@progbits
richard@deodand:~$ clang-4.0 -O3 -S t.c && cat t.s
.text
.file "t.c"
.globl h
.p2align 4, 0x90
.type h,@function
h: # @h
.cfi_startproc
# BB#0:
pushq %rax
.Lcfi0:
.cfi_def_cfa_offset 16
xorl %eax, %eax
callq f
incq %rax
popq %rcx
retq
.Lfunc_end0:
.size h, .Lfunc_end0-h
.cfi_endproc
.ident "clang version 4.0.0-3 (tags/RELEASE_400/rc1)"
.section ".note.GNU-stack","",@progbits
@ewxrjk

ewxrjk commented Apr 30, 2017

Copy link
Copy Markdown
Author

Why would you write that code? Because the natural way of doing it triggers a false positive from a sanitizer in the x=(unsigned long)-1 case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment