| Issue |
240185
|
| Summary |
[AVR] Adding a constant to an integer wider than 64 bits mixes subi/sbci with adc, inverting the carry
|
| Labels |
new issue
|
| Assignees |
|
| Reporter |
kaidokert
|
On AVR, adding a constant to an integer wider than 64 bits mixes two carry conventions. The low 16 bits are lowered as `subi`/`sbci` of the negated constant, which leaves C set as a *borrow*. The upper bytes are then propagated with `adc`, which reads C as a *carry*. The two senses are inverted, so the result is wrong whenever the low part's borrow and carry differ, which in practice is almost always.
**Reproducer** (`add_imm.ll`):
```llvm
target datalayout = "e-P1-p:16:8-i8:8-i16:8-i32:8-i64:8-f32:8-f64:8-n8-a:8"
target triple = "avr-unknown-unknown"
define i128 @add1(i128 %x) {
%r = add i128 %x, 1
ret i128 %r
}
```
`llc -O2 -mtriple=avr -mcpu=atmega328p` (any AVR CPU) emits:
```
movw r26, r8
ldi r30, 0
ldi r31, 0
subi r26, 255
sbci r27, 255
adc r10, r30
adc r11, r31
... ; adc for the remaining bytes
```
For `x = 0xA_F000_0000`, `subi`/`sbci` compute `0x0000 - 0xFFFF`. That sets C, a borrow, although adding 1 produces no carry, and the `adc` chain then adds it to bit 16. The result is `0xA_F001_0001` instead of `0xA_F000_0001`. For `x = 0xFFFF` the opposite happens: the carry is lost, and the result is `0` instead of `0x1_0000`. Measured under simavr, from Rust's `i128::wrapping_add(1)` and `checked_add(1)`. `checked_sub(1)` fails the same way.
**Scope.** A survey with `llc` over `add`/`sub` of a constant:
| Type and constant | Lowering |
|---|---|
| `i128 + 1`, `i128 - 1` | `subi`/`sbci` on the low word, then `adc` ×14: wrong (measured under simavr) |
| `i128 + 65536`, `i128 + 2^32` | `subi`/`sbci` on the constant's lowest nonzero word, then `adc` above it: the same mixed pattern |
| `i96 + 1` | `subi`/`sbci`, then `adc` ×10: the same mixed pattern |
| `i72 + 1` | `subi`, `sbci`, `adc` ×6, `sbci`: mixed |
| `i64 + 1` | `subi` + 7× `sbci`, consistent: correct |
Adding a runtime value to an `i128` is correct, as are `i128` shifts and multiplication.
**Versions.** Seen with LLVM 23.1.0 (rustc nightly-2026-08-14) and LLVM 23.1.5 (rustc 1.102.0-nightly).
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs