Issue 241363
Summary [X86] Redundant zero-extension of a byte-swapped 16-bit load (rolw + movzwl, movbew + movzwl)
Labels new issue
Assignees
Reporter Sernior
    Reading a big-endian `u16` and widening it, the usual way to parse a length-prefixed binary
protocol, emits a zero-extension that is redundant (generic x86-64) or avoidable (MOVBE targets).
On Zen 4 it costs one cycle on the dependency chain.

https://godbolt.org/z/6zvqEGxbK

```llvm
define i64 @load_bswap16_zext(ptr %p) {
  %v = load i16, ptr %p, align 1
  %s = call i16 @llvm.bswap.i16(i16 %v)
  %z = zext i16 %s to i64
  ret i64 %z
}
declare i16 @llvm.bswap.i16(i16)
```

`llc -O3` (trunk):

```asm
movzwl  (%rdi), %eax     # bits 16-63 are now zero
rolw $8, %ax          # does not touch bits 16-63
movzwl  %ax, %eax        # redundant
```

`llc -O3 -mcpu=znver4` (trunk):

```asm
movbew  (%rdi), %ax      # writes only bits 0-15
movzwl  %ax, %eax        # needed here, but avoidable
```

Expected: drop the second `movzwl` in the generic case. On MOVBE targets, when the result is
zero-extended, `movzwl` + `rolw` (or `xorl %eax, %eax` + `movbew`) avoids the extra instruction.
The `xorl` form is the idiom LLVM already uses for a zero-extended SETcc
(`xorl %eax, %eax; cmpq %rsi, %rdi; sete %al`: https://godbolt.org/z/6YGM4oq1a).

If the extension is kept on purpose to avoid a partial-register merge on older cores, the
`xorl` + `movbew` form avoids it too, for the same reason it is used before SETcc.

Latency on Zen 4 (Ryzen 5 7600X), measured with a dependency chain load -> swap -> extend ->
`lea (%rdi,%rax)` -> next load, L1 hits:

| Sequence | Cycles per step |
|---|---|
| `movzwl` + `lea` (no swap, wrong value: lower bound only) | 5.0 |
| `movzwl` + `rolw` + `lea` | 6.0 |
| `xorl` + `movbew` + `lea` | 6.0 |
| `movzwl` + `rolw` + `movzwl` + `lea` (current, generic) | 7.0 |
| `movbew` + `movzwl` + `lea` (current, znver4) | 7.0 |

Reproduces with Clang 18, 20 and trunk: llc trunk on Compiler Explorer (2026-11-11) and Clang
18.1.3 (Ubuntu 24.04).
I can share the microbenchmark, and I would be glad to work on a patch if this is welcome.

This report was prepared with the help of an AI assistant (Claude), which ran the measurements on
my machine; I reviewed the analysis and checked the generated code on Compiler Explorer.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to