[llvm] [InstCombine] Fold fptoui(fadd(uitofp(X), C)) to X (PR #210588)
Arda Serdar Pektezol via llvm-commits
llvm-commits at lists.llvm.org
Sun Jul 19 08:33:35 PDT 2026
================
@@ -2581,10 +2580,57 @@ static Instruction *foldFPtoI(Instruction &FI, InstCombiner &IC) {
: BinaryOperator::CreateUDiv(X, C);
}
+// fptoui (fadd (uitofp X), C) --> X
+//
+// X is already an integer, so if 0 <= C < 1 and X fits exactly in the float,
+// adding C can't reach the next integer and fptoui just gives X back. This is
+// the (unsigned)((float)x + 0.5f) rounding trick.
+static Value *foldFPToUIOfUIToFPInc(FPToUIInst &FI) {
+ Value *X;
+ const APFloat *C;
+ if (!match(FI.getOperand(0), m_FAdd(m_UIToFP(m_Value(X)), m_APFloat(C))))
+ return nullptr;
+
+ Type *IntTy = FI.getType();
+ if (X->getType() != IntTy)
+ return nullptr;
+
+ // Need a finite C in [0, 1).
+ if (!C->isFinite() || C->isNegative() ||
+ C->compare(APFloat(C->getSemantics(), 1)) != APFloat::cmpLessThan)
+ return nullptr;
+
+ // The uitofp has to be lossless, so the whole int type must fit in the
+ // mantissa.
+ unsigned Width = IntTy->getScalarSizeInBits();
+ int Mantissa =
+ FI.getOperand(0)->getType()->getScalarType()->getFPMantissaWidth();
+ if (Mantissa < 0 || Width > static_cast<unsigned>(Mantissa))
+ return nullptr;
+
+ // Also check the biggest value + C doesn't round up to 2^Width. Testing the
+ // top of the range is enough since the spacing between floats only grows.
+ const fltSemantics &Sem = C->getSemantics();
----------------
pektezol wrote:
Would it be better to move this above since `C->getSemantics()` gets repeated?
https://github.com/llvm/llvm-project/pull/210588
More information about the llvm-commits
mailing list