https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81972
Bug ID: 81972
Summary: Improve data tracking for simple conditional code
Product: gcc
Version: 7.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: [email protected]
Target Milestone: ---
[code]
__attribute__((nonnull(1)))
void f1(int*);
void f2(int* n)
{
int* ptr = nullptr;
if (*n > 2)
ptr = n;
f1(ptr);
}
void f3(int* n)
{
if (*n > 2)
f1(n);
else
f1(nullptr);
}
[/code]
Functions f2 and f3 are equivalent. Above code compiled by gcc 7.2 (with -O3
-Wall -Wextra) generates following assembler code:
[code]
f2(int*):
cmp DWORD PTR [rdi], 2
mov eax, 0
cmovle rdi, rax
jmp f1(int*)
f3(int*):
cmp DWORD PTR [rdi], 2
jg .L7
xor edi, edi
.L7:
jmp f1(int*)
[/code]
There are two issues here:
- both functions contains bug, they try to pass NULL pointer to f1. However gcc
reports this for f3 only. gcc is able to track data for optimization purposes,
so it should be possible to generate warning for f2.
- f3 is compiled to code with branch, so most probably it will be slower a bit.
It could be optimized to get the same code as f2 (branchless).