Bug 80331 - unused const std::string not optimized away
Summary: unused const std::string not optimized away
Status: NEW
Alias: None
Product: gcc
Classification: Unclassified
Component: libstdc++ (show other bugs)
Version: 7.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords:
Depends on: 23383
Blocks:
  Show dependency tree / graph
 
Reported: 2017-04-05 16:50 UTC by AK
Modified: 2025-11-30 01:25 UTC (History)
5 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed: 2024-11-27 00:00:00


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description AK 2017-04-05 16:50:56 UTC
$ cat t.cpp
#include<string>
int sain() {
  const std::string s("a");
  return 0;
}

# gcc version 7.0.0 20170118 (experimental) (GCC)
$ g++ -S -o t.s t.cpp -O2 -fno-exceptions -std=c++11

$ cat t.s
	.type	_Z4sainv, @function
_Z4sainv:
.LFB940:
	.cfi_startproc
	pushq	%rbx
	.cfi_def_cfa_offset 16
	.cfi_offset 3, -16
	movl	$.LC0+1, %esi
	subq	$32, %rsp
	.cfi_def_cfa_offset 48
	leaq	16(%rsp), %rbx
	movq	%rsp, %rdi
	movq	%rbx, (%rsp)
	call	_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE12_M_constructIPKcEEvT_S8_St20forward_iterator_tag.isra.16.constprop.20
	movq	(%rsp), %rdi
	cmpq	%rbx, %rdi
	je	.L13
	call	_ZdlPv
.L13:
	addq	$32, %rsp
	.cfi_def_cfa_offset 16
	xorl	%eax, %eax
	popq	%rbx
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE940:
	.size	_Z4sainv, .-_Z4sainv


clang++, on the other hand, completely optimizes the const string.

	.type	_Z4sainv,@function
_Z4sainv:                               # @_Z4sainv
	.cfi_startproc
# BB#0:
	xorl	%eax, %eax
	retq
.Lfunc_end0:
	.size	_Z4sainv, .Lfunc_end0-_Z4sainv
Comment 1 Markus Trippelsdorf 2017-04-05 16:56:00 UTC
Cannot reproduce. Try a more recent snapshot?
Comment 2 Marc Glisse 2017-04-05 17:03:27 UTC
If you replace "a" with something longer (size>16 when counting the last '\0'), it does reproduce. I'd say this is a dup of 2 known issues:
- the compiled part of libstdc++ prevents optimization (maybe eventually with LTO?),
- gcc knows about malloc and free but not about new and delete.

I didn't check if those are the only blockers in this case...
Comment 3 Marc Glisse 2017-04-05 17:13:50 UTC
(In reply to Marc Glisse from comment #2)
> I didn't check if those are the only blockers in this case...

Looks like they are indeed the only blockers, since we optimize the below just fine. So, known issue (which doesn't mean we shouldn't do something about it).
(with 2 dead strings instead of 1, we need -O3, -O2 is not sufficient)

#include <bits/c++config.h>
#undef _GLIBCXX_EXTERN_TEMPLATE
#define _GLIBCXX_EXTERN_TEMPLATE 0
#include <string>
#include <memory>
inline void operator delete(void*p){__builtin_free(p);}
inline void* operator new(size_t n){return __builtin_malloc(n);}
int main() {
  const std::string s("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
}
Comment 4 Drea Pinski 2017-04-05 17:31:17 UTC
23383
Comment 5 Markus Trippelsdorf 2017-04-05 18:01:57 UTC
Lets close as dup.

*** This bug has been marked as a duplicate of bug 78104 ***
Comment 6 Drea Pinski 2022-01-07 02:03:35 UTC
Reopening as it is not a dup of that one (though I think there is another bug about this one).
Comment 7 Drea Pinski 2022-01-07 02:21:40 UTC
With -std=c++20 -O2 I get better code than just -std=c++17 -O2:
  _34 = operator new (24);
  __builtin_memcpy (_34, "a                      ", 23);
  MEM[(char_type &)_34 + 23] = 0;
  operator delete (_34, 24);

That is all I think due to what is referenced in PR 86590.
Comment 8 Jonathan Wakely 2022-01-07 10:54:05 UTC
(In reply to Andrew Pinski from comment #7)
> With -std=c++20 -O2 I get better code than just -std=c++17 -O2:
>   _34 = operator new (24);
>   __builtin_memcpy (_34, "a                      ", 23);
>   MEM[(char_type &)_34 + 23] = 0;
>   operator delete (_34, 24);
> 
> That is all I think due to what is referenced in PR 86590.

Yes, it's because the explicit instantiations are disabled for C++20:

# if __cplusplus <= 201703L && _GLIBCXX_EXTERN_TEMPLATE > 0
  extern template class basic_string<char>;
Comment 9 AK 2022-06-04 22:55:53 UTC
can't repro this with gcc 12.1 Seems like this is fixed?

https://godbolt.org/z/e6n94zK4E
Comment 10 Marc Glisse 2022-06-05 07:54:47 UTC
(In reply to AK from comment #9)
> can't repro this with gcc 12.1 Seems like this is fixed?

No. As stated in other comments, it still reproduces with a longer string (or with -D_GLIBCXX_USE_CXX11_ABI=0).
Comment 11 Sam James 2024-11-27 06:02:08 UTC
The new/delete improvements haven't sorted this one yet.
Comment 12 Jan Hubicka 2024-11-27 07:12:12 UTC
I think with my patch to basic_string we should have at least arrived to something comparable with clang.
With -O2 it is optimized away,
with -O2 -D_GLIBCXX_USE_CXX11_ABI=0 I get:

int sain ()
{
  struct allocator_type D.37493;
  struct allocator D.33221;
  struct _Rep * _18;
  _Atomic_word * _29;
  char __libc_single_threaded.11_30;
  unsigned int _33;
  int _34;

  <bb 2> [local count: 1073741824]:
  _18 = std::basic_string<char>::_Rep::_S_create (1, 0, &D.33221);
  MEM[(char_type &)_18 + 24] = 97;
  if (_18 != &_S_empty_rep_storage)
    goto <bb 3>; [10.00%]
  else
    goto <bb 8>; [90.00%]

  <bb 3> [local count: 107374184]:
  _18->D.33079._M_refcount = 0;
  _18->D.33079._M_length = 1;
  MEM[(char_type &)_18 + 25] = 0;
  D.33221 ={v} {CLOBBER(eos)};
  __libc_single_threaded.11_30 = __libc_single_threaded;
  if (__libc_single_threaded.11_30 != 0)
    goto <bb 4>; [67.00%]
  else
    goto <bb 5>; [33.00%]

  <bb 4> [local count: 71940704]:
  MEM[(_Atomic_word *)_18 + 16B] = -1;
  goto <bb 6>; [100.00%]

  <bb 5> [local count: 35433481]:
  _29 = &_18->D.33079._M_refcount;
  _33 = __atomic_fetch_add_4 (_29, 4294967295, 4);
  _34 = (int) _33;
  if (_34 <= 0)
    goto <bb 6>; [7.88%]
  else
    goto <bb 7>; [92.12%]

  <bb 6> [local count: 27380417]:
  std::basic_string<char>::_Rep::_M_destroy (_18, &D.37493);

  <bb 7> [local count: 1073741824]:
  D.37493 ={v} {CLOBBER(eos)};
  return 0;

  <bb 8> [local count: 966367640]:
  D.33221 ={v} {CLOBBER(eos)};
  goto <bb 7>; [100.00%]

}

this is not optimized since _M_create and M_destroy are not inlined. Those seems to be invisible to compiler, so even if modref was extended to propagate removable allocations inter-proceduraly, we have problem.

With longer string also both clang and GCC will not optimize the code completely. We get:

int sain ()
{
  size_type __dnew;
  const struct string s;
  char * _7;
  long unsigned int _9;
  long unsigned int _10;
  char * _17;
  long unsigned int __dnew.1_18;
  long unsigned int __dnew.2_20;
  char * _21;
  char * _22;

  <bb 2> [local count: 1073741824]:
  MEM[(struct basic_string *)&s] ={v} {CLOBBER(bob)};
  MEM[(struct _Alloc_hider *)&s] ={v} {CLOBBER(bob)};
  MEM[(struct _Alloc_hider *)&s]._M_p = &s.D.25525._M_local_buf;
  __dnew = 40;
  _17 = std::__cxx11::basic_string<char>::_M_create (&s, &__dnew, 0);
  s._M_dataplus._M_p = _17;
  __dnew.1_18 = __dnew;
  s.D.25525._M_allocated_capacity = __dnew.1_18;
  __builtin_memcpy (_17, "this string is longer than 15 characters", 40);
  __dnew.2_20 = __dnew;
  _21 = s._M_dataplus._M_p;
  _22 = _21 + __dnew.2_20;
  MEM[(char_type &)_22] = 0;
  __dnew ={v} {CLOBBER(eos)};
  _7 = s._M_dataplus._M_p;
  if (&s.D.25525._M_local_buf == _7)
    goto <bb 4>; [18.09%]
  else
    goto <bb 3>; [81.91%]

  <bb 3> [local count: 879501928]:
  _9 = s.D.25525._M_allocated_capacity;
  _10 = _9 + 1;
  operator delete (_7, _10);

  <bb 4> [local count: 1073741824]:
  s ={v} {CLOBBER(eob)};
  s ={v} {CLOBBER(eos)};
  return 0;

}

Call to _M_create is problem here. Again it is not seen by modref.
With -std=c++23 we optimize out the code, while clang doesn't
Comment 13 Jan Hubicka 2024-12-10 17:10:42 UTC
As discussed with Jason, problem with _M_create not seen by middle-end is actually due to C++ standard. Explicit instantiations prevents implicit ones for non-inline functions, see discussion in PR39242.  Without understanding the side-effects we can not optimize, so I think we want to declare it inline with Jakub's not-really-inline-hint attribute?
Comment 14 Jan Hubicka 2024-12-10 17:52:00 UTC
Declaring _S_create and _M_create inline indeed helps a little:

diff --git a/libstdc++-v3/include/bits/basic_string.h b/libstdc++-v3/include/bits/basic_string.h
index 17b973c8b45..d73a61abe5b 100644
--- a/libstdc++-v3/include/bits/basic_string.h
+++ b/libstdc++-v3/include/bits/basic_string.h
@@ -278,7 +278,7 @@ _GLIBCXX_BEGIN_NAMESPACE_CXX11
       }
 
       // Create & Destroy
-      _GLIBCXX20_CONSTEXPR
+      _GLIBCXX20_CONSTEXPR inline
       pointer
       _M_create(size_type&, size_type);
 
diff --git a/libstdc++-v3/include/bits/cow_string.h b/libstdc++-v3/include/bits/cow_string.h
index 087ddf81dd8..0bd75f0fcb1 100644
--- a/libstdc++-v3/include/bits/cow_string.h
+++ b/libstdc++-v3/include/bits/cow_string.h
@@ -259,7 +259,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
        }
 
        // Create & Destroy
-       static _Rep*
+       static inline _Rep*
        _S_create(size_type, size_type, const _Alloc&);
 
        void

Now I get:

int sain ()
{
  struct allocator_type D.27707;
  char * _45;
  _Atomic_word * _49;
  char __libc_single_threaded.12_50;
  unsigned int _53;
  int _54;

  <bb 2> [local count: 1073741824]:
  _45 = operator new (26);
  MEM[(struct _Rep *)_45].D.24285._M_capacity = 1;
  MEM[(struct _Rep *)_45].D.24285._M_refcount = 0;
  MEM[(char_type &)_45 + 24] = 97;
  if (_45 != &_S_empty_rep_storage)
    goto <bb 4>; [10.00%]
  else
    goto <bb 3>; [90.00%]

  <bb 3> [local count: 999008065]:
  goto <bb 8>; [100.00%]

  <bb 4> [local count: 107374184]:
  MEM[(struct _Rep *)_45].D.24285._M_length = 1;
  MEM[(char_type &)_45 + 25] = 0;
  __libc_single_threaded.12_50 = __libc_single_threaded;
  if (__libc_single_threaded.12_50 != 0)
    goto <bb 5>; [67.00%]
  else
    goto <bb 6>; [33.00%]

  <bb 5> [local count: 71940704]:
  MEM[(_Atomic_word *)_45 + 16B] = -1;
  goto <bb 7>; [100.00%]

  <bb 6> [local count: 35433481]:
  _49 = &MEM[(struct _Rep *)_45].D.24285._M_refcount;
  _53 = __atomic_fetch_add_4 (_49, 4294967295, 4);
  _54 = (int) _53;
  if (_54 <= 0)
    goto <bb 7>; [7.88%]
  else
    goto <bb 3>; [92.12%]

  <bb 7> [local count: 27380417]:
  std::basic_string<char>::_Rep::_M_destroy (_45, &D.27707);

  <bb 8> [local count: 1073741824]:
  D.27707 ={v} {CLOBBER(eos)};
  return 0;

}

New memory is kept alive by:

  _45 = operator new (26);
...
  if (_45 != &_S_empty_rep_storage)
    goto <bb 4>; [10.00%]
  else
    goto <bb 3>; [90.00%]

I think we ought to be able to deduce from malloc attribute that _45 is different from address of a decl.
Comment 15 Jan Hubicka 2024-12-14 16:05:31 UTC
Original testcase is solved by https://gcc.gnu.org/pipermail/gcc-patches/2024-December/671599.html
We still won't optimize longer strings because _M_create is not inline.
Comment 16 Jan Hubicka 2024-12-14 16:06:46 UTC
Original testcase is solved by https://gcc.gnu.org/pipermail/gcc-patches/2024-December/671599.html
We still won't optimize longer strings because _M_create is not inline.
Comment 17 GCC Commits 2025-03-30 21:51:33 UTC
The master branch has been updated by Jan Hubicka <hubicka@gcc.gnu.org>:

https://gcc.gnu.org/g:9c5505a35d9d71705464f9254f55407192d31ec3

commit r15-9047-g9c5505a35d9d71705464f9254f55407192d31ec3
Author: Jan Hubicka <hubicka@ucw.cz>
Date:   Sun Mar 30 23:49:49 2025 +0200

    Optimize string constructor
    
    this patch improves code generation on string constructors.  We currently have
    _M_construct which takes as a parameter two iterators (begin/end pointers to
    other string) and produces new string.  This patch adds special case of
    constructor where instead of begining/end pointers we readily know the string
    size and also special case when we know that source is 0 terminated.  This
    happens commonly when producing stirng copies. Moreover currently ipa-prop is
    not able to propagate information that beg-end is known constant (copied string
    size) which makes it impossible for inliner to spot the common case where
    string size is known to be shorter than 15 bytes and fits in local buffer.
    
    Finally I made new constructor inline. Because it is explicitely instantiated
    without C++20 constexpr we do not produce implicit instantiation (as required
    by standard) which prevents inlining, ipa-modref and any other IPA analysis to
    happen.  I think we need to make many of the other functions inline, since
    optimization accross string manipulation is quite important. There is PR94960
    to track this issue.
    
    Bootstrapped/regtested x86_64-linux, OK?
    
    libstdc++-v3/ChangeLog:
    
            PR tree-optimization/103827
            PR tree-optimization/80331
            PR tree-optimization/87502
    
            * config/abi/pre/gnu.ver: Add version for _M_construct<bool>
            * include/bits/basic_string.h: (basic_string::_M_construct<bool>): Declare.
            (basic_string constructors): Use it.
            * include/bits/basic_string.tcc: (basic_string::_M_construct<bool>): New template.
            * src/c++11/string-inst.cc: Instantated S::_M_construct<bool>.
    
    gcc/testsuite/ChangeLog:
    
            * g++.dg/tree-ssa/pr80331.C: New test.
            * g++.dg/tree-ssa/pr87502.C: New test.
Comment 18 GCC Commits 2025-03-31 05:40:52 UTC
The master branch has been updated by Jakub Jelinek <jakub@gcc.gnu.org>:

https://gcc.gnu.org/g:78aed0ae5de801cc1e8220b214145300b28da562

commit r15-9050-g78aed0ae5de801cc1e8220b214145300b28da562
Author: Jakub Jelinek <jakub@redhat.com>
Date:   Mon Mar 31 07:39:53 2025 +0200

    libstdc++: Fix up string _M_constructor<bool> exports [PR103827]
    
    On Thu, Mar 27, 2025 at 02:04:24PM +0100, Jan Hubicka wrote:
    > Seems I missed the approval, sorry.  I will push it - I think it would
    > be useful to have it in.
    
    Unfortunately the exports in this patch only work on targets where size_t is
    unsigned long, not e.g. on ia32 where it is unsigned int, or targets where
    it is unsigned long long.
    
    2025-03-31  Jakub Jelinek  <jakub@redhat.com>
    
            PR tree-optimization/103827
            PR tree-optimization/80331
            PR tree-optimization/87502
            * config/abi/pre/gnu.ver (GLIBCXX_3.4.34): Use [jmy] rather than m
            in pattern for _M_construct<bool>(char const*, size_t).