[llvm] [VectorCombine] Fold vector sign-bit checks (PR #175194)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Fri Jan 16 08:01:28 PST 2026
================
@@ -4043,6 +4044,203 @@ bool VectorCombine::foldCastFromReductions(Instruction &I) {
return true;
}
+/// Fold:
+/// icmp pred (reduce.{add,or,and,umax,umin}(signbit_extract(x))), C
+/// into:
+/// icmp sgt/slt (reduce.{or,umax,and,umin}(x)), -1/0
+///
+/// Sign-bit reductions produce values with known semantics:
+/// - reduce.{or,umax}: 0 if no element is negative, 1 if any is
+/// - reduce.{and,umin}: 1 if all elements are negative, 0 if any isn't
+/// - reduce.add: count of negative elements (0 to NumElts)
+///
+/// We transform to a direct sign check on reduce.{or,umax} or
+/// reduce.{and,umin} without explicit sign-bit extraction.
+///
+/// In spirit, it's similar to foldSignBitCheck in InstCombine.
+bool VectorCombine::foldSignBitReductionCmp(Instruction &I) {
+ CmpPredicate Pred;
+ Value *ReduceOp;
+ const APInt *CmpVal;
+ if (!match(&I, m_ICmp(Pred, m_Value(ReduceOp), m_APInt(CmpVal))))
+ return false;
+
+ auto *II = dyn_cast<IntrinsicInst>(ReduceOp);
+ if (!II || !II->hasOneUse())
+ return false;
+
+ Intrinsic::ID OrigIID = II->getIntrinsicID();
+ switch (OrigIID) {
+ case Intrinsic::vector_reduce_or:
+ case Intrinsic::vector_reduce_umax:
+ case Intrinsic::vector_reduce_and:
+ case Intrinsic::vector_reduce_umin:
+ case Intrinsic::vector_reduce_add:
+ break;
+ default:
+ return false;
+ }
+
+ Value *ReductionSrc = II->getArgOperand(0);
+ if (!ReductionSrc->hasOneUse())
+ return false;
+
+ auto *VecTy = dyn_cast<FixedVectorType>(ReductionSrc->getType());
+ if (!VecTy)
+ return false;
+
+ unsigned BitWidth = VecTy->getScalarSizeInBits();
+ unsigned NumElts = VecTy->getNumElements();
+
+ // Match sign-bit extraction: shr X, (bitwidth-1)
+ Value *X;
+ if (!match(ReductionSrc, m_Shr(m_Value(X), m_SpecificInt(BitWidth - 1))))
+ return false;
+
+ // MaxVal: 1 for or/and/umax/umin, NumElts for add
+ APInt MaxVal(CmpVal->getBitWidth(),
+ OrigIID == Intrinsic::vector_reduce_add ? NumElts : 1);
+
+ // In addition to direct comparisons EQ 0, NE 0, EQ 1, NE 1, etc. we support
+ // inequalities that can be interpreted as either EQ or NE considering a
+ // rather narrow range of possible value of sign-bit reductions.
+ bool IsEq;
+ bool TestsHigh;
+ if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) {
+ // EQ/NE: comparison must be against 0 or MaxVal
+ if (!CmpVal->isZero() && *CmpVal != MaxVal)
+ return false;
+ IsEq = Pred == ICmpInst::ICMP_EQ;
+ TestsHigh = *CmpVal == MaxVal;
+ } else if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) &&
+ *CmpVal == MaxVal) {
+ // s/ult MaxVal -> ne MaxVal
+ IsEq = false;
+ TestsHigh = true;
+ } else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT) &&
----------------
dtcxzyw wrote:
ICmpInst::isGT
https://github.com/llvm/llvm-project/pull/175194
More information about the llvm-commits
mailing list