llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[InstCombine] fptrunc(fadd(fpext bfloat, fpext bfloat)) to half is narrowed although half cannot hold bfloat values

Open ChoKyuWon opened this issue 1 month ago • 1 comments

Reproducer

godbolt: https://godbolt.org/z/8To3EEohb (opt -passes=instcombine, and the program run at -O0 and -O2)

@a = global bfloat 0xR4780
@b = global bfloat 0xRC780
@fmt = private constant [4 x i8] c"%g\0A\00"

define half @f(bfloat %a, bfloat %b) {
  %x = fpext bfloat %a to double
  %y = fpext bfloat %b to double
  %sum = fadd double %x, %y
  %r = fptrunc double %sum to half
  ret half %r
}

define i32 @main() {
  %va = load volatile bfloat, ptr @a
  %vb = load volatile bfloat, ptr @b
  %r = call half @f(bfloat %va, bfloat %vb)
  %d = fpext half %r to double
  call i32 (ptr, ...) @printf(ptr @fmt, double %d)
  ret i32 0
}

declare i32 @printf(ptr, ...)
$ clang -O0 repro.ll && ./a.out
0
$ clang -O2 repro.ll && ./a.out
-nan

InstCombine narrows the fadd to half:

define half @f(bfloat %a, bfloat %b) {
  %x = fpext bfloat %a to double
  %y = fpext bfloat %b to double
  %1 = fptrunc double %x to half
  %2 = fptrunc double %y to half
  %r = fadd half %1, %2
  ret half %r
}

65536 + -65536 is exactly +0.0 in double, so @f returns +0.0. After the fold, each operand is converted to half first. 65536 is above the largest finite half (65504), so the operands become +inf and -inf, and their sum is NaN.

The narrowing in InstCombinerImpl::visitFPTrunc (OpWidth >= 2*DstWidth+1 && DstWidth >= SrcWidth) compares only significand widths. bfloat has fewer significand bits than half but a much wider exponent range, so converting a bfloat value to half can overflow or underflow. Alive2 also finds the underflow side. The web instance times out on this query, so this is from a local alive-tv built at the same trunk:

$ alive-tv --smt-to=120000 --disable-undef-input --disable-poison-input --passes=instcombine f.ll   # @f only
Transformation doesn't verify!

ERROR: Value mismatch

Example:
bfloat %a = #x8108 (-0.000000000000?)
bfloat %b = #x0000 (+0.0)
...
Source value: #x8000 (-0.0)
Target value: #x0000 (+0.0)

The fmul and fdiv cases use the same kind of significand-width-only check and are narrowed the same way. For example, with fmul and %b = 2^-16, -O0 prints 1 and -O2 prints inf.

This is not a recent regression. opt 11.0.0 already narrowed this function, at that time with a bitcast from bfloat to half.

Related: #82493 fixed a similar mix-up of bfloat and half in this code for frem. #202489 changed how this fold handles ninf; this case has no fast-math flags.

Disclaimer: This test case was generated by a fuzzer, and the report was written with LLM assistance.

ChoKyuWon avatar Oct 07 '26 04:10 ChoKyuWon

Hi @ChoKyuWon,

I've opened a PR that fixes this: https://github.com/llvm/llvm-project/pull/230379

RS-Gits avatar Oct 09 '26 06:10 RS-Gits