https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128834
--- Comment #3 from Jakub Jelinek <jakub at gcc dot gnu.org> ---
Possibly unrelated thing to help though at the generic level (why using the
builtin works) is that when using the builtin, we get in the IL __imag__
.ADD_OVERFLOW (..., ...) first cast to bool and then back to u64, which evrp
optimizes into just casting
__imag__ from u128 to u64.
While in the add_carry case, .ADD_OVERFLOW is pattern matched only late
(widening_mult pass) and
_4 = _3 + p_11;
*acc_13(D) = _4;
_5 = *top_15(D);
_6 = _4 < p_11;
_7 = (long unsigned int) _6;
_8 = _5 + _7;
*top_15(D) = _8;
is matched as
_18 = .ADD_OVERFLOW (_3, p_11);
_4 = REALPART_EXPR <_18>;
_17 = IMAGPART_EXPR <_18>;
*acc_13(D) = _4;
_5 = *top_15(D);
_6 = _17 != 0;
_7 = (long unsigned int) _6;
_8 = _5 + _7;
*top_15(D) = _8;
Note, the _17 != 0 in there as opposed to not setting _6 at all and changing _7
to be _7 = (long unsigned int) _5;
The IMAGPART_EXPR has value in [0, 1] range, but I think we don't do VRP
anymore etc.
When I compile -O2 -fno-early-inlining
typedef unsigned long long u64;
typedef unsigned __int128 u128;
static inline u128 foo(u128 *acc, u64 a, u64 b)
{
u128 p = (u128)a * b;
return __builtin_add_overflow(*acc, p, acc);
}
void bar(u128 *acc, u64 *top, u64 a, u64 b) {
*top += foo(acc, a, b) != 0;
}
which more matches what we actually pattern match for add_carry in
widening_mul, vrp1 is able to optimize
_19 = IMAGPART_EXPR <_17>;
_2 = _19 != 0;
_4 = (long long unsigned int) _2;
into
_19 = IMAGPART_EXPR <_17>;
_2 = (_Bool) _19;
_4 = (long long unsigned int) _19;
But there is no vrp after widening_mul. Wonder if the pattern matching
shouldn't try to optimize this manually. Of course, whether changing the
backend is desirable anyway or not is another question.