<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/63532>63532</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            Miscompilation of __builtin_usub_overflow / __builtin_usubc (regression in LLVM 15)
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            backend:ARM,
            regression,
            miscompilation
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          chfast
      </td>
    </tr>
</table>

<pre>
    In clang/LLVM 15 (also XCode 14.3.1) the `__builtin_usubc` is mis-compiled on arm64 / aarch64.

This is the test reproducing the bug:

```cpp
using u64 = unsigned long long;

[[gnu::noinline]] auto sub(const u64 x[3], const u64 y[3])
{
    u64 k = 0;
    __builtin_subcll(x[0], y[0], k, &k);
 __builtin_subcll(x[1], y[1], k, &k);
    return __builtin_subcll(x[2], y[2], k, &k);
}

int main()
{
    const u64 x[] = {0, 0, 0};
    const u64 y[] = {1, 0, 0};
    if (sub(x, y) != ~u64(0))
 return 1;  // Return 1 if result is incorrect.
    return 0;
}
```

The incorrect assembly is:

```asm
        ldp x8, x9, [x0]
        ldp     x10, x11, [x1]
        cmp     x8, x10
        sbcs    xzr, x9, x11
        cset    w8, lo
        ldr x9, [x0, #16]
        ldr     x10, [x1, #16]
        sub     x9, x9, x10
        sub     x0, x9, x8
        ret
```

In LLVM 16 the issue seems to be fixed. We get the following assembly:

```asm
 ldp     x8, x9, [x0]
        ldp     x10, x11, [x1]
        cmp x8, x10
        cset    w8, lo
        cmp     x9, x11
        csel w8, wzr, w8, ne
        csinc   w8, w8, wzr, hs
        ldr     x9, [x0, #16]
        ldr     x10, [x1, #16]
        sub     x9, x9, x10
        sub     x0, x9, x8
 ret
```

https://godbolt.org/z/n4oxq5cz5
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJzMVk1v4zYQ_TXUZRCDpCzZOugQxz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