https://gcc.gnu.org/bugzilla/show_bug.cgi?id=86732
Bug ID: 86732
Summary: Potential nullptr dereference does not propagate
knowledge about the pointer
Product: gcc
Version: 9.0
Status: UNCONFIRMED
Keywords: missed-optimization
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: antoshkka at gmail dot com
Target Milestone: ---
Following example
static const int* get_if(const int* v) {
if (v && *v == 0) return v;
return nullptr;
}
int example(const int& a) {
return *get_if(&a);
}
Generates quite a large assembly:
_Z7exampleRKi:
mov eax, DWORD PTR [rdi]
test eax, eax
jne .L2
xor eax, eax
ret
_Z7exampleRKi.cold.0:
.L2:
mov eax, DWORD PTR ds:0
ud2
However clang generates a better code:
_Z7exampleRKi: # @_Z7exampleRKi
mov eax, dword ptr [rdi]
ret
If we unconditionally dereference the result of `get_if`, then it is UB to
return a nullptr. So all the nullptr checks could be eliminated.