[llvm] [InstCombine] Fold sext of an nsw binop on trunc nsw into a wide nsw … (PR #228530)
Alexey Bataev via llvm-commits
llvm-commits at lists.llvm.org
Mon Oct 5 16:53:00 PDT 2026
================
@@ -1922,6 +1922,72 @@ bool TypeEvaluationHelper::canEvaluateSExtdPred(Value *V, Type *Ty) {
return false;
}
+/// Fold
+/// sext (binop nsw (trunc nsw X to iN), Y) to iM
+/// to
+/// binop nsw X, sext(Y)
+/// when X already has type iM. Y may be a constant, another trunc nsw back to
+/// an iM value, or any other iN value. trunc nsw means X fits in iN, and nsw
+/// on the narrow binop means the result also fits in iN, so the sign-extended
+/// value is that same operation on X and the sign-extended other operand. The
+/// wide binop is nsw because its result fits in iN.
+///
+/// A constant Y is folded into sext(Y) immediately. A non-constant Y becomes
+/// an explicit sext, so a loop-invariant narrow operand stays an nsw
+/// recurrence.
+///
+/// EvaluateInDifferentType rebuilds the binop without overflow flags. The
+/// sign-bit check then fails and visitSExt emits a shl/ashr pair, which SCEV
+/// cannot treat as a non-wrapping recurrence.
+static Instruction *
+foldSExtOfNSWBinOpOfTrunc(SExtInst &Sext, const DataLayout &DL,
+ InstCombiner::BuilderTy &Builder) {
+ auto *BinOp = dyn_cast<OverflowingBinaryOperator>(Sext.getOperand(0));
+ if (!BinOp || !BinOp->hasNoSignedWrap())
----------------
alexey-bataev wrote:
```suggestion
if (!BinOp || !BinOp->hasOneUse() || !BinOp->hasNoSignedWrap())
```
https://github.com/llvm/llvm-project/pull/228530
More information about the llvm-commits
mailing list