← Back to Pull requests

[InstCombine] Fold zero-test of "(X + Y) | Y" to "X | Y" #230431

Open
Misasasa opened this pull request with 36 lines diff across 2 files
View on GitHub
Misasasa Misasasa commented on Oct 09, 2026 09:53 UTC
Author

Summary

Fixes: #230424

Fold zero-test of X | (X + Y) into X | Y:

  • X | (X + Y) == 0 into X | Y == 0 (Proof: https://alive2.llvm.org/ce/z/Cty8_F)

  • X | (X + Y) != 0 into X | Y != 0 (Proof: https://alive2.llvm.org/ce/z/RzM9rG)
  • Motivation

    In standard library functions like std::vector<short>::_M_fill_insert or
    std::vector<char>::_M_range_insert<...>, I find patterns like

    define i1 @src(i64 %x, i64 %y) {
      %1 = tail call i64 @llvm.umax.i64(i64 %x, i64 %y)
      %2 = add nsw i64 %1, %x
      %3 = icmp ult i64 %2, %x
      %4 = tail call i64 @llvm.umin.i64(i64 %2, i64 2305843009213693951)
      %5 = select i1 %3, i64 2305843009213693951, i64 %4
      %6 = icmp eq i64 %5, 0
      ret i1 %6
    }
    

    which can be optimized into (discovered via super-optimizer)
    define i1 @tgt(i64 %x, i64 %y) {
      %1 = or i64 %x, %y
      %ieq = icmp eq i64 %1, 0
      ret i1 %ieq
    }
    

    (https://alive2.llvm.org/ce/z/bQqGyS)

    This optimization becomes available under this patch.

    Assisted-by

    Qwen-3.7-Plus, which helps me locate/sketch the patch and write tests.

    Diff: 36 lines (+36 / -0) across 2 files Reviewer: dtcxzyw Review duration: 76189m
    All Vouch review confidence checks passed
    Residual risk 0.04 = Change Risk (0.33) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.33 · 36 lines diff across 2 files
    0.33
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    88%
    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.216
    Real PR Conversation Timeline
    12 items
    github-actions[bot] github-actions[bot] commented on Oct 09, 2026 09:53 UTC
    Bot

    <!--LLVM NEW CONTRIBUTOR COMMENT-->

    Hello @Misasasa :wave:

    Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.

    All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
    The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
    Our LLVM Developer Policy describes our expectations for code quality, commit summaries and contains notes on our CI system.
    The InstCombine Contributor Guide lays out a series of rules that contributions to InstCombine (and other middle-end components) should follow.

    Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.

    ---

    Frequently asked questions

    How do I add reviewers?

    This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.

    You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.

    What if there are no comments?

    If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.

    Are any special GitHub settings required to contribute to LLVM?

    We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.

    ---

    If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.

    Thank you,
    The LLVM Community

    llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Oct 09, 2026 09:54 UTC
    Bot

    <!--LLVM PR SUMMARY COMMENT-->

    @llvm/pr-subscribers-llvm-transforms

    Author: Archmushroom (Misasasa)

    <details>
    <summary>Changes</summary>

    Fixes #<!-- -->230424

    Fold icmp eq/ne (or (add X, Y), Y), 0 into icmp eq/ne (or X, Y), 0
    because or(A, B) == 0 iff A == 0 &amp;&amp; B == 0, and
    (X + Y) == 0 &amp;&amp; Y == 0 iff X == 0 &amp;&amp; Y == 0.

    Added regression test in
    llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll,
    and all InstCombine lit tests pass.

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

    2 Files Affected:

  • (modified) llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp (+19)

  • (modified) llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll (+39)
  • ``````

    diff --git a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
    index 8893744821f7e6..7a878cbb09ba52 100644
    --- a/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
    +++ b/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
    @@ -1296,6 +1296,25 @@ Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
         // will fold to a constant elsewhere.
       }
     
    +  // (icmp eq/ne (or (add X, Y), Y), 0) -> (icmp eq/ne (or X, Y), 0)
    +  // Because or(A, B) == 0 iff A == 0 and B == 0, and (X + Y) == 0 and Y == 0
    +  // iff X == 0 and Y == 0, the zero-test is preserved.
    +  if (ICmpInst::isEquality(Pred)) {
    +    Value *OrOp0, *OrOp1;
    +    if (match(Cmp.getOperand(0), m_c_Or(m_Value(OrOp0), m_Value(OrOp1)))) {
    +      Value *X, *Y;
    +      // Check if one operand is add(X, Y) and the other is Y
    +      if (match(OrOp0, m_Add(m_Value(X), m_Value(Y))) && Y == OrOp1) {
    +        Value *NewOr = Builder.CreateOr(X, Y);
    +        return new ICmpInst(Pred, NewOr, Cmp.getOperand(1));
    +      }
    +      if (match(OrOp1, m_Add(m_Value(X), m_Value(Y))) && Y == OrOp0) {
    +        Value *NewOr = Builder.CreateOr(X, Y);
    +        return new ICmpInst(Pred, NewOr, Cmp.getOperand(1));
    +      }
    +    }
    +  }
    +
       // (icmp eq/ne f(X), 0) -> (icmp eq/ne X, 0)
       // where f(X) == 0 if and only if X == 0
       if (ICmpInst::isEquality(Pred))
    diff --git a/llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll b/llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll
    index 43afd3c69f7c30..81392fbb995232 100644
    --- a/llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll
    +++ b/llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll
    @@ -310,3 +310,42 @@ entry:
       %cmp = icmp ne <4 x i32> %or, zeroinitializer
       ret <4 x i1> %cmp
     }
    +
    +; ==============================================================================
    +; Zero-test on or(add(X, Y), Y): the "or(add(X,Y),Y) == 0" sub-expression is
    +; folded to "or(X, Y)".  The add is redundant because it does not contribute
    +; bits that are not already present in Y (adding X to Y keeps all bits of Y
    +; that are tested by the zero-check; the fold relies on the later zero-icmp).
    +; (Generated from real missed-optimization candidates.)
    +; ==============================================================================
    +define i1 @zero_or_add_eq(i64 %x, i64 %y) {
    +; CHECK-LABEL: @zero_or_add_eq(
    +; CHECK-NEXT:    [[N0:%.*]] = tail call i64 @llvm.umax.i64(i64 [[X:%.*]], i64 [[Y:%.*]])
    +; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[N0]], [[X]]
    +; CHECK-NEXT:    [[RET:%.*]] = icmp eq i64 [[TMP1]], 0
    +; CHECK-NEXT:    ret i1 [[RET]]
    +;
    +  %n0 = tail call i64 @llvm.umax.i64(i64 %x, i64 %y)
    +  %n1 = add nsw i64 %n0, %x
    +  %n2 = icmp ult i64 %n1, %x
    +  %n3 = tail call i64 @llvm.umin.i64(i64 %n1, i64 576460752303423487)
    +  %n4 = select i1 %n2, i64 576460752303423487, i64 %n3
    +  %n5 = icmp eq i64 %n4, 0
    +  ret i1 %n5
    +}
    +
    +define i1 @zero_or_add_ne(i1 %c, i64 %y) {
    +; CHECK-LABEL: @zero_or_add_ne(
    +; CHECK-NEXT:    [[N0:%.*]] = select i1 [[C:%.*]], i64 1, i64 [[Y:%.*]]
    +; CHECK-NEXT:    [[TMP1:%.*]] = or i64 [[N0]], [[Y]]
    +; CHECK-NEXT:    [[RET:%.*]] = icmp ne i64 [[TMP1]], 0
    +; CHECK-NEXT:    ret i1 [[RET]]
    +;
    +  %n0 = select i1 %c, i64 1, i64 %y
    +  %n1 = add nsw i64 %n0, %y
    +  %n2 = icmp ult i64 %n1, %y
    +  %n3 = tail call i64 @llvm.umin.i64(i64 %n1, i64 288230376151711743)
    +  %n4 = select i1 %n2, i64 288230376151711743, i64 %n3
    +  %n5 = icmp ne i64 %n4, 0
    +  ret i1 %n5
    +}
    
    
    ``````

    </details>

    dtcxzyw dtcxzyw commented on code on Oct 16, 2026 17:12 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp:1
    @@ -1296,6 +1296,25 @@ Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
         // will fold to a constant elsewhere.
       }
     
    +  // (icmp eq/ne (or (add X, Y), Y), 0) -> (icmp eq/ne (or X, Y), 0)
    +  // Because or(A, B) == 0 iff A == 0 and B == 0, and (X + Y) == 0 and Y == 0
    +  // iff X == 0 and Y == 0, the zero-test is preserved.
    +  if (ICmpInst::isEquality(Pred)) {
    +    Value *OrOp0, *OrOp1;
    +    if (match(Cmp.getOperand(0), m_c_Or(m_Value(OrOp0), m_Value(OrOp1)))) {

    match(Cmp.getOperand(0), m_c_Or(m_c_Add(m_Value(X), m_Value(Y)), m_Deferred(Y)))

    dtcxzyw dtcxzyw commented on code on Oct 16, 2026 17:13 UTC
    Code Review
    llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll:1
    @@ -310,3 +310,42 @@ entry:
       %cmp = icmp ne <4 x i32> %or, zeroinitializer
       ret <4 x i1> %cmp
     }
    +
    +; ==============================================================================
    +; Zero-test on or(add(X, Y), Y): the "or(add(X,Y),Y) == 0" sub-expression is
    +; folded to "or(X, Y)".  The add is redundant because it does not contribute
    +; bits that are not already present in Y (adding X to Y keeps all bits of Y
    +; that are tested by the zero-check; the fold relies on the later zero-icmp).
    +; (Generated from real missed-optimization candidates.)

    Please make the comment concise.

    dtcxzyw dtcxzyw commented on code on Oct 16, 2026 17:16 UTC
    Code Review
    llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll:1
    @@ -310,3 +310,42 @@ entry:
       %cmp = icmp ne <4 x i32> %or, zeroinitializer
       ret <4 x i1> %cmp
     }
    +
    +; ==============================================================================
    +; Zero-test on or(add(X, Y), Y): the "or(add(X,Y),Y) == 0" sub-expression is
    +; folded to "or(X, Y)".  The add is redundant because it does not contribute
    +; bits that are not already present in Y (adding X to Y keeps all bits of Y
    +; that are tested by the zero-check; the fold relies on the later zero-icmp).
    +; (Generated from real missed-optimization candidates.)
    +; ==============================================================================

    Only add tests with the pattern handled by this patch. See https://llvm.org/docs/InstCombineContributorGuide.html#tests.

    dtcxzyw dtcxzyw requested changes on Oct 16, 2026 17:16 UTC
    Changes Requested Reviewer

    Please write the PR description yourself and follow the instructions in https://llvm.org/docs/AIToolPolicy.html and https://llvm.org/docs/InstCombineContributorGuide.html.

    Misasasa Misasasa commented on code on Oct 19, 2026 08:25 UTC
    Code Review
    llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp:1
    @@ -1296,6 +1296,25 @@ Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
         // will fold to a constant elsewhere.
       }
     
    +  // (icmp eq/ne (or (add X, Y), Y), 0) -> (icmp eq/ne (or X, Y), 0)
    +  // Because or(A, B) == 0 iff A == 0 and B == 0, and (X + Y) == 0 and Y == 0
    +  // iff X == 0 and Y == 0, the zero-test is preserved.
    +  if (ICmpInst::isEquality(Pred)) {
    +    Value *OrOp0, *OrOp1;
    +    if (match(Cmp.getOperand(0), m_c_Or(m_Value(OrOp0), m_Value(OrOp1)))) {

    Done.

    Misasasa Misasasa commented on code on Oct 19, 2026 08:25 UTC
    Code Review
    llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll:1
    @@ -310,3 +310,42 @@ entry:
       %cmp = icmp ne <4 x i32> %or, zeroinitializer
       ret <4 x i1> %cmp
     }
    +
    +; ==============================================================================
    +; Zero-test on or(add(X, Y), Y): the "or(add(X,Y),Y) == 0" sub-expression is
    +; folded to "or(X, Y)".  The add is redundant because it does not contribute
    +; bits that are not already present in Y (adding X to Y keeps all bits of Y
    +; that are tested by the zero-check; the fold relies on the later zero-icmp).
    +; (Generated from real missed-optimization candidates.)

    Done.

    Misasasa Misasasa commented on code on Oct 19, 2026 08:25 UTC
    Code Review
    llvm/test/Transforms/InstCombine/icmp-or-of-select-with-zero.ll:1
    @@ -310,3 +310,42 @@ entry:
       %cmp = icmp ne <4 x i32> %or, zeroinitializer
       ret <4 x i1> %cmp
     }
    +
    +; ==============================================================================
    +; Zero-test on or(add(X, Y), Y): the "or(add(X,Y),Y) == 0" sub-expression is
    +; folded to "or(X, Y)".  The add is redundant because it does not contribute
    +; bits that are not already present in Y (adding X to Y keeps all bits of Y
    +; that are tested by the zero-check; the fold relies on the later zero-icmp).
    +; (Generated from real missed-optimization candidates.)
    +; ==============================================================================

    Done.

    Misasasa Misasasa commented on Oct 19, 2026 08:28 UTC
    Author

    Thanks for your review! I have rewritten my PR description and revised my changes as suggested.

    Misasasa Misasasa commented on Nov 02, 2026 09:45 UTC
    Author

    @dtcxzyw Thanks for your review! I have reworked my PR as suggested, including codes, tests, and the PR description itself. Would you mind taking another look?

    Reviewers
    Assignees
    Misasasa Misasasa
    Labels
    risk: low confidence: 88.6% 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: 33.1% (LOW) · Higher = larger blast radius
    33.1%
    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: 88.6% · Lower = rushed or shallow review
    88.6%
    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: 3.8% · Safe to merge
    3.8%