[llvm] [InstCombine] Fold icmp in select to smin (PR #87157)

Krishna Narayanan via llvm-commits llvm-commits at lists.llvm.org
Sun Apr 14 04:23:31 PDT 2024


================
@@ -1689,40 +1689,35 @@ static Value *foldSelectInstWithICmpConst(SelectInst &SI, ICmpInst *ICI,
 
 static Value *foldSelectInstWithICmpOr(SelectInst &SI, ICmpInst *ICI,
                                        InstCombiner::BuilderTy &Builder) {
-
-  // a > -1 ? 1 : (a | value) --> smin(1, a | value)
-  // a >= 0 ? 1 : (a | value) --> smin(1, a | value)
+  // a > -1 ? 1 : ( a | (+ve)value) --> smin(1, a | (+ve)value)
+  // a < -1 ? ( a | (+ve)value) : 1 --> smin(1, a | (+ve)value)
+  Value *C;
   const APInt *Cmp;
   Value *A = ICI->getOperand(0);
   Value *B = ICI->getOperand(1);
-  Type *Ty = SI.getType();
   Value *TVal = SI.getTrueValue();
   Value *FVal = SI.getFalseValue();
-  Constant *One = ConstantInt::get(Ty, 1);
-  Constant *NegOne = ConstantInt::get(Ty, -1);
-  Constant *Zero = Constant::getNullValue(Ty);
-  CmpInst::Predicate Pred = ICI->getPredicate();
+  ICmpInst::Predicate Pred = ICI->getPredicate();
 
-  if (!match(B, m_APIntAllowUndef(Cmp)))
+  if (!match(B, m_APInt(Cmp)))
     return nullptr;
 
-  // Swap TVal, FVal for Inverse
-  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
+  if (Pred == ICmpInst::ICMP_SLT)
     std::swap(TVal, FVal);
 
   if (!(match(TVal, m_One()) || match(TVal, m_Zero()) ||
         match(TVal, m_AllOnes())) ||
-      !match(FVal, m_Or(m_Value(A), m_StrictlyPositive())))
+      !(match(FVal, m_Or(m_Value(A), m_Value(C)))))
+    return nullptr;
+
+  if (!match(C, m_StrictlyPositive()))
----------------
Krishna-13-cyber wrote:

Yes, there was no specific reason/point to do this. 
```
if (....!(match(FVal, m_Or(m_Value(A), m_Value(C)))))
    return nullptr;
if (!match(C, m_StrictlyPositive()))
    return nullptr;
```
```
if (...... !(match(FVal, m_Or(m_Value(A), m_StrictlyPositive()))))
```
Either of them failed to pass the llvm.assume test cases as the expression don't fold, so tried using the earlier approach.
As this fold is only applicable for positive values, we cannot match any other values other than this as it would lead to invalid transform. 
Not sure what constraint or needful I am missing out to handle these generic testcases, would need some assistance in this.

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


More information about the llvm-commits mailing list