heir icon indicating copy to clipboard operation
heir copied to clipboard

`compare-to-sign-rewrite` reverses less-than and greater-than comparisons

Open YGTao opened this issue 1 month ago • 0 comments

I found that compare-to-sign-rewrite uses the wrong subtraction order when rewriting less-than and greater-than comparisons.

For example, arith.cmpf olt is rewritten as:

0.5 * (sign(a - b) + 1)

However, HEIR's math_ext.sign returns -1 for negative inputs, 0 for zero, and 1 for positive inputs. This expression is therefore true when a > b, not when a < b.

Reproducer

Tested with HEIR commit bc7eabdddd0085e1048c87ecaa4e1f3439810dae.

func.func @less_than(%a: f32, %b: f32) -> i1 {
  %result = arith.cmpf olt, %a, %b : f32
  return %result : i1
}

Run:

heir-opt --compare-to-sign-rewrite repro.mlir

The generated computation uses sign(a - b) rather than sign(b - a).

For a = 1.0 and b = 2.0:

Expected: 1 < 2 = true

Actual rewrite:
  sign(1 - 2) = -1
  0.5 * (-1 + 1) = 0  (false)

The ogt rewrite has the opposite problem: it uses sign(b - a) for a > b. The corresponding integer comparison rewrites appear to have the same issue.

Possible cause

In lib/Transforms/CompareToSignRewrite/CompareToSignRewrite.cpp, the subtraction order appears to be reversed for the strict comparison predicates.

For unequal operands, the expected expressions would be:

a < b: 0.5 * (sign(b - a) + 1)
a > b: 0.5 * (sign(a - b) + 1)

Related PR #3553

I noticed that PR #3553 ("Approximate tensor comparisons, max/min and padded max pools") also modifies CompareToSignRewrite, but the proposed changes retain the reversed subtraction order.

In particular, the new cmpi_ugt FileCheck expectation still uses rhs - lhs before math_ext.sign, which corresponds to the opposite strict comparison.

It would be good to correct the comparison direction and add a value-based regression test as part of that work, rather than preserving the existing behavior in the new tests.

YGTao avatar Oct 28 '26 13:10 YGTao