[ExpandIRInsts] uitofp/sitofp of a wide integer to bfloat is rounded to float first, so the result can be off by one ulp
reproducer
godbolt: https://godbolt.org/z/PEWWx6bWf alive: https://alive2.llvm.org/ce/z/U5aVU_
target triple = "x86_64-unknown-linux-gnu"
define bfloat @f() {
%r = uitofp i129 8136949792 to bfloat
ret bfloat %r
}
define i32 @main() {
%r = call bfloat @f()
%b = bitcast bfloat %r to i16
%c = zext i16 %b to i32
ret i32 %c
}
$ opt -S '-passes=require<libcall-lowering-info>,function(expand-ir-insts)' repro.ll
define bfloat @f() {
...
itofp-if-end26:
...
%43 = or i32 %41, %40
%44 = bitcast i32 %43 to float
%45 = fptrunc float %44 to bfloat
...
$ llubi repro.ll; echo $?
243
$ opt -S '-passes=require<libcall-lowering-info>,function(expand-ir-insts)' repro.ll | llubi -; echo $?
242
$ alive-tv --disable-undef-input --disable-poison-input '-passes=require<libcall-lowering-info>,function(expand-ir-insts)' repro.ll
...
Transformation doesn't verify!
ERROR: Value mismatch
...
Source value: #x4ff3 (8153726976)
Target value: #x4ff2 (8120172544)
suggested fix
expandIToFP maps bfloat to float's mantissa width (FPMantissaWidth == 7 ? 23) and the isHalfTy() || isBFloatTy() arm fptruncs the rounded float, so an input with more than 24 significant bits is rounded twice (8136949792 first becomes the bfloat tie 242·2^25 + 2^24, which then rounds to even); half is unaffected because every integer below its overflow threshold is exact in float.
Make the float step round to odd: in itofp-sw-epilog, replace ((a | ((a >> 2) & 1)) + 1) >> 2 with (a >> 2) | ((a & 3) != 0) (the carry-out branch itofp-if-then20 then becomes dead); float keeps 16 more bits than bfloat, so the final fptrunc rounds once. Rounding directly at bfloat precision would also work.
Same double rounding as #234116, but in the IR expansion for integers wider than the target's limit (> 128 bits on x86-64), which a SelectionDAG fix does not reach.
Hi @dtcxzyw , @ChoKyuWon I reproduced this locally with the supplied IR: llubi exits 243 before expand-ir-insts and 242 afterward. My local build has only the AArch64 backend, so I used an AArch64 target triple, but the pass emits the same float-to-bfloat sequence described here. I’d like to work on a regression test and a fix in ExpandIRInsts. Is anyone already working on this?