]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Micro-optimization for std::optional [PR112480]
authorJonathan Wakely <jwakely@redhat.com>
Sat, 11 Nov 2023 00:35:18 +0000 (00:35 +0000)
committerJonathan Wakely <jwakely@redhat.com>
Mon, 13 Nov 2023 23:22:19 +0000 (23:22 +0000)
This small change removes a branch when clearing a std::optional<T> for
types with no-op destructors. For types where the destructor can be
optimized away (e.g. because it's trivial, or empty and can be inlined)
the _M_destroy() function does nothing but set _M_engaged to false.
Setting _M_engaged=false unconditionally is cheaper than only doing it
when initially true, because it allows the compiler to remove a branch.

The compiler thinks it would be incorrect to unconditionally introduce a
store there, because it could conflict with reads in other threads, so
it won't do that optimization itself. We know it's safe to do because
we're in a non-const member function, so the standard forbids any
potentially concurrent calls to other member functions of the same
object. Making the store unconditional can't create a data race that
isn't already present in the program.

libstdc++-v3/ChangeLog:

PR libstdc++/112480
* include/std/optional (_Optional_payload_base::_M_reset): Set
_M_engaged to false unconditionally.

libstdc++-v3/include/std/optional

index 53450c760d9fe11e5750a021bf4a0c4e26998037..a8c97717b724770fce24f2d54f5b1335747a04d5 100644 (file)
@@ -311,6 +311,8 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
       {
        if (this->_M_engaged)
          _M_destroy();
+       else // This seems redundant but improves codegen, see PR 112480.
+         this->_M_engaged = false;
       }
     };