Skip to content

[WebAssembly] Fold any/alltrue (setcc x, 0, eq/ne) to [not] any/alltrue x #144741

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 1, 2025

Conversation

badumbatish
Copy link
Contributor

@badumbatish badumbatish commented Jun 18, 2025

Fixes #50142, a miss of further vectorization, where we can only achieve zext (xor (any_true), -1).

Now in test case simd-setcc-reductions, it's converted to all_true.

Also fixes #145177, which is

all_true (setcc x, 0, eq) -> not any_true
any_true (setcc x, 0, ne) -> any_true
all_true (setcc x, 0, ne) -> all_true

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Jun 18, 2025

@llvm/pr-subscribers-backend-webassembly

Author: jjasmine (badumbatish)

Changes

Fix a miss of further vectorization introduced in #50142 , where we can only achieve zext (xor (any_true), -1).

Now in test case issue50142, it's converted to all_true.


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

2 Files Affected:

  • (modified) llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp (+31)
  • (added) llvm/test/CodeGen/WebAssembly/issue50142.ll (+20)
diff --git a/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp b/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
index 3cd923c0ba058..84a18f74867a5 100644
--- a/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
+++ b/llvm/lib/Target/WebAssembly/WebAssemblyISelLowering.cpp
@@ -19,6 +19,7 @@
 #include "WebAssemblyTargetMachine.h"
 #include "WebAssemblyUtilities.h"
 #include "llvm/CodeGen/CallingConvLower.h"
+#include "llvm/CodeGen/ISDOpcodes.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineInstrBuilder.h"
 #include "llvm/CodeGen/MachineJumpTableInfo.h"
@@ -36,6 +37,7 @@
 #include "llvm/Support/KnownBits.h"
 #include "llvm/Support/MathExtras.h"
 #include "llvm/Target/TargetOptions.h"
+#include <iostream>
 using namespace llvm;
 
 #define DEBUG_TYPE "wasm-lower"
@@ -3248,6 +3250,35 @@ static SDValue performSETCCCombine(SDNode *N,
   ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
   SDLoc DL(N);
   EVT VT = N->getValueType(0);
+  //  N           LHS     LhsL        LhsLL    LhsLR   InnerCond RHS Cond
+  // setcc (iN (bitcast (setcc vNi1 (vNiY X), <vNiY 0>, eq)),     0, eq
+  // => all_true (vNi1 X)
+  if (DCI.isBeforeLegalize() && VT.isScalarInteger() && (Cond == ISD::SETEQ) &&
+      (isNullConstant(RHS)) && LHS->getOpcode() == ISD::BITCAST) {
+    SDValue LhsL = LHS.getOperand(0);
+    EVT LhsLType = LhsL.getValueType();
+    ISD::CondCode InnerCond = cast<CondCodeSDNode>(LhsL->getOperand(2))->get();
+    if (LhsL.getOpcode() == ISD::SETCC && InnerCond == ISD::SETEQ) {
+      SDValue LhsLL = LhsL.getOperand(0); // vNi1 X
+      SDValue LhsLR = LhsL.getOperand(1); // 0
+      unsigned NumElts = LhsLType.getVectorNumElements();
+      bool Vectorizable =
+          NumElts == 2 || NumElts == 4 || NumElts == 8 || NumElts == 16;
+      EVT Width = MVT::getIntegerVT(128 / NumElts);
+      // EVT LhsLLType = LhsLL.getValueType();
+
+      if (Vectorizable && LhsLR.getOpcode() == ISD::BUILD_VECTOR &&
+          LhsLType.isFixedLengthVector()) {
+        return DAG.getZExtOrTrunc(
+            DAG.getNode(
+                ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
+                {DAG.getConstant(Intrinsic::wasm_alltrue, DL, MVT::i32),
+                 DAG.getSExtOrTrunc(LhsLL, DL,
+                                    LhsLType.changeVectorElementType(Width))}),
+            DL, MVT::i1);
+      }
+    }
+  }
 
   // setcc (iN (bitcast (vNi1 X))), 0, ne
   //   ==> any_true (vNi1 X)
diff --git a/llvm/test/CodeGen/WebAssembly/issue50142.ll b/llvm/test/CodeGen/WebAssembly/issue50142.ll
new file mode 100644
index 0000000000000..24ba941e76ee2
--- /dev/null
+++ b/llvm/test/CodeGen/WebAssembly/issue50142.ll
@@ -0,0 +1,20 @@
+; RUN: llc < %s -mtriple=wasm32-- -mattr=+simd128 | FileCheck --check-prefix=CHECK %s
+
+; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(argmem: read)
+define hidden range(i32 0, 2) i32 @all_true(ptr noundef readonly captures(none) %a) local_unnamed_addr #0 {
+; CHECK-LABEL: all_true:
+; CHECK:         .functype all_true (i32) -> (i32)
+; CHECK: local.get 0
+; CHECK-NEXT: v128.load 0:p2align=0
+; CHECK-NEXT: i8x16.all_true
+; CHECK-NEXT:    # fallthrough-return
+; CHECK-NEXT: end_function 
+entry:
+  %0 = load <16 x i8>, ptr %a, align 1
+  %.fr = freeze <16 x i8> %0
+  %1 = icmp eq <16 x i8> %.fr, zeroinitializer
+  %2 = bitcast <16 x i1> %1 to i16
+  %3 = icmp eq i16 %2, 0
+  %conv3 = zext i1 %3 to i32
+  ret i32 %conv3
+}

@badumbatish badumbatish force-pushed the issue50142 branch 2 times, most recently from 4d84fc3 to 79479c6 Compare June 18, 2025 17:04
@badumbatish badumbatish changed the title Fix 50142 [WebAssembly] Fix missed optimization in 50142 Jun 18, 2025
@badumbatish
Copy link
Contributor Author

@tlively hi, I saw you're one of the issue filers for #50142, I'm not sure who's the code reviewers for the webassembly components to review my code. Can i get some pointers on who to tag?

@dschuff
Copy link
Member

dschuff commented Jun 18, 2025

@tlively is probably good (unless he wants to delegate that off), also @sparker-arm has been working on wasm SIMD recently.

Copy link
Contributor

@lukel97 lukel97 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you precommit the test in this PR? I.e. rebase this so there's one commit adding the test without the changes, and another adding the changes to WebAssemblyISelLowering.cpp and the changes to the test case. That way you can see the diff in the PR

@badumbatish
Copy link
Contributor Author

badumbatish commented Jun 19, 2025

i updated the code, in the case of 4xi16, the fold doesn't work since i was targeting setcc

define i32 @all_true_4_i16(<4 x i16> %v) {
; CHECK-LABEL: all_true_4_i16:
; CHECK:         .functype all_true_4_i16 (v128) -> (i32)
; CHECK-NEXT:  # %bb.0:
; CHECK-NEXT:    v128.const $push0=, 0, 0, 0, 0, 0, 0, 0, 0
; CHECK-NEXT:    i16x8.eq $push1=, $0, $pop0
; CHECK-NEXT:    i32x4.extend_low_i16x8_s $push2=, $pop1
; CHECK-NEXT:    v128.any_true $push3=, $pop2
; CHECK-NEXT:    i32.const $push4=, -1
; CHECK-NEXT:    i32.xor $push5=, $pop3, $pop4
; CHECK-NEXT:    i32.const $push6=, 1
; CHECK-NEXT:    i32.and $push7=, $pop5, $pop6
; CHECK-NEXT:    return $pop7
  %1 = icmp eq <4 x i16> %v, zeroinitializer
  %2 = bitcast <4 x i1> %1 to i4
  %3 = icmp eq i4 %2, 0
  %conv3 = zext i1 %3 to i32
  ret i32 %conv3
}

ok i just check the specs, haha there isn't any 4 x i16 in web assembly, will remove

Copy link
Contributor

@lukel97 lukel97 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this new approach looks good!

Copy link
Contributor

@lukel97 lukel97 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks! Although we should also wait for a WebAssembly maintainer to approve this too (this isn't my neck of the woods in LLVM!)

Can you also update your PR title to not reference the issue, but instead something like "[WebAssembly] Combine any_true (setcc x, 0, eq) to not all_true"?

We should also follow up on this to also handle:

  • all_true (setcc x, 0, eq) -> not any_true
  • any_true (setcc x, 0, ne) -> any_true
  • all_true (setcc x, 0, ne) -> all_true

@badumbatish badumbatish changed the title [WebAssembly] Fix missed optimization in 50142 [WebAssembly] Combine any_true (setcc x, 0, eq) to not all_true Jun 21, 2025
@badumbatish
Copy link
Contributor Author

really sorry about the extra ping @tlively , can I please get the PR either approved or reviewed?

I think I can reuse some of the code for issue #145177. I just want to make sure the code structure is good before I base the new PR ontop of this PR

@badumbatish
Copy link
Contributor Author

badumbatish commented Jun 26, 2025

I've refactored, and added support and test case for three more patterns. This will fix #145177

all_true (setcc x, 0, eq) -> not any_true
any_true (setcc x, 0, ne) -> any_true
all_true (setcc x, 0, ne) -> all_true

@badumbatish badumbatish changed the title [WebAssembly] Combine any_true (setcc x, 0, eq) to not all_true [WebAssembly] Fold any/alltrue (setcc x, 0, eq/ne) Jun 27, 2025
@badumbatish badumbatish changed the title [WebAssembly] Fold any/alltrue (setcc x, 0, eq/ne) [WebAssembly] Fold any/alltrue (setcc x, 0, eq/ne) to [not] any/alltrue x Jun 27, 2025
Copy link
Contributor

@lukel97 lukel97 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for handling the new test cases! You should add "Fixes #50142, fixes #145177" to your PR description so it will automatically close those issues when this gets merged

badumbatish and others added 5 commits June 30, 2025 11:50
This introduces the fold (any_true (setcc <X> 0, eq)) to (not
(all_true)), allowing potential extra fold of (not (not ...))

Introduces test simd-setcc-reductions and readjusts simd-vecreduce-bool
Use SDPatternMatching and remove truncation. Also added 4xi64 case to
reflect that.
all_true (setcc x, 0, eq) -> not any_true
any_true (setcc x, 0, ne) -> any_true
all_true (setcc x, 0, ne) -> all_true
Copy link
Contributor

@lukel97 lukel97 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM with the new changes, thanks! Gentle ping to the other WebAssembly maintainers for another review

@lukel97 lukel97 requested a review from sparker-arm June 30, 2025 21:22
Copy link
Member

@dschuff dschuff left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Otherwise LGTM

@dschuff
Copy link
Member

dschuff commented Jul 1, 2025

It looks like this one is ready to go too. is the commit message up-to-date?

@badumbatish
Copy link
Contributor Author

Otherwise LGTM

just changed, tysm for merging

@dschuff
Copy link
Member

dschuff commented Jul 1, 2025

just changed, tysm for merging

No problem, well done!

I'm just going to wait for the CI tests to finish, then I'll merge.

@dschuff dschuff merged commit e9c9f8f into llvm:main Jul 1, 2025
7 checks passed
Copy link

github-actions bot commented Jul 1, 2025

@badumbatish Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@lukel97
Copy link
Contributor

lukel97 commented Jul 1, 2025

Thanks for the review and the commit @dschuff, it's much appreciated!

@llvm-ci
Copy link
Collaborator

llvm-ci commented Jul 2, 2025

LLVM Buildbot has detected a new failure on builder clang-arm64-windows-msvc running on linaro-armv8-windows-msvc-04 while building llvm at step 6 "test-build-unified-tree-check-all".

Full details are available at: https://lab.llvm.org/buildbot/#/builders/161/builds/6806

Here is the relevant piece of the build log for the reference
Step 6 (test-build-unified-tree-check-all) failure: 1200 seconds without output running [b'ninja', b'check-all'], attempting to kill
...
UNSUPPORTED: lld :: wasm/wrap.s (84340 of 84350)
UNSUPPORTED: mlgo-utils :: corpus/extract_ir_script.test (84341 of 84350)
UNSUPPORTED: mlgo-utils :: corpus/extract_ir_test.py (84342 of 84350)
UNSUPPORTED: mlgo-utils :: corpus/make_corpus_script.test (84343 of 84350)
UNSUPPORTED: mlgo-utils :: pytype.test (84344 of 84350)
PASS: lit :: xunit-output-report-failures-only.py (84345 of 84350)
PASS: lit :: selecting.py (84346 of 84350)
PASS: lit :: xfail-cl.py (84347 of 84350)
PASS: lit :: shtest-shell.py (84348 of 84350)
PASS: lit :: shtest-define.py (84349 of 84350)
command timed out: 1200 seconds without output running [b'ninja', b'check-all'], attempting to kill
program finished with exit code 1
elapsedTime=3858.992169

@badumbatish
Copy link
Contributor Author

badumbatish commented Jul 2, 2025

ruh roh

i digged into the build log and couldn't find any failures, just that its timing out on task 84350???

PASS: lit :: shtest-shell.py (84348 of 84350)
PASS: lit :: shtest-define.py (84349 of 84350)
....
command timed out: 1200 seconds without output running [b'ninja', b'check-all'], attempting to kill
program finished with exit code 1

how can i make sure this is not some kind of performance regression on my end?

@lukel97
Copy link
Contributor

lukel97 commented Jul 2, 2025

ruh roh

i digged into the build log and couldn't find any failures, just that its timing out on task 84350???


PASS: lit :: shtest-shell.py (84348 of 84350)

PASS: lit :: shtest-define.py (84349 of 84350)

....

command timed out: 1200 seconds without output running [b'ninja', b'check-all'], attempting to kill

program finished with exit code 1

how can i make sure this is not some kind of performance regression on my end?

I wouldn't worry about that buildbot failure, it's likely just a flakey test/bot. There's quite a lot of false alarms as you'll soon come to see :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[WebAssembly] Missed optimization in any_true/all_true [SIMD] code not recognized as all_true
6 participants