[llvm] [llvm] Optimize usub.sat fix for #79690 (PR #151044)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Mon Aug 18 09:53:21 PDT 2025
================
@@ -1993,6 +1991,137 @@ Value *InstCombinerImpl::foldSelectWithConstOpToBinOp(ICmpInst *Cmp,
return BinOp;
}
+/// Folds:
+/// %a_sub = call @llvm.usub.sat(x, IntConst1)
+/// %b_sub = call @llvm.usub.sat(y, IntConst2)
+/// %or = or %a_sub, %b_sub
+/// %cmp = icmp eq %or, 0
+/// %sel = select %cmp, 0, MostSignificantBit
+/// into:
+/// %a_sub' = usub.sat(x, IntConst1 - MostSignificantBit)
+/// %b_sub' = usub.sat(y, IntConst2 - MostSignificantBit)
+/// %or = or %a_sub', %b_sub'
+/// %and = and %or, MostSignificantBit
+/// Likewise, for vector arguments as well.
+static Instruction *foldICmpUSubSatWithAndForMostSignificantBitCmp(
+ SelectInst &SI, ICmpInst *ICI, InstCombiner::BuilderTy &Builder) {
+ auto *CI = dyn_cast<ICmpInst>(SI.getCondition());
+ if (!CI) {
+ return nullptr;
+ }
+
+ Value *CmpLHS = CI->getOperand(0);
+ Value *CmpRHS = CI->getOperand(1);
+ if (!match(CmpRHS, m_Zero())) {
+ return nullptr;
+ }
+ auto Pred = CI->getPredicate();
+ auto *TrueVal = SI.getTrueValue();
+ auto *FalseVal = SI.getFalseValue();
+
+ if (Pred != ICmpInst::ICMP_EQ && Pred != llvm::ICmpInst::ICMP_NE)
+ return nullptr;
+
+ // Match: icmp eq (or (usub.sat A, IntConst1), (usub.sat B, IntConst2)), 0
+ Value *A, *B;
+ ConstantInt *IntConst1, *IntConst2, *PossibleMSBInt;
+
+ if (match(CmpLHS, m_Or(m_Intrinsic<Intrinsic::usub_sat>(
+ m_Value(A), m_ConstantInt(IntConst1)),
----------------
dtcxzyw wrote:
Use `m_APInt`, then you can avoid repeating code to handle vector splats.
If you want to handle non-splat vectors as well, use constant folding helpers. But it is not enforced: https://llvm.org/docs/InstCombineContributorGuide.html#guidelines-for-reviewers.
IIRC the original motivating case only has constant splats.
https://github.com/llvm/llvm-project/pull/151044
More information about the llvm-commits
mailing list