[llvm] [InstCombine] Generalize ignoreSignBitOfZero/NaN to handle more cases (PR #141015)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Tue May 27 02:50:15 PDT 2025


================
@@ -6357,6 +6357,118 @@ std::optional<bool> llvm::computeKnownFPSignBit(const Value *V, unsigned Depth,
   return Known.SignBit;
 }
 
+/// Return true if the sign bit of result can be ignored by the user when the
+/// result is zero.
+bool llvm::ignoreSignBitOfZero(const Use &U) {
+  auto *User = cast<Instruction>(U.getUser());
+  if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
+    if (FPOp->hasNoSignedZeros())
+      return true;
+  }
+
+  switch (User->getOpcode()) {
+  case Instruction::FPToSI:
+  case Instruction::FPToUI:
+    return true;
+  case Instruction::FCmp:
+    // fcmp treats both positive and negative zero as equal.
+    return true;
+  case Instruction::Call:
+    if (auto *II = dyn_cast<IntrinsicInst>(User)) {
+      switch (II->getIntrinsicID()) {
+      case Intrinsic::fabs:
+        return true;
+      case Intrinsic::copysign:
+        return U.getOperandNo() == 0;
+      case Intrinsic::is_fpclass:
+      case Intrinsic::vp_is_fpclass: {
+        auto Test =
+            static_cast<FPClassTest>(
+                cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
+            FPClassTest::fcZero;
+        return Test == FPClassTest::fcZero || Test == FPClassTest::fcNone;
+      }
+      default:
+        return false;
+      }
+    }
+    return false;
+  default:
+    return false;
+  }
+}
+
+/// Return true if the sign bit of result can be ignored by the user when the
+/// result is NaN.
+bool llvm::ignoreSignBitOfNaN(const Use &U) {
+  auto *User = cast<Instruction>(U.getUser());
+  if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
+    if (FPOp->hasNoNaNs())
+      return true;
+  }
+
+  switch (User->getOpcode()) {
+  case Instruction::FPToSI:
+  case Instruction::FPToUI:
+    return true;
+  // Proper FP math operations ignore the sign bit of NaN.
----------------
nikic wrote:

Reference: https://llvm.org/docs/LangRef.html#behavior-of-floating-point-nan-values

> the result has a non-deterministic sign

https://github.com/llvm/llvm-project/pull/141015


More information about the llvm-commits mailing list