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

            Bug ID: 124821
           Summary: Missed optimization for std::string destruction
           Product: gcc
           Version: 15.2.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: terra at gnome dot org
  Target Milestone: ---

https://godbolt.org/z/YvE7jWd5z

-----------------------------------------------------------------
#include <string>

extern int foo (std::string_view s);

int
bar()
{
    return foo(std::string{});
}
-----------------------------------------------------------------

gcc 15.2 compiles this into code that after the call the foo has the full
destructor for std::string including a call to "operator delete":

bar():
        push    r14
        xor     edi, edi
        push    rbx
        sub     rsp, 56
        lea     rbx, [rsp+32]
        mov     BYTE PTR [rsp+32], 0
        mov     rsi, rbx
        mov     QWORD PTR [rsp+16], rbx
        mov     QWORD PTR [rsp+24], 0
        call    foo(std::basic_string_view<char, std::char_traits<char>>)
        mov     rdi, QWORD PTR [rsp+16]
        cmp     rdi, rbx
        je      .L1
        mov     DWORD PTR [rsp+12], eax
        mov     rax, QWORD PTR [rsp+32]
        lea     rsi, [rax+1]
        call    operator delete(void*, unsigned long)
        mov     eax, DWORD PTR [rsp+12]
.L1:
        add     rsp, 56
        pop     rbx
        pop     r14
        ret
        mov     r14, rax
        jmp     .L3
bar() (.cold):


Since the string wasn't heap allocated to begin with and no-one has had access
to later cause a heap allocation, the branch with operator delete should be
optimized away.


Somewhat related to bug 87502.

Reply via email to