[llvm] [InstCombine] Add missing constant check (PR #170068)
Yingwei Zheng via llvm-commits
llvm-commits at lists.llvm.org
Sun Nov 30 19:34:55 PST 2025
https://github.com/dtcxzyw created https://github.com/llvm/llvm-project/pull/170068
`cast<Constant>` is not guarded by a type check during canonicalization of predicates. This patch adds a type check in the outer if to avoid the crash. `dyn_cast` may introduce another nested if, so I just use `isa<Constant>` instead.
Address the crash reported in https://github.com/llvm/llvm-project/pull/153053#issuecomment-3593914124.
>From ce3ae4f136cf5f277f8b959d30ead9a080859f45 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng <dtcxzyw2333 at gmail.com>
Date: Mon, 1 Dec 2025 11:28:26 +0800
Subject: [PATCH] [InstCombine] Add missing constant check
---
.../Transforms/InstCombine/InstCombineSelect.cpp | 1 +
.../Transforms/InstCombine/saturating-add-sub.ll | 16 ++++++++++++++++
2 files changed, 17 insertions(+)
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
index e7dc366b13798..c9f51e4b294b1 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
@@ -1163,6 +1163,7 @@ static Value *canonicalizeSaturatedAddSigned(ICmpInst *Cmp, Value *TVal,
// (X >= Y) ? INT_MAX : (X + C) --> sadd.sat(X, C)
// where Y is INT_MAX - C or INT_MAX - C - 1, and C > 0
if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) &&
+ isa<Constant>(Cmp1) &&
match(FVal, m_Add(m_Specific(Cmp0), m_StrictlyPositive(C)))) {
APInt IntMax =
APInt::getSignedMaxValue(Cmp1->getType()->getScalarSizeInBits());
diff --git a/llvm/test/Transforms/InstCombine/saturating-add-sub.ll b/llvm/test/Transforms/InstCombine/saturating-add-sub.ll
index c0ad5818e448a..1294f867f07c0 100644
--- a/llvm/test/Transforms/InstCombine/saturating-add-sub.ll
+++ b/llvm/test/Transforms/InstCombine/saturating-add-sub.ll
@@ -2671,3 +2671,19 @@ define i8 @neg_neg_constant(i8 %x, i8 %y) {
%s = select i1 %cmp, i8 127, i8 %d
ret i8 %s
}
+
+; Make sure we don't crash in this case.
+define i32 @pr153053_strict_pred_with_nonconstant_rhs(i32 %x, i32 %y) {
+; CHECK-LABEL: @pr153053_strict_pred_with_nonconstant_rhs(
+; CHECK-NEXT: entry:
+; CHECK-NEXT: [[CMP:%.*]] = icmp slt i32 [[X:%.*]], [[Y:%.*]]
+; CHECK-NEXT: [[ADD:%.*]] = add i32 [[X]], 1
+; CHECK-NEXT: [[RES:%.*]] = select i1 [[CMP]], i32 [[ADD]], i32 2147483647
+; CHECK-NEXT: ret i32 [[RES]]
+;
+entry:
+ %cmp = icmp slt i32 %x, %y
+ %add = add i32 %x, 1
+ %res = select i1 %cmp, i32 %add, i32 2147483647
+ ret i32 %res
+}
More information about the llvm-commits
mailing list