[llvm] [InstCombine] Fold icmp eq/ne X, select(icmp pred X, P, C1, C2) to set membership (PR #226756)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Sun Sep 27 08:59:32 PDT 2026


================
@@ -4553,6 +4553,32 @@ Instruction *InstCombinerImpl::foldSelectICmp(CmpPredicate Pred, SelectInst *SI,
     return SelectInst::Create(SI->getOperand(0), Op1, Op2, "", nullptr, SI);
   }
 
+  // Fold icmp eq/ne X, select(icmp pred X, P, C1, C2)
+  // When the select condition compares X with a constant P and the select
+  // arms are constants C1/C2, we can fold to a set membership test.
+  // Example: X == select(X >s 0, 2, 0) -> (X == 2) | (X == 0)
+  // This is valid when C1 satisfies the condition (C1 >s 0) and C2 does not.
+  if (ICmpInst::isEquality(Pred)) {
----------------
dtcxzyw wrote:

We may generalize it to handle other predicates.
```
icmp pred1 X, select (icmp pred2 X, C0), C1, C2 -> (icmp pred1 X C1) | (icmp pred1 X C2) 
iff (icmp pred1 X, C1) implies (icmp pred2 X, C0) and (icmp pred1 X, C2) implies !(icmp pred2 X, C0)
icmp pred1 X, select (icmp pred2 X, C0), C1, C2 -> (icmp pred1 X C1) & (icmp pred1 X C2) 
iff !(icmp pred1 X, C1) implies (icmp pred2 X, C0) and !(icmp pred1 X, C2) implies !(icmp pred2 X, C0)
``` 

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


More information about the llvm-commits mailing list