<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/140992>140992</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [InstCombine] Do not rely on the nsz flag on fcmp
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            metabug,
            miscompilation,
            llvm:instcombine,
            floating-point
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
            dtcxzyw
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          dtcxzyw
      </td>
    </tr>
</table>

<pre>
    As discussed in https://discourse.llvm.org/t/rfc-clarify-the-behavior-of-fp-operations-on-bit-strings-with-nsz-flag/85981, forbidding nsz flags in bitwise FP operations (select/phi/copysign/fabs/fneg) is infeasible as it blocks some common optimizations (e.g., `(X < 0.0) ? -X : X -> fabs(X)`). I am working on a better formal definition for the nsz flag (and other rewrite-based flags).

However, the nsz flag on fcmp is meaningless since fcmp treats both positive and negative zero as equal. It allows us to freely add nsz: https://alive2.llvm.org/ce/z/x2iNNo
Unfortunately, I notice that some existing optimizations in InstCombine rely on the nsz flag on fcmp. It is a strange behavior and causes some miscompilations (e.g., https://alive2.llvm.org/ce/z/J9ZBXX).

I have created a [tool](https://github.com/dtcxzyw/llvm-tools/blob/main/fcmp-nsz.py) for metamorphic testing, to ensure that the nsz flag on fcmp doesn't affect the optimized IR.

</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJyMlMGO4zYMhp9GuRAOHDmZ2AcfMjM1mh4WRYECg95km7bZlSVXopNJnr6gk53ZoItFT4FFheT_8xNNjNQ7xFLtnpXWLTfv18tZaa12rysz8-BDeT9c1b69lIcILcVmjhFbIAcD8xRVdlC6UrqSkJ9DxLW1p3HtQ690xUpXoWuSxppA3SXhAZMaB3MiHxLfJd2U-AmDYfIuJt4lNXESOZDrY3ImHhIXr0lnjSTLd0W-UfoFOh9qaltyPbh4BQlHaagmPlNEqH6Hz6ygdB7R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