← Back to Pull requests

[InstCombine] Fold binop of selects with implied conditions when only one arm simplifies #224477

Merged
Joshi-Tejas merged 5 files (391 lines) on Nov 12, 2026 11:29 UTC
View on GitHub
Joshi-Tejas Joshi-Tejas commented on Sep 17, 2026 23:44 UTC
Author

Transform:

(P == C0 ? X : Def) + (P == C1 ? Y : 0)

into:

P == C0 ? X : (Def + (P == C1 ? Y : 0))

More generally, when both operands of a binop are one-use selects and the condition of one implies the condition of the other, so that one arm simplifies once the other select is resolved, distribute the binop over the select and create the remaining arm.

This allows for more parts of the expression to be predicated, and allows more CSE and reuse of nodes calculated as part of an exclusive sum algorithm.

Proof: https://alive2.llvm.org/ce/z/vvfiTF.

Co-authored-by: Lewis Crawford <lcrawford@nvidia.com>

Diff: 391 lines (+344 / -47) across 5 files Reviewer: antoniofrighetto Review duration: 79904m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.45) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.45 · 391 lines diff across 5 files
0.45
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.88 · 5 substantive comment(s)
0.88
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.357
Real PR Conversation Timeline
24 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Sep 17, 2026 23:45 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-transforms

Author: Tejas Joshi (Joshi-Tejas)

<details>
<summary>Changes</summary>

Transform:

((P == C0 ? X : Def) + Base) + (P == C1 ? Y : 0)

into:

Base + (P == C0 ? X : (Def + (P == C1 ? Y : 0)))

This allows for more parts of the expression to be predicated, and allows more CSE and reuse of nodes calculated as part of an exclusive sum algorithm.

https://alive2.llvm.org/ce/z/ukGm5g

Originally authored by: @<!-- -->LewisCrawford

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

2 Files Affected:

  • (modified) llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp (+28)

  • (added) llvm/test/Transforms/InstCombine/select-sum.ll (+25)
  • ``````

    diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
    index 317d587ddedd6..9991dc6ab9bc7 100644
    --- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
    +++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
    @@ -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)) {
    +
    +      Value *DefaultPlusYOrZero = Builder.CreateAdd(Default, SelYOrZero);
    +      Value *XorDorYPlusD =
    +          Builder.CreateSelect(CmpP0EqC0, X, DefaultPlusYOrZero);
    +      Value *NewAdd = Builder.CreateAdd(Base, XorDorYPlusD);
    +      return replaceInstUsesWith(I, NewAdd);
    +    }
    +  }
    +
       if (Instruction *Res = foldDivCeil(I))
         return Res;
     
    diff --git a/llvm/test/Transforms/InstCombine/select-sum.ll b/llvm/test/Transforms/InstCombine/select-sum.ll
    new file mode 100644
    index 0000000000000..201e56b8df759
    --- /dev/null
    +++ b/llvm/test/Transforms/InstCombine/select-sum.ll
    @@ -0,0 +1,25 @@
    +; RUN: opt < %s -passes=instcombine -S | FileCheck %s
    +
    +target datalayout = "e-p:64:64-p1:16:16-p2:32:32:32-p3:64:64:64"
    +
    +; Test transform of:
    +;   ((P == A ? X : Def) + Base) + (P == B ? Y : 0)
    +; into:
    +;   Base + (P == A ? X : (Def + (P == B ? Y : 0))
    +define i32 @test_sum_selects(i32 %p, i32 %x, i32 %y, i32 %default, i32 %base) {
    +; CHECK-LABEL: @test_sum_selects
    +; CHECK-DAG: [[C0:%.*]] = icmp eq i32 %p, 288
    +; CHECK-DAG: [[C1:%.*]] = icmp eq i32 %p, 128
    +; CHECK-DAG: [[SELY:%.*]] = select i1 [[C1]], i32 %y, i32 0
    +; CHECK-DAG: [[SELY_DEF:%.*]] = add i32 %default, [[SELY]]
    +; CHECK-DAG: [[SELX:%.*]] = select i1 [[C0]], i32 %x, i32 [[SELY_DEF]]
    +; CHECK-DAG: [[SUM:%.*]] = add i32 %base, [[SELX]]
    +; CHECK-DAG: ret i32 [[SUM]]
    +  %c0 = icmp eq i32 %p, 288
    +  %sel0 = select i1 %c0, i32 %x, i32 %default
    +  %c1 = icmp eq i32 %p, 128
    +  %sel1 = select i1 %c1, i32 %y, i32 0
    +  %sum1 = add i32 %sel0, %base
    +  %sum2 = add i32 %sum1, %sel1
    +  ret i32 %sum2
    +}
    
    
    ``````

    </details>

    Joshi-Tejas Joshi-Tejas commented on Sep 17, 2026 23:56 UTC
    Author

    @nikic @dtcxzyw @antoniofrighetto please review!

    dtcxzyw dtcxzyw commented on code on Sep 19, 2026 03:19 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp:1
    @@ -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)) {

    It seems incorrect when C0 = <i32 1, i32 2> and C1 = <i32 1, i32 3>.

    dtcxzyw dtcxzyw commented on Sep 19, 2026 03:21 UTC
    Reviewer

    Do we have a more generalized heuristic to reorder the operands in an addition tree?

    Joshi-Tejas Joshi-Tejas commented on code on Sep 20, 2026 18:21 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp:1
    @@ -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)) {

    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

    boomanaiden154 boomanaiden154 commented on code on Sep 22, 2026 06:31 UTC
    Code Review
    llvm/test/Transforms/InstCombine/select-sum.ll:1
    @@ -0,0 +1,25 @@
    +; RUN: opt < %s -passes=instcombine -S | FileCheck %s
    +
    +target datalayout = "e-p:64:64-p1:16:16-p2:32:32:32-p3:64:64:64"
    +
    +; Test transform of:
    +;   ((P == A ? X : Def) + Base) + (P == B ? Y : 0)
    +; into:
    +;   Base + (P == A ? X : (Def + (P == B ? Y : 0))
    +define i32 @test_sum_selects(i32 %p, i32 %x, i32 %y, i32 %default, i32 %base) {
    +; CHECK-LABEL: @test_sum_selects
    +; CHECK-DAG: [[C0:%.*]] = icmp eq i32 %p, 288
    +; CHECK-DAG: [[C1:%.*]] = icmp eq i32 %p, 128

    Can we get a test case with profile information to ensure we directly preserve/drop branch weights on the selects.

    Joshi-Tejas Joshi-Tejas commented on code on Sep 22, 2026 21:35 UTC
    Code Review
    llvm/test/Transforms/InstCombine/select-sum.ll:1
    @@ -0,0 +1,25 @@
    +; RUN: opt < %s -passes=instcombine -S | FileCheck %s
    +
    +target datalayout = "e-p:64:64-p1:16:16-p2:32:32:32-p3:64:64:64"
    +
    +; Test transform of:
    +;   ((P == A ? X : Def) + Base) + (P == B ? Y : 0)
    +; into:
    +;   Base + (P == A ? X : (Def + (P == B ? Y : 0))
    +define i32 @test_sum_selects(i32 %p, i32 %x, i32 %y, i32 %default, i32 %base) {
    +; CHECK-LABEL: @test_sum_selects
    +; CHECK-DAG: [[C0:%.*]] = icmp eq i32 %p, 288
    +; CHECK-DAG: [[C1:%.*]] = icmp eq i32 %p, 128

    Updated the testcase that checks for preserved branch weights, since the new select uses the same condition. Please check!

    github-actions[bot] github-actions[bot] commented on Sep 22, 2026 21:38 UTC
    Bot

    <!--LLVM CODE FORMAT COMMENT: {clang-format}-->

    :white_check_mark: With the latest revision this PR passed the C/C++ code formatter.

    Joshi-Tejas Joshi-Tejas commented on code on Sep 26, 2026 23:21 UTC
    Code Review
    llvm/test/Transforms/InstCombine/select-sum.ll:1
    @@ -0,0 +1,25 @@
    +; RUN: opt < %s -passes=instcombine -S | FileCheck %s
    +
    +target datalayout = "e-p:64:64-p1:16:16-p2:32:32:32-p3:64:64:64"
    +
    +; Test transform of:
    +;   ((P == A ? X : Def) + Base) + (P == B ? Y : 0)
    +; into:
    +;   Base + (P == A ? X : (Def + (P == B ? Y : 0))
    +define i32 @test_sum_selects(i32 %p, i32 %x, i32 %y, i32 %default, i32 %base) {
    +; CHECK-LABEL: @test_sum_selects
    +; CHECK-DAG: [[C0:%.*]] = icmp eq i32 %p, 288
    +; CHECK-DAG: [[C1:%.*]] = icmp eq i32 %p, 128

    Ping @boomanaiden154 @dtcxzyw

    dtcxzyw dtcxzyw commented on Sep 27, 2026 16:30 UTC
    Contributor

    Do we have a more generalized heuristic to reorder the operands in an addition tree?

    I still expect a general way to reuse the logic in https://github.com/llvm/llvm-project/pull/224478. Can we reassociate the expr to put two selects in the same binop in SimplifyAssociativeOrCommutative, if one of the conditions can be implied by another?

    Joshi-Tejas Joshi-Tejas commented on code on Sep 28, 2026 22:41 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:1
    @@ -1442,8 +1487,54 @@ Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
           return NewSel;
       }
     
    -  if (!True || !False)
    +  if (!True || !False) {
    +    // When the conditions differ, one arm of a select may determine the other
    +    // select's value and simplify the binop. Keep the other arm as a binop.
    +    if (LHSIsSelect && RHSIsSelect && A != D && LHS->hasOneUse() &&
    +        RHS->hasOneUse()) {
    +      auto foldImpliedSelectArm = [&](SelectInst *Outer, Value *Other,
    +                                      bool OuterIsLHS) -> Value * {
    +        Value *OuterCond = Outer->getCondition();
    +        auto simplifyArm = [&](Value *Arm, bool CondIsTrue) -> Value * {
    +          Value *OtherArm =
    +              simplifySelectWithImpliedCond(Other, OuterCond, CondIsTrue);
    +          if (OtherArm == Other)
    +            return nullptr;
    +          return OuterIsLHS ? simplifyBinOp(Opcode, Arm, OtherArm, FMF, Q)
    +                            : simplifyBinOp(Opcode, OtherArm, Arm, FMF, Q);
    +        };
    +
    +        Value *NewTrue = simplifyArm(Outer->getTrueValue(), true);
    +        Value *NewFalse = simplifyArm(Outer->getFalseValue(), false);
    +        if (!NewTrue && !NewFalse)
    +          return nullptr;
    +
    +        auto createArm = [&](Value *Arm) {
    +          return (OuterIsLHS || I.isCommutative())
    +                     ? Builder.CreateBinOp(Opcode, Arm, Other)
    +                     : Builder.CreateBinOp(Opcode, Other, Arm);
    +        };
    +        if (!NewTrue)
    +          NewTrue = createArm(Outer->getTrueValue());
    +        if (!NewFalse)
    +          NewFalse = createArm(Outer->getFalseValue());
    +
    +        Value *NewV =
    +            Builder.CreateSelect(OuterCond, NewTrue, NewFalse, I.getName());
    +        if (auto *NewSI = dyn_cast<SelectInst>(NewV))
    +          NewSI->copyMetadata(*Outer, {LLVMContext::MD_prof,
    +                                       LLVMContext::MD_unpredictable,
    +                                       LLVMContext::MD_dbg});
    +        return NewV;
    +      };
    +
    +      if (Value *V = foldImpliedSelectArm(cast<SelectInst>(RHS), LHS, false))
    +        return V;
    +      if (Value *V = foldImpliedSelectArm(cast<SelectInst>(LHS), RHS, true))
    +        return V;
    +    }

    Handled the reassociation in SimplifyAssociativeOrCommutative but unfortunately, couldn't find a cleaner solution here to be able to handle the transform in the test select-sum.ll.

    antoniofrighetto antoniofrighetto commented on Oct 05, 2026 15:18 UTC
    Reviewer

    The results from llvm-opt-benchmark look overall promising, though I think the shape of the code could be ameliorated. To move this forward, I'd suggest extending the existing LHSIsSelect / RHSIsSelect branches to create the missing arm, generalizing #224478 as already suggested (which only folds when both arms simplify), possibly similarly to what the A == D case already does (i.e., when both selects are one-use, the other select is resolved on both arms, and at least one arm simplifies), and leaving the regrouping of operands for a separate patch.

    While at it, I'd also suggest simplifying the simplifySelectWithImpliedCond() lambda by employing simplifyNestedSelectsUsingImpliedCond() from InstCombineSelect instead (after turning it into an InstCombinerImpl member), though could be done separately too.

    Joshi-Tejas Joshi-Tejas commented on Oct 09, 2026 21:28 UTC
    Author

    @antoniofrighetto @dtcxzyw
    I had tried handling the the select arms separately like suggested but it sent InstCombine into an infinite loop, reverting two simplifications by each other. But my simplification check was not restrictive enough and now I think I have handled it properly and the code is cleaner.

    Joshi-Tejas Joshi-Tejas commented on Oct 16, 2026 23:13 UTC
    Author

    ping @dtcxzyw

    antoniofrighetto antoniofrighetto commented on Nov 03, 2026 18:35 UTC
    Contributor

    After rebasing over 3e4965d6e9fc6e187c463c3235bc003517582939, I tried the generalization I had in mind, and, keeping the ops reassociation (and select-sum.ll test) for a follow-up, I think this way would compose and read a bit simpler:

    diff --git a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
    index 97cafe14a619..8f7e3ac0ff4f 100644
    --- a/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
    +++ b/llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
    @@ -1379,6 +1379,46 @@ bool InstCombinerImpl::tryReassociateAndFoldSymmetricPair(
       return true;
     }
     
    +static void distributeBinOpOverSelect(InstCombinerImpl &IC,
    +                                      Instruction::BinaryOps Opcode,
    +                                      SelectInst *Sel, Value *Other,
    +                                      bool SelIsLHS, FastMathFlags FMF,
    +                                      const SimplifyQuery &SQ, Value *&True,
    +                                      Value *&False) {
    +  // If V is a select whose condition is implied by Cond, try to resolve it to
    +  // the appropriate arm for this value of Cond.
    +  auto SimplifySelectWithImpliedCond = [&](Value *V, Value *Cond,
    +                                           bool CondIsTrue) -> Value * {
    +    auto *InnerSI = dyn_cast<SelectInst>(V);
    +    if (!InnerSI || Cond->getType() != InnerSI->getCondition()->getType())
    +      return V;
    +
    +    if (Value *Arm = IC.simplifyNestedSelectsUsingImpliedCond(*InnerSI, Cond,
    +                                                              CondIsTrue))
    +      return Arm;
    +    return V;
    +  };
    +
    +  Value *Cond = Sel->getCondition();
    +  Value *TVal = Sel->getTrueValue(), *FVal = Sel->getFalseValue();
    +  Value *OtherT = SimplifySelectWithImpliedCond(Other, Cond, true);
    +  Value *OtherF = SimplifySelectWithImpliedCond(Other, Cond, false);
    +  auto [LHSTrueArm, RHSTrueArm] =
    +      SelIsLHS ? std::pair(TVal, OtherT) : std::pair(OtherT, TVal);
    +  auto [LHSFalseArm, RHSFalseArm] =
    +      SelIsLHS ? std::pair(FVal, OtherF) : std::pair(OtherF, FVal);
    +  True = simplifyBinOp(Opcode, LHSTrueArm, RHSTrueArm, FMF, SQ);
    +  False = simplifyBinOp(Opcode, LHSFalseArm, RHSFalseArm, FMF, SQ);
    +
    +  if (!Other->hasOneUse())
    +    return;
    +
    +  if (True && !False && OtherT != Other)
    +    False = IC.Builder.CreateBinOp(Opcode, LHSFalseArm, RHSFalseArm);
    +  else if (False && !True && OtherF != Other)
    +    True = IC.Builder.CreateBinOp(Opcode, LHSTrueArm, RHSTrueArm);
    +}
    +
     Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
                                                             Value *LHS,
                                                             Value *RHS) {
    @@ -1402,20 +1442,6 @@ Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
     
       Value *Cond, *True = nullptr, *False = nullptr;
     
    -  // If V is a select whose condition is implied by Cond, try to resolve it to
    -  // the appropriate arm for this value of Cond.
    -  auto SimplifySelectWithImpliedCond = [&](Value *V, Value *Cond,
    -                                           bool CondIsTrue) -> Value * {
    -    auto *InnerSI = dyn_cast<SelectInst>(V);
    -    if (!InnerSI || Cond->getType() != InnerSI->getCondition()->getType())
    -      return V;
    -
    -    if (Value *Arm =
    -            simplifyNestedSelectsUsingImpliedCond(*InnerSI, Cond, CondIsTrue))
    -      return Arm;
    -    return V;
    -  };
    -
       // Special-case for add/negate combination. Replace the zero in the negation
       // with the trailing add operand:
       // (Cond ? TVal : -N) + Z --> Cond ? True : (Z - N)
    @@ -1448,24 +1474,25 @@ Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
           else if (True && !False)
             False = Builder.CreateBinOp(Opcode, C, F);
         }
    -  } else if (LHSIsSelect && LHS->hasOneUse()) {
    +  } else {
         // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
    -    Cond = A;
    -    Value *TrueRHS = SimplifySelectWithImpliedCond(RHS, Cond, true);
    -    Value *FalseRHS = SimplifySelectWithImpliedCond(RHS, Cond, false);
    -    True = simplifyBinOp(Opcode, B, TrueRHS, FMF, Q);
    -    False = simplifyBinOp(Opcode, C, FalseRHS, FMF, Q);
    -    if (Value *NewSel = foldAddNegate(B, C, RHS))
    -      return NewSel;
    -  } else if (RHSIsSelect && RHS->hasOneUse()) {
         // X op (D ? E : F) -> D ? (X op E) : (X op F)
    -    Cond = D;
    -    Value *TrueLHS = SimplifySelectWithImpliedCond(LHS, Cond, true);
    -    Value *FalseLHS = SimplifySelectWithImpliedCond(LHS, Cond, false);
    -    True = simplifyBinOp(Opcode, TrueLHS, E, FMF, Q);
    -    False = simplifyBinOp(Opcode, FalseLHS, F, FMF, Q);
    -    if (Value *NewSel = foldAddNegate(E, F, LHS))
    -      return NewSel;
    +    // Prefer distributing over the LHS select.
    +    if (LHSIsSelect && LHS->hasOneUse()) {
    +      Cond = A;
    +      distributeBinOpOverSelect(*this, Opcode, SI, RHS, /*SelIsLHS=*/true, FMF,
    +                                Q, True, False);
    +      if (Value *NewSel = foldAddNegate(B, C, RHS))
    +        return NewSel;
    +    }
    +    if ((!True || !False) && RHSIsSelect && RHS->hasOneUse()) {
    +      SI = cast<SelectInst>(RHS);
    +      Cond = D;
    +      distributeBinOpOverSelect(*this, Opcode, SI, LHS, /*SelIsLHS=*/false, FMF,
    +                                Q, True, False);
    +      if (Value *NewSel = foldAddNegate(E, F, LHS))
    +        return NewSel;
    +    }
       }
     
       if (!True || !False)
    

    Not sure how the infinite loop arose, but I couldn't trigger it myself. The only thing is that, as the lambda SimplifySelectWithImpliedCond is now wrapped within the static method distributeBinOpOverSelect, the helper simplifyNestedSelectsUsingImpliedCond() needs to be moved as a public method of InstCombinerImpl class (not in the diff).

    Joshi-Tejas Joshi-Tejas commented on Nov 03, 2026 21:15 UTC
    Author

    @antoniofrighetto updated according to the suggestion. Please check. Do you mean the reassociation follow-up should be a separate PR or just another commit here?

    antoniofrighetto antoniofrighetto commented on Nov 04, 2026 14:10 UTC
    Reviewer

    Yes, I'd prefer to keep the reassociation of the operands as a separate change.

    Could you please update the proof by generalizing it for the current change? You can use llvm.assume(i1) to assume that the two select conditions cannot both be true. We also need to a few tests more, where we test a multi-use select, splat/non-splat vectors, one with !prof on both selects, etc.

    Joshi-Tejas Joshi-Tejas commented on Nov 05, 2026 18:12 UTC
    Author

    Added more tests and updated the proof. @antoniofrighetto can you please commit on my behalf if everything looks good?

    antoniofrighetto antoniofrighetto commented on code on Nov 09, 2026 11:18 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:1
    @@ -1379,6 +1379,46 @@ bool InstCombinerImpl::tryReassociateAndFoldSymmetricPair(
       return true;
     }
     
    +static void distributeBinOpOverSelect(InstCombinerImpl &IC,
    +                                      Instruction::BinaryOps Opcode,
    +                                      SelectInst *Sel, Value *Other,
    +                                      bool SelIsLHS, FastMathFlags FMF,
    +                                      const SimplifyQuery &SQ, Value *&True,
    +                                      Value *&False) {
    +  // If V is a select whose condition is implied by Cond, try to resolve it to
    +  // the appropriate arm for this value of Cond.
    +  auto SimplifySelectWithImpliedCond = [&](Value *V, Value *Cond,
    +                                           bool CondIsTrue) -> Value * {
    +    auto *InnerSI = dyn_cast<SelectInst>(V);
    +    if (!InnerSI || Cond->getType() != InnerSI->getCondition()->getType())
    +      return V;
    +
    +    if (Value *Arm = IC.simplifyNestedSelectsUsingImpliedCond(*InnerSI, Cond,
    +                                                              CondIsTrue))
    +      return Arm;
    +    return V;
    +  };
    +
    +  Value *Cond = Sel->getCondition();
    +  Value *TVal = Sel->getTrueValue(), *FVal = Sel->getFalseValue();
    +  Value *OtherT = SimplifySelectWithImpliedCond(Other, Cond, true);
    +  Value *OtherF = SimplifySelectWithImpliedCond(Other, Cond, false);
    +  auto [LHSTrueArm, RHSTrueArm] =
    +      SelIsLHS ? std::pair(TVal, OtherT) : std::pair(OtherT, TVal);
    +  auto [LHSFalseArm, RHSFalseArm] =
    +      SelIsLHS ? std::pair(FVal, OtherF) : std::pair(OtherF, FVal);

    Sorry, nit on readability (w/ a newline too):

      Value *LHSTrueArm = TVal, *RHSTrueArm = OtherT;
      Value *LHSFalseArm = FVal, *RHSFalseArm = OtherF;
      if (!SelIsLHS) {
        std::swap(LHSTrueArm,  RHSTrueArm);
        std::swap(LHSFalseArm, RHSFalseArm);
      }
      
    

    antoniofrighetto antoniofrighetto commented on code on Nov 09, 2026 11:19 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:1
    @@ -1448,24 +1474,23 @@ Value *InstCombinerImpl::SimplifySelectsFeedingBinaryOp(BinaryOperator &I,
           else if (True && !False)
             False = Builder.CreateBinOp(Opcode, C, F);
         }
    -  } else if (LHSIsSelect && LHS->hasOneUse()) {
    -    // (A ? B : C) op Y -> A ? (B op Y) : (C op Y)
    -    Cond = A;
    -    Value *TrueRHS = SimplifySelectWithImpliedCond(RHS, Cond, true);
    -    Value *FalseRHS = SimplifySelectWithImpliedCond(RHS, Cond, false);
    -    True = simplifyBinOp(Opcode, B, TrueRHS, FMF, Q);
    -    False = simplifyBinOp(Opcode, C, FalseRHS, FMF, Q);
    -    if (Value *NewSel = foldAddNegate(B, C, RHS))
    -      return NewSel;
    -  } else if (RHSIsSelect && RHS->hasOneUse()) {
    -    // X op (D ? E : F) -> D ? (X op E) : (X op F)
    -    Cond = D;
    -    Value *TrueLHS = SimplifySelectWithImpliedCond(LHS, Cond, true);
    -    Value *FalseLHS = SimplifySelectWithImpliedCond(LHS, Cond, false);
    -    True = simplifyBinOp(Opcode, TrueLHS, E, FMF, Q);
    -    False = simplifyBinOp(Opcode, FalseLHS, F, FMF, Q);
    -    if (Value *NewSel = foldAddNegate(E, F, LHS))
    -      return NewSel;
    +  } else {
    +    // Prefer distributing over the LHS select.
    +    if (LHSIsSelect && LHS->hasOneUse()) {
    +      Cond = A;
    +      distributeBinOpOverSelect(*this, Opcode, SI, RHS, /*SelIsLHS=*/true, FMF,
    +                                Q, True, False);
    +      if (Value *NewSel = foldAddNegate(B, C, RHS))
    +        return NewSel;
    +    }
    +    if ((!True || !False) && RHSIsSelect && RHS->hasOneUse()) {

        // If distributing over the LHS select was not possible, or did not fold,
        // try the RHS select.
        if ((!True || !False) && RHSIsSelect && RHS->hasOneUse()) {
    

    antoniofrighetto antoniofrighetto commented on code on Nov 09, 2026 11:20 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstructionCombining.cpp:1
    @@ -1379,6 +1379,46 @@ bool InstCombinerImpl::tryReassociateAndFoldSymmetricPair(
       return true;
     }
     
    +static void distributeBinOpOverSelect(InstCombinerImpl &IC,

    Could you please add a comment that briefly describes this helper?

    antoniofrighetto antoniofrighetto approved these changes on Nov 09, 2026 11:22 UTC
    Approved Reviewer

    LGTM

    Joshi-Tejas Joshi-Tejas commented on Nov 10, 2026 17:32 UTC
    Author

    @antoniofrighetto can you please commit on my behalf? Thanks!

    Assignees
    Joshi-Tejas Joshi-Tejas
    Labels
    risk: low confidence: 89.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 44.6% (MEDIUM) · Higher = larger blast radius
    44.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.8% · Lower = rushed or shallow review
    89.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.6% · Safe to merge
    4.6%