[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:01 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())
+    return nullptr;
+
+  auto Opc = static_cast<Instruction::BinaryOps>(BinOp->getOpcode());
+  if (Opc != Instruction::Add && Opc != Instruction::Sub &&
+      Opc != Instruction::Mul)
+    return nullptr;
+
+  // V is the widened operand. NeedsSExt means V still has the narrow type and
+  // must be sign-extended. FromWideTrunc means V is an existing iM value
+  // recovered from trunc nsw.
+  struct WideOp {
+    Value *V = nullptr;
+    bool NeedsSExt = false;
+    bool FromWideTrunc = false;
+  };
+  Type *DestTy = Sext.getType();
+  auto widenOperand = [&](Value *V) -> WideOp {
+    Value *X;
+    if (match(V, m_NSWTrunc(m_Value(X))) && X->getType() == DestTy)
+      return {X, false, true};
+    if (auto *C = dyn_cast<Constant>(V))
+      return {ConstantFoldIntegerCast(C, DestTy, /*IsSigned=*/true, DL), false,
+              false};
+    // Any other same-typed value sign-extends to its mathematical value.
+    // This is only used when the other operand recovers an existing iM value,
+    // so the fold does not widen arithmetic that was never connected to one.
+    if (V->getType() == BinOp->getType())
+      return {V, true, false};
+    return {};
+  };
----------------
alexey-bataev wrote:

```suggestion
  // `op %t, %t` would read X twice in the wide type.
  Value *Op0 = BinOp->getOperand(0), *Op1 = BinOp->getOperand(1);
  if (Op0 == Op1)
    return nullptr;
```

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


More information about the llvm-commits mailing list