[llvm] [InstCombine] Fold select pattern with sub and negation to abs intrinsic (PR #156246)
    Yingwei Zheng via llvm-commits 
    llvm-commits at lists.llvm.org
       
    Sun Sep  7 07:43:06 PDT 2025
    
    
  
================
@@ -1153,6 +1153,15 @@ static Value *foldAbsDiff(ICmpInst *Cmp, Value *TVal, Value *FVal,
     return Builder.CreateBinaryIntrinsic(Intrinsic::abs, TI, Builder.getTrue());
   }
 
+  // Match: (A > B) ? (A - B) : (0 - (A - B)) --> abs(A - B)
+  // Recognize the pattern where we have sub, icmp, neg(sub), select
+  if (Pred == CmpInst::ICMP_SGT &&
+      match(TI, m_Sub(m_Specific(A), m_Specific(B))) &&
+      match(FI, m_Neg(m_Specific(TI))) && TI->hasNoSignedWrap()) {
----------------
dtcxzyw wrote:
```suggestion
  if (Pred == CmpInst::ICMP_SGT &&
      match(TI, m_NSWSub(m_Specific(A), m_Specific(B))) &&
      match(FI, m_Neg(m_Specific(TI)))) {
```
Can you add some tests that commute the operands?
```
(B < A) ? (A - B) : (0 - (A - B))
(A >= B) ? (A - B) : (0 - (A - B))
(A <= B) ? (0 - (A - B)) : (A - B)
(B <= A) ? (A - B) : (0 - (A - B))
```
https://github.com/llvm/llvm-project/pull/156246
    
    
More information about the llvm-commits
mailing list