[llvm] [InstCombine] Optimize addition of selects (PR #224477)

Tejas Joshi via llvm-commits llvm-commits at lists.llvm.org
Sun Sep 20 11:22:04 PDT 2026


================
@@ -2041,6 +2041,34 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
   if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
     return Res;
 
+  {
+    Value *X, *Y, *P0, *P1, *Base, *Default, *CmpP0EqC0, *SelYOrZero;
+    ConstantInt *C0, *C1;
+    // Transform:
+    //   ((P == C0 ? X : Default) + Base) + (P == C1 ? Y : 0)
+    // into:
+    //   Base + (P == C0 ? X : (Default + (P == C1 ? Y : 0)))
+    // This provides more opportunities for CSE and predication in
+    // exclusive-sum reduction patterns, which can reduce register pressure.
+    if (match(&I, m_c_Add(m_c_Add(m_Value(Base),
+                                  m_Select(m_Value(CmpP0EqC0), m_Value(X),
+                                           m_Value(Default))),
+                          m_Value(SelYOrZero))) &&
+        match(SelYOrZero, m_Select(m_SpecificICmp(CmpInst::ICMP_EQ, m_Value(P1),
+                                                  m_ConstantInt(C1)),
+                                   m_Value(Y), m_ZeroInt())) &&
+        match(CmpP0EqC0, m_SpecificICmp(CmpInst::ICMP_EQ, m_Value(P0),
+                                        m_ConstantInt(C0))) &&
+        P0 == P1 && !C0->isElementWiseEqual(C1)) {
----------------
Joshi-Tejas wrote:

I think `m_ConstantInt` does not match for vectors, so this won't be an issue (addressed the misleading `isElementWiseEqual`). Do you mean we would want to generalize this for vectors as well?

I believe InstCombine already has generalized reassociation when a new operand pairing simplifies, but this fold constructs a new select and therefore is not visible to simplifyBinOp. We could generalize this by recognizing mutually exclusive selects which I handled at https://github.com/llvm/llvm-project/pull/224478

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


More information about the llvm-commits mailing list