[InstCombine] Fold binop of selects with implied conditions when only one arm simplifies #224477
<!--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:
````````````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>
@nikic @dtcxzyw @antoniofrighetto please review!
It seems incorrect when C0 = <i32 1, i32 2> and C1 = <i32 1, i32 3>.
Do we have a more generalized heuristic to reorder the operands in an addition tree?
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
Can we get a test case with profile information to ensure we directly preserve/drop branch weights on the selects.
Updated the testcase that checks for preserved branch weights, since the new select uses the same condition. Please check!
<!--LLVM CODE FORMAT COMMENT: {clang-format}-->
:white_check_mark: With the latest revision this PR passed the C/C++ code formatter.
Ping @boomanaiden154 @dtcxzyw
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?
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.
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.
@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.
ping @dtcxzyw
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).
@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?
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.
Added more tests and updated the proof. @antoniofrighetto can you please commit on my behalf if everything looks good?
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);
}
// If distributing over the LHS select was not possible, or did not fold,
// try the RHS select.
if ((!True || !False) && RHSIsSelect && RHS->hasOneUse()) {
Could you please add a comment that briefly describes this helper?
LGTM
@antoniofrighetto can you please commit on my behalf? Thanks!
antoniofrighetto
Joshi-Tejas
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>