https://gcc.gnu.org/bugzilla/show_bug.cgi?id=102829

            Bug ID: 102829
           Summary: Redundant null check after atomic load from that
                    address
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: laurynas.biveinis at gmail dot com
  Target Milestone: ---

The following source code
----
struct d {
  long b;

  d *e() {
    __atomic_load_n(&b, 0);
    return this;
  }
};

d *j;

void i();

void k() {
  auto l = j->e();
  if (l)
    i();
}
----
produces the following bit of assembly with -O3 on x86_64
(https://godbolt.org/z/G1ThvnMWP):
...
        mov     rdx, QWORD PTR [rax]
        test    rax, rax
        je      .L1
...

It first dereferences the address at RAX, and later checks whether RAX == 0.
Since we already tried accessing memory at that address, the nullptr check
seems redundant. Moreover, since the address happens to be of 'this' of
variable j, it being equal to nullptr is UB anyway and may be assumed to be !=
nullptr?

Clang tests show the redundant test being present up to version 11 inclusive
(https://godbolt.org/z/rT3ha4enb) and absent from version 12 onwards
(https://godbolt.org/z/Gfb9EWMfq)

Reply via email to