[llvm] [ValueTracking] Fold max/min when incrementing/decrementing by 1 (PR #142466)

Alex MacLean via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 3 07:55:58 PDT 2025


================
@@ -8388,6 +8388,24 @@ static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
     }
   }
 
+  // (X > Y) ? X : (Y - 1) ==> MIN(X, Y - 1)
+  // (X < Y) ? X : (Y + 1) ==> MAX(X, Y + 1)
+  // When overflow corresponding to the sign of the comparison is poison.
+  // Note that the UMIN case is not possible as we canonicalize to addition.
+  if (CmpLHS == TrueVal) {
+    if (Pred == CmpInst::ICMP_SGT &&
+        match(FalseVal, m_NSWAddLike(m_Specific(CmpRHS), m_ConstantInt<1>())))
+      return {SPF_SMAX, SPNB_NA, false};
+
+    if (Pred == CmpInst::ICMP_SLT &&
+        match(FalseVal, m_NSWAddLike(m_Specific(CmpRHS), m_ConstantInt<-1>())))
+      return {SPF_SMIN, SPNB_NA, false};
+
+    if (Pred == CmpInst::ICMP_UGT &&
+        match(FalseVal, m_NUWAddLike(m_Specific(CmpRHS), m_ConstantInt<1>())))
+      return {SPF_UMAX, SPNB_NA, false};
+  }
----------------
AlexMaclean wrote:

Unfortunately, it seems this case is not possible. We canonicalize `sub nuw %x, 1` to `add %x, -1`, discarding the `nuw` flag as unsigned wrap is now guaranteed unless %x is 0. I've noted that this case isn't possible in a comment. Is there a work around to this problem you can think of?

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


More information about the llvm-commits mailing list