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

            Bug ID: 106865
           Summary: addcarry pattern
           Product: gcc
           Version: 13.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: unlvsur at live dot com
  Target Milestone: ---

clang provides builtins like __builtin_addcll to deal with addcarry in a
generic way. However, i believe we can provide pattern matching in GCC so
existing programs may get benefit from the code, instead of adding new
builtins.

https://godbolt.org/z/3j18bPq8b

Take riscv as example:

https://godbolt.org/z/KWxfPWGz4

https://godbolt.org/z/b4r63oGqj

This proves GCC and clang can generate identical code EVEN without using adc
builtins.

I suggest to add pattern matching for code like this in GCC:

template<typename T>
inline constexpr T add_carry_no_carry_in(T a,T b,T& carryout) noexcept
{
    T res{a+b};
    carryout=res<a;
    return res;
}

template<typename T>
inline constexpr T add_carry(T a,T b,T carryin,T& carryout) noexcept
{
    if(carryin>1)
    {
        __builtin_unreachable();
    }
    a=add_carry_no_carry_in(carryin,a,carryout);
    a=add_carry_no_carry_in(a,b,carryin);
    carryout+=carryin;
    return a;
}

This should correctly identify carries for GCC without adding new builtins
while it keeps the same interface as clang's builtins.

Reply via email to