Skip to content

[wasm] Make PackedSimd.Shuffle public and use it in CoreLib - #137562

Merged
lewing merged 1 commit into
mainfrom
lewing-packedsimd-shuffle-public
Nov 17, 2026
Merged

lewing merged 1 commit into
mainfrom
lewing-packedsimd-shuffle-public

Conversation

@lewing

@lewing lewing commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

PackedSimd.Shuffle (i8x16.shuffle) was approved with the rest of the WASM SIMD surface in #53730. It stayed internal because Mono's LLVM backend crashed when the shuffle mask wasn't a constant. Mono's wasm support is going away. CoreCLR's wasm JIT already handles both cases:

  • Constant, in-range mask: contained as the immediate of a single i8x16.shuffle.
  • Non-constant mask: lowered to a bounds check plus two i8x16.swizzle and an or (LowerHWIntrinsicNativeShuffle). Indices > 31 throw ArgumentOutOfRangeException.

Changes

  • Make both PackedSimd.Shuffle overloads public, matching the approved shape (lower, upper, indices). Add them to the ref assembly and document the index range and constant-mask behavior.
  • Use a single constant-mask PackedSimd.Shuffle where CoreLib previously emulated a two-source byte permute:
    • Vector128.UnpackLow / UnpackHigh (used by HexConverter): replaces two swizzles plus or.
    • TeddyHelper.RightShift1 / RightShift2: replaces two swizzles plus or.
    • ProbabilisticMap.ContainsMask16Chars: replaces mask/shift plus two saturating narrows with even/odd byte unzips.
  • Add PackedSimdTests coverage for constant masks, non-constant masks (both overloads), and out-of-range non-constant indices (skipped on Mono, which masks indices instead of throwing).

Crossgen2 output for the touched loops (AsciiStringSearchValuesTeddyBase.IndexOfAnyN2Vector128, ProbabilisticMap.IndexOfAnyVectorized) shows each permute is now a single i8x16.shuffle with the expected immediate. No touched method failed R2R compilation.

Validation

Built with ./build.sh clr+libs+host+packs -os browser -c Release /p:AotHostArchitecture=arm64 /p:AotHostOS=osx. Tests ran with XHARNESS_COMMAND=test-browser ./dotnet.sh build /t:Test <proj> /p:TargetOS=browser /p:TargetArchitecture=wasm /p:RuntimeFlavor=CoreCLR /p:Configuration=Release /p:TestWasmReadyToRun=true /p:EnableAggressiveTrimming=true /p:EnableNgenOptimization=false /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=true (browser CoreCLR, trimmed R2R, Chrome).

EnableNgenOptimization=false matters here. By default, library-test R2R passes StandardOptimizationData.mibc with --partial, which leaves SearchValues/HexConverter uncompiled. They then run in the interpreter, where PackedSimd.IsSupported is false, so the changed paths aren't exercised. With full R2R, the composite grows from 0.8 MB to 38.6 MB.

  • System.Runtime.Intrinsics.Tests: passed, 13346 passed / 0 failed / 1 skipped. Includes the 6 new Shuffle tests.
  • System.Memory.Tests with WasmTestAppArgs=-class System.Memory.Tests.Span.StringSearchValuesTests: passed, 110 passed / 0 failed / 2 skipped (_Nls, _InvariantCulture). Covers Teddy N2/N3, including the *_RandomInputs fuzz tests.
  • System.Runtime.Extensions.Tests with WasmTestAppArgs=-class System.Tests.ConvertToHexStringTests: passed, 122/122. Covers UnpackLow/High via HexConverter.
  • ProbabilisticMap: in the stacked follow-up [wasm] Prefer the vectorized ProbabilisticMap in SearchValues.Create on PackedSimd #137575, the *_RandomInputs_Char tests plus SearchValues_Contains/SearchValues_GetValues passed 1058/1058 under full R2R on top of this branch.

Not run: the full System.Memory.Tests suite.

Mono's LLVM AOT still returns NULL for PackedSimd.Shuffle in simd-intrinsics.c, so a call there would recurse into the managed body. The Mono interpreter does implement it. This PR doesn't add Mono support.

Note

This PR description was generated with GitHub Copilot.

PackedSimd.Shuffle was approved in #53730 but kept internal because Mono's
LLVM backend required a constant mask. CoreCLR's wasm JIT emits i8x16.shuffle
for constant masks and falls back to swizzles for non-constant ones, so expose
the approved API and replace the two-swizzle-plus-or emulations in
Vector128.UnpackLow/High and TeddyHelper.RightShift1/2, and the
mask/shift/narrow unzip in ProbabilisticMap, with a single i8x16.shuffle.

Co-authored-by: Copilot App <[email protected]>
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-runtime-intrinsics
See info in area-owners.md if you want to be subscribed.

@lewing
lewing marked this pull request as ready for review November 15, 2026 00:14
@lewing lewing added the arch-wasm WebAssembly architecture label Nov 15, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to 'arch-wasm': @lewing, @pavelsavara
See info in area-owners.md if you want to be subscribed.

@lewing

lewing commented Nov 15, 2026 •

Copy link
Copy Markdown
Member Author

@adamperlin @tannergooding follow up from the shuffle discussion, ptal

@lewing
lewing requested review from tannergooding and a balanced review from Copilot November 15, 2026 21:09
@lewing
lewing added this pull request to stack #137600 November 15, 2026 21:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

On Mono wasm LLVM AOT with SIMD enabled, Shuffle is not lowered and falls back to a self-recursive managed body, breaking previously working hex conversion and affecting other SIMD paths.

1 open issue
What changed in this PR

This PR exposes the byte and signed-byte PackedSimd.Shuffle APIs and uses constant-mask shuffles to simplify WebAssembly SIMD operations in CoreLib’s hex conversion and string searching.

Changes:

  • Add public overloads, reference declarations, and documentation for shuffle indices and lowering behavior.
  • Replace swizzle compositions and narrowing sequences with constant-mask shuffles.
  • Add tests for constant, variable, and out-of-range indices.
File Description
src/​libraries/​System.Runtime.Intrinsics/​tests/​Wasm/​PackedSimdTests.cs Adds shuffle result and invalid-index tests.
src/​libraries/​System.Runtime.Intrinsics/​ref/​System.Runtime.Intrinsics.cs Exposes both shuffle overloads in the reference assembly.
src/​libraries/​System.Private.CoreLib/​src/​System/​SearchValues/​Strings/​Helpers/​TeddyHelper.cs Uses shuffles for one- and two-byte shifts.
src/​libraries/​System.Private.CoreLib/​src/​System/​SearchValues/​ProbabilisticMap.cs Uses shuffles to separate character bytes.
src/​libraries/​System.Private.CoreLib/​src/​System/​Runtime/​Intrinsics/​Wasm/​PackedSimd.PlatformNotSupported.cs Makes unsupported-platform stubs public.
src/​libraries/​System.Private.CoreLib/​src/​System/​Runtime/​Intrinsics/​Wasm/​PackedSimd.cs Publishes and documents both overloads.
src/​libraries/​System.Private.CoreLib/​src/​System/​Runtime/​Intrinsics/​Vector128.cs Uses shuffles for byte unpacking.

Review effort: Balanced

@adamperlin adamperlin left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks good to me overall

@lewing
lewing merged commit b48d9e4 into main Nov 17, 2026
113 of 115 checks passed
@lewing
lewing deleted the lewing-packedsimd-shuffle-public branch November 17, 2026 00:14
lewing added a commit that referenced this pull request Nov 17, 2026
…on PackedSimd (#137575)

Stacked on #137562.

`ProbabilisticMap.IndexOfAny`/`LastIndexOfAny` already take the
vectorized path when `PackedSimd.IsSupported` (#129838), but
`SearchValues.ShouldUseProbabilisticMap` only short-circuited for
`Sse41`/`AdvSimd.Arm64`. On wasm, non-ASCII sets (min value >= 128)
therefore fell through to the memory-footprint heuristic, which picks
the scalar `BitmapCharSearchValues` whenever `maxInclusive <= 1536 + 64
* count` (so any set in Latin Extended, Greek, Cyrillic, etc.). This PR
adds `|| PackedSimd.IsSupported` so wasm makes the same choice as x64
and arm64.

## Benchmark

Browser CoreCLR, ReadyToRun (composite, trimmed), Chromium 158 on an
osx-arm64 host. `ProbabilisticCharSearchValues` and
`BitmapCharSearchValues` are built from the same values (through
`UnsafeAccessor`) and timed in the same run. Each figure is the best of
7 samples of about 40 ms, in ns per call. "Speedup" is bitmap time
divided by probabilistic time, so values above 1 favour this change. The
*ascii* and *nonascii-nomatch* rows are full scans with no match. The
*all-in-set* rows are `IndexOfAnyExcept` over a haystack made only of
set members.

Summary at 1024 and 16384 chars:

| Value set | Before → after | IndexOfAny, ASCII haystack | IndexOfAny,
non-ASCII haystack (no match) | IndexOfAnyExcept |
|---|---|--:|--:|--:|
| 6 values, U+0100–U+017F | Bitmap → Probabilistic | 4.16x / 4.28x |
3.98x / 4.04x | 1.03x / 1.06x |
| 20 values, U+0100–U+017F | Bitmap → Probabilistic | 2.80x / 2.82x |
3.65x / 3.38x | 1.03x / 1.09x |
| 100 values, U+0370–U+04FF | Bitmap → Probabilistic | 1.89x / 2.06x |
4.23x / 3.94x | 1.17x / 1.22x |
| 204 values, U+0100–U+01FF (dense) | Bitmap → Probabilistic | **0.67x /
0.77x** | **0.67x / 0.71x** | 1.02x / 1.09x |
| 20 values, U+4E00–U+9FFF (sparse; control) | Probabilistic (no change)
| 2.85x / 2.59x | 3.99x / 3.44x | 1.01x / 1.12x |

The vectorized probabilistic map is 1.4–4.3x faster for sparse and
moderate sets, even at 16 chars. It is about 25–33% slower for very
dense sets such as 204 of the 256 values in U+0100–U+01FF. There, every
low and high byte is in the bloom filter, so most chars reach the
exact-match check. x64 and arm64 make the same trade-off because they
always prefer the vectorized map, so this PR keeps parity rather than
adding a wasm-only density check.

Correctness: the benchmark also compared every implementation, plus
whatever `SearchValues.Create` returned, against a naive reference. It
checked no-match haystacks and haystacks with a match in the last
position, at every length. There were 0 mismatches.

<details>
<summary>Full results (16/64/1024/16384 chars)</summary>

| Value set | Operation / haystack | Length | Bitmap (ns) |
Probabilistic (ns) | Speedup |
|---|---|--:|--:|--:|--:|
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/ascii | 16 | 34.1 | 24.8 | 1.38x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/nonascii-nomatch | 16 | 18.7 | 10.7 | 1.76x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAnyExcept/all-in-set | 16 | 21.3 | 20.2 | 1.05x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/ascii | 64 | 53.1 | 18.4 | 2.89x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/nonascii-nomatch | 64 | 42.5 | 13.6 | 3.12x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAnyExcept/all-in-set | 64 | 52.0 | 52.5 | 0.99x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/ascii | 1024 | 785.8 | 188.8 | 4.16x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/nonascii-nomatch | 1024 | 772.1 | 194.2 | 3.98x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAnyExcept/all-in-set | 1024 | 859.1 | 834.7 | 1.03x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/ascii | 16384 | 14697.3 | 3436.3 | 4.28x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAny/nonascii-nomatch | 16384 | 16406.2 | 4064.9 | 4.04x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 6 Latin Ext-A (U+0100-U+017F) |
IndexOfAnyExcept/all-in-set | 16384 | 17700.2 | 16723.6 | 1.06x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/ascii | 16 | 22.2 | 12.2 | 1.82x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/nonascii-nomatch | 16 | 18.5 | 10.6 | 1.75x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAnyExcept/all-in-set | 16 | 20.7 | 20.1 | 1.03x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/ascii | 64 | 61.2 | 24.9 | 2.46x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/nonascii-nomatch | 64 | 49.0 | 15.4 | 3.17x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAnyExcept/all-in-set | 64 | 63.6 | 60.7 | 1.05x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/ascii | 1024 | 941.5 | 336.5 | 2.80x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/nonascii-nomatch | 1024 | 753.8 | 206.8 | 3.65x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAnyExcept/all-in-set | 1024 | 851.4 | 828.6 | 1.03x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/ascii | 16384 | 13647.5 | 4834.0 | 2.82x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAny/nonascii-nomatch | 16384 | 12255.9 | 3625.5 | 3.38x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 Latin Ext-A (U+0100-U+017F)
| IndexOfAnyExcept/all-in-set | 16384 | 13598.6 | 12426.8 | 1.09x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/ascii | 16 | 17.3 | 12.7 | 1.36x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/nonascii-nomatch | 16 | 20.5 | 11.2 | 1.84x
|
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAnyExcept/all-in-set | 16 | 19.1 | 18.8 | 1.02x
|
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/ascii | 64 | 61.7 | 29.6 | 2.08x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/nonascii-nomatch | 64 | 65.7 | 19.6 | 3.34x
|
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAnyExcept/all-in-set | 64 | 68.3 | 59.1 | 1.15x
|
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/ascii | 1024 | 950.6 | 502.0 | 1.89x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/nonascii-nomatch | 1024 | 1115.4 | 264.0 |
4.23x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAnyExcept/all-in-set | 1024 | 959.8 | 817.9 |
1.17x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/ascii | 16384 | 14355.5 | 6982.4 | 2.06x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAny/nonascii-nomatch | 16384 | 15820.3 | 4016.1
| 3.94x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 100 Greek+Cyrillic
(U+0370-U+04FF) | IndexOfAnyExcept/all-in-set | 16384 | 14965.8 |
12280.3 | 1.22x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/ascii | 16 | 19.3 | 22.3 | 0.87x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/nonascii-nomatch | 16 | 15.8 | 19.3 | 0.82x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAnyExcept/all-in-set | 16 | 18.7 | 20.1 | 0.93x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/ascii | 64 | 54.7 | 72.1 | 0.76x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/nonascii-nomatch | 64 | 48.9 | 69.1 | 0.71x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAnyExcept/all-in-set | 64 | 56.6 | 53.6 | 1.06x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/ascii | 1024 | 845.3 | 1269.5 | 0.67x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/nonascii-nomatch | 1024 | 683.6 | 1025.4 | 0.67x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAnyExcept/all-in-set | 1024 | 856.0 | 837.7 | 1.02x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/ascii | 16384 | 13964.8 | 18212.9 | 0.77x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAny/nonascii-nomatch | 16384 | 11157.2 | 15722.7 | 0.71x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 204 dense (U+0100-U+01FF) |
IndexOfAnyExcept/all-in-set | 16384 | 13476.6 | 12402.3 | 1.09x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/ascii | 16 | 17.1 | 8.2 | 2.09x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/nonascii-nomatch | 16 | 19.3 | 10.0 | 1.92x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAnyExcept/all-in-set | 16 | 20.6 | 20.1 | 1.02x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/ascii | 64 | 59.0 | 29.7 | 1.99x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/nonascii-nomatch | 64 | 62.3 | 25.4 | 2.45x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAnyExcept/all-in-set | 64 | 62.3 | 59.6 | 1.04x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/ascii | 1024 | 955.2 | 334.9 | 2.85x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/nonascii-nomatch | 1024 | 982.7 | 246.4 | 3.99x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAnyExcept/all-in-set | 1024 | 848.4 | 840.8 | 1.01x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/ascii | 16384 | 12280.3 | 4736.3 | 2.59x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAny/nonascii-nomatch | 16384 | 13989.3 | 4064.9 | 3.44x |
�[40m�[32minfo�[39m�[22m�[49m: SVBENCH | 20 sparse CJK (U+4E00-U+9FFF) |
IndexOfAnyExcept/all-in-set | 16384 | 15405.3 | 13793.9 | 1.12x |

</details>

<details>
<summary>Benchmark source (temporary test project, not
committed)</summary>

```csharp
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics.Wasm;
using Xunit;

namespace SvBench
{
    public class SearchValuesBench
    {
        [UnsafeAccessor(UnsafeAccessorKind.Constructor)]
        [return: UnsafeAccessorType("System.Buffers.ProbabilisticCharSearchValues, System.Private.CoreLib")]
        private static extern object NewProbabilistic(ReadOnlySpan<char> values, int maxInclusive);

        [UnsafeAccessor(UnsafeAccessorKind.Constructor)]
        [return: UnsafeAccessorType("System.Buffers.BitmapCharSearchValues, System.Private.CoreLib")]
        private static extern object NewBitmap(ReadOnlySpan<char> values, int maxInclusive);

        private static char[] Range(int start, int count, int step) =>
            Enumerable.Range(0, count).Select(i => (char)(start + i * step)).ToArray();

        private static IEnumerable<(string Name, char[] Values)> ValueSets()
        {
            yield return ("6 Latin Ext-A (U+0100-U+017F)", Range(0x100, 6, 20));
            yield return ("20 Latin Ext-A (U+0100-U+017F)", Range(0x100, 20, 6));
            yield return ("100 Greek+Cyrillic (U+0370-U+04FF)", Range(0x370, 100, 4));
            yield return ("204 dense (U+0100-U+01FF)", Enumerable.Range(0x100, 0x100).Where(c => c % 5 != 0).Select(c => (char)c).ToArray());
            yield return ("20 sparse CJK (U+4E00-U+9FFF)", Range(0x4E00, 20, 0x3FF));
        }

        private static long s_sink;

        private static double Measure(SearchValues<char> sv, char[] haystack, bool except)
        {
            ReadOnlySpan<char> span = haystack;
            // Calibrate iterations so that each sample takes ~40 ms.
            int iters = 1;
            while (true)
            {
                var sw = Stopwatch.StartNew();
                Run(sv, span, except, iters);
                if (sw.Elapsed.TotalMilliseconds > 40 || iters > (1 << 26)) break;
                iters *= 2;
            }

            double best = double.MaxValue;
            for (int s = 0; s < 7; s++)
            {
                var sw = Stopwatch.StartNew();
                Run(sv, span, except, iters);
                double ns = sw.Elapsed.TotalNanoseconds / iters;
                best = Math.Min(best, ns);
            }
            return best;
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void Run(SearchValues<char> sv, ReadOnlySpan<char> span, bool except, int iters)
        {
            long sum = 0;
            if (except)
            {
                for (int i = 0; i < iters; i++) sum += span.IndexOfAnyExcept(sv);
            }
            else
            {
                for (int i = 0; i < iters; i++) sum += span.IndexOfAny(sv);
            }
            s_sink += sum;
        }

        private static int NaiveIndexOfAny(char[] h, HashSet<char> set, bool except)
        {
            for (int i = 0; i < h.Length; i++) if (set.Contains(h[i]) != except) return i;
            return -1;
        }

        [Fact]
        public void Bench()
        {
            Console.WriteLine($"SVBENCH PackedSimd.IsSupported={PackedSimd.IsSupported}");
            int[] lengths = { 16, 64, 1024, 16384 };
            var rng = new Random(42);
            int failures = 0;

            foreach (var (name, values) in ValueSets())
            {
                int max = values.Max();
                var set = new HashSet<char>(values);
                var create = SearchValues.Create(values);
                var prob = (SearchValues<char>)NewProbabilistic(values, max);
                var bitmap = (SearchValues<char>)NewBitmap(values, max);
                bool oldHeuristicPicksProb = 2 * (128 + values.Length * 4) < 64 + max / 8;
                Console.WriteLine($"SVBENCH set=\"{name}\" Create=>{create.GetType().Name} oldHeuristic=>{(oldHeuristicPicksProb ? "Probabilistic" : "Bitmap")}");

                // Haystacks that never match (full scan): ASCII text, and non-ASCII text from the same block but outside the set.
                var nonSet = Enumerable.Range(0x80, 0x2000).Select(c => (char)c).Where(c => !set.Contains(c) && !char.IsSurrogate(c)).ToArray();
                var nearby = Enumerable.Range(values.Min() & ~0xFF, 0x200).Select(c => (char)c).Where(c => !set.Contains(c)).ToArray();

                foreach (int len in lengths)
                {
                    char[] ascii = Enumerable.Range(0, len).Select(_ => (char)rng.Next(0x20, 0x7F)).ToArray();
                    char[] near = Enumerable.Range(0, len).Select(_ => nearby[rng.Next(nearby.Length)]).ToArray();
                    char[] inSet = Enumerable.Range(0, len).Select(_ => values[rng.Next(values.Length)]).ToArray();

                    foreach (var (kind, hay, except) in new[] { ("IndexOfAny/ascii", ascii, false), ("IndexOfAny/nonascii-nomatch", near, false), ("IndexOfAnyExcept/all-in-set", inSet, true) })
                    {
                        int expected = NaiveIndexOfAny(hay, set, except);
                        foreach (var (impl, sv) in new[] { ("prob", prob), ("bitmap", bitmap), ("create", create) })
                        {
                            int actual = except ? hay.AsSpan().IndexOfAnyExcept(sv) : hay.AsSpan().IndexOfAny(sv);
                            if (actual != expected)
                            {
                                failures++;
                                Console.WriteLine($"SVBENCH MISMATCH set=\"{name}\" {kind} len={len} impl={impl} expected={expected} actual={actual}");
                            }
                        }

                        // Correctness with a match placed at the end.
                        if (!except)
                        {
                            char[] withMatch = (char[])hay.Clone();
                            withMatch[len - 1] = values[len % values.Length];
                            foreach (var (impl, sv) in new[] { ("prob", prob), ("bitmap", bitmap), ("create", create) })
                            {
                                int actual = withMatch.AsSpan().IndexOfAny(sv);
                                int exp = NaiveIndexOfAny(withMatch, set, false);
                                if (actual != exp)
                                {
                                    failures++;
                                    Console.WriteLine($"SVBENCH MISMATCH-END set=\"{name}\" {kind} len={len} impl={impl} expected={exp} actual={actual}");
                                }
                            }
                        }

                        double p = Measure(prob, hay, except);
                        double b = Measure(bitmap, hay, except);
                        Console.WriteLine($"SVBENCH | {name} | {kind} | {len} | {b:F1} | {p:F1} | {b / p:F2}x |");
                    }
                }
            }

            Console.WriteLine($"SVBENCH done failures={failures} sink={s_sink}");
            Assert.Equal(0, failures);
        }
    }
}

```

Run with:

```
XHARNESS_COMMAND=test-browser ./dotnet.sh build /t:Test src/libraries/System.Memory/tests/SvBench/SvBench.Tests.csproj /p:TargetOS=browser /p:TargetArchitecture=wasm /p:RuntimeFlavor=CoreCLR /p:Configuration=Release /p:TestWasmReadyToRun=true /p:EnableAggressiveTrimming=true /p:EnableNgenOptimization=false /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=true
```

`/p:EnableNgenOptimization=false` matters. Without it, the library-test
R2R configuration passes `StandardOptimizationData.mibc` and compiles
with crossgen2 `--partial`. Unprofiled CoreLib methods, including all of
`SearchValues`, then run in the interpreter at about 190 ns/char, and
with `PackedSimd.IsSupported == false`.

</details>

## Validation

- `./build.sh clr+libs+host+packs -os browser -c Release
/p:AotHostArchitecture=arm64 /p:AotHostOS=osx`: passed.
- Browser CoreCLR R2R (Chrome) run of `System.Memory.Tests` filtered to
`SpanTests.Test{,Last}IndexOfAny{,Except}_RandomInputs_Char`,
`SearchValues_Contains` and `SearchValues_GetValues`, using
`/p:TestScope=all /p:EnableNgenOptimization=false`: **1058 passed, 0
failed**. The random-input tests create `SearchValues<char>` from random
Latin-1 and full-range needles, which now go through
`ProbabilisticCharSearchValues` on wasm.

> [!NOTE]
> This PR description was generated with GitHub Copilot.

Co-authored-by: Copilot App <[email protected]>
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants