<table border="1" cellspacing="0" cellpadding="8">
<tr>
<th>Issue</th>
<td>
<a href=https://github.com/llvm/llvm-project/issues/97975>97975</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
LLVM lowers consecutive `half` operations with too much precision on several backends
</td>
</tr>
<tr>
<th>Labels</th>
<td>
new issue
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
beetrees
</td>
</tr>
</table>
<pre>
Consider the following IR:
```llvm
define half @f(half %a, half %b, half %c) {
%d = fadd half %a, %b
%e = fadd half %d, %c
ret half %e
}
```
On backends without native `half` support, LLVM generally lowers `half` by converting to `float`, performing the desired operation, and then converting back to `half`. For this to be a valid lowering, a conversion back to `f16` must occur after each operation, otherwise the excess precision of `float` will affect the result. For example `65504.0 + 65504.0 + -65504.0` equals infinity if each operation is done at `half` precision, but will result in `65504.0` if the intermediate value is not rounded to a `half` but instead kept as a `float`. This excess runtime precision can lead to miscompilations similar to #89885.
However, it appears that on several backends LLVM will fail to round the intermediate result of consecutive `half` operations, leading to these kind of bugs. I'm filing this as a single issue rather than a separate issue for each backend as I believe this is an issue with LLVM's default handling of `half` operations rather than a problem in any specific backend (for instance, AFAIK the only backend-specific code LoongArch has for handling `half` was added in #94456).
By inspecting the assembly LLVM emits, I've discovered that at least the following backends appear to be affected (in brackets are a specific target triple that I've checked):
- AVR (`avr-unknown-unknown`)
- Hexagon (`hexagon-unknown-linux-musl`)
- LoongArch (`loongarch64-unknown-linux-gnu`)
- M68k (`m68k-unknown-linux-gnu`)
- MIPS (`mips64el-unknown-linux-gnuabi64`)
- MSP430 (`msp430-none-elf`)
- PowerPC (`powerpc64le-unknown-linux-gnu`)
- SPARC (`sparc64-unknown-linux-gnu`)
- WASM (`wasm32-unknown-wasi`): Already reported in #96437
I also noticed that 32-bit ARM has this problem in LLVM 18 but not on the `main` branch. Looking through the issue tracker, it seems it's likely that this was fixed by #80440.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.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