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

[MLIR] Missed Optimization: FP16 division expansion drops nnan

Open dev-816 opened this issue 2 months ago • 1 comments

-llvm-optimize-for-nvvm-target drops nnan when expanding an FP16 llvm.fdiv. In the example below, nnan allows the NaN check to fold to false. After expansion, the replacement llvm.fptrunc has no fast-math flags, and the comparison remains. Losing this information may prevent subsequent elimination of the NaN check.

The expansion should preserve the applicable fast-math information on the replacement result.

Code Example

input.mlir

module {
  llvm.func @nnan(%a: f16, %b: f16) -> i1 {
    %q = llvm.fdiv %a, %b {fastmathFlags = #llvm.fastmath<nnan>} : f16
    %isnan = llvm.fcmp "uno" %q, %q : f16
    llvm.return %isnan : i1
  }
}

Relevant output after expansion:

%14 = llvm.select %13, %5, %8 : i1, f32
%15 = llvm.fptrunc %14 : f32 to f16
%16 = llvm.fcmp "uno" %15, %15 : f16
llvm.return %16 : i1

Command

mlir-opt input.mlir -llvm-optimize-for-nvvm-target

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25

dev-816 avatar Oct 02 '26 04:10 dev-816

@llvm/issue-subscribers-mlir

Author: CC_Fans (dev-816)

`-llvm-optimize-for-nvvm-target` drops `nnan` when expanding an FP16 `llvm.fdiv`. In the example below, `nnan` allows the NaN check to fold to `false`. After expansion, the replacement `llvm.fptrunc` has no fast-math flags, and the comparison remains. Losing this information may prevent subsequent elimination of the NaN check.

The expansion should preserve the applicable fast-math information on the replacement result.

Code Example

input.mlir

module {
  llvm.func @<!-- -->nnan(%a: f16, %b: f16) -&gt; i1 {
    %q = llvm.fdiv %a, %b {fastmathFlags = #llvm.fastmath&lt;nnan&gt;} : f16
    %isnan = llvm.fcmp "uno" %q, %q : f16
    llvm.return %isnan : i1
  }
}

Relevant output after expansion:

%14 = llvm.select %13, %5, %8 : i1, f32
%15 = llvm.fptrunc %14 : f32 to f16
%16 = llvm.fcmp "uno" %15, %15 : f16
llvm.return %16 : i1

Command

mlir-opt input.mlir -llvm-optimize-for-nvvm-target

Version: 6f54fe6b6fb22f8a335fd19b94049fc769dfea25