https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97640
Bug ID: 97640
Summary: GCC doesn't optimize-out outside-affecting lambdas
within y-combinator while clang does.
Product: gcc
Version: unknown
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c++
Assignee: unassigned at gcc dot gnu.org
Reporter: hotguest1 at hotmail dot com
Target Milestone: ---
Suppose we have a y-combinator, so that we can write lambdas in recursive
fashion.
template <class F>
struct y_combinator {
F f;
template <class... Ts>
constexpr decltype(auto) operator()(Ts&&... ts) const { return
f(std::ref(*this), std::forward<Ts>(ts)...); }
template <class... Ts>
constexpr decltype(auto) operator()(Ts&&... ts) { return
f(std::ref(*this), std::forward<Ts>(ts)...); }
};
Let's have a constexpr-qualified lambda
auto sum = y_combinator{[&](auto self,int a,int b,int res = 0) mutable {
if (a>b) {
return res;
}
res += a;
return self(a+1,b,res);
}};
This lambda is constexpr-qualified.
So both gcc and clang do optimize-out all the things in the name of constexpr
expansion.
https://compiler-explorer.com/z/qx4MGE
==============================================================================
Let's try an outside-affecting lambda
auto sum = y_combinator{[&,res=0](auto self,int a,int b) mutable {
if (a>b) {
return res;
}
res += a;
return self(a+1,b);
}};
This non-constexpr-qualified lambda is optimized-out in clang but in gcc it is
not.
https://compiler-explorer.com/z/hPGWod