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

            Bug ID: 113527
           Summary: Missed optimization [[assume]] attribute
           Product: gcc
           Version: 14.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: eric-bugs at omnifarious dot org
  Target Milestone: ---

This code https://godbolt.org/z/jeYGcr5sv still generates all the exception
handling code. It treats the assume attribute more like 'likely' than 'assume'.
It's supposed to be undefined behavior for the assumption to be false.

Here is the code replicated here:

#include <variant>

struct Potato
{
    explicit Potato(int);
    Potato(const Potato & other) noexcept;
};

using V = std::variant<Potato, int, double>;

template <class... Ts_>
struct overloaded : Ts_... { using Ts_::operator()...; };

auto f(const V & v) -> int
{
    [[assume(! v.valueless_by_exception())]];
    return visit(overloaded{
        [](int) { return 144; },
        [](double) { return 27; },
        [](const Potato &) { return 50; }
    }, v);
}

You can make the exception handling code go away by simply using "if
(v.valueless_by_exception())" and returning some random value in the false
case. But, if the spirit of the keyword is to be observed, you should be fine
just doing a straight up table lookup and using the result without even
checking the type tag at all.

Reply via email to