Bug 87628 - Redundant check of pointer when operator delete is called
Summary: Redundant check of pointer when operator delete is called
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: unknown
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: missed-optimization
Depends on:
Blocks:
 
Reported: 2018-10-17 05:36 UTC by AK
Modified: 2023-05-23 19:45 UTC (History)
4 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2018-10-17 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description AK 2018-10-17 05:36:47 UTC
https://godbolt.org/z/DY9ruv

void if_delete(char *p) {
    if (p) {
        delete(p);
    }
}

$ gcc-8.2 -Os -fno-exceptions

if_delete(char*):
  test rdi, rdi
  je .L1
  mov esi, 1
  jmp operator delete(void*, unsigned long)
.L1:
  ret


While clang removes the check at -Oz:

$ clang -Oz -fno-exceptions
if_delete(char*):
        jmp     operator delete(void*)
Comment 1 Richard Biener 2018-10-17 07:33:32 UTC
Confirmed.  IIRC there are duplicates of this bug.
Comment 2 Eric Gallager 2019-10-18 04:11:10 UTC
(In reply to Richard Biener from comment #1)
> Confirmed.  IIRC there are duplicates of this bug.

Well related bugs for the plain-C equivalent with free() at least
Comment 3 AK 2022-09-21 04:44:47 UTC
Still happening with gcc trunk.

https://godbolt.org/z/5K94665GK
Comment 4 AK 2022-09-21 05:00:32 UTC
Seems like clang now added the check:

$ clang++ -Oz -fno-exceptions

if_delete(char*):                         # @if_delete(char*)
        test    rdi, rdi
        jne     operator delete(void*)@PLT                      # TAILCALL
        ret
Comment 5 AK 2023-05-17 17:53:06 UTC
As per: https://en.cppreference.com/w/cpp/memory/new/operator_delete
"""
In all cases, if ptr is a null pointer, the standard library deallocation functions do nothing. If the pointer passed to the standard library deallocation function was not obtained from the corresponding standard library allocation function, the behavior is undefined.
"""

So it should be fine to remove the check `if(p)`
Comment 6 AK 2023-05-17 18:14:55 UTC
Opened a bug for clang as well: https://github.com/llvm/llvm-project/issues/62783