Skip to content

JIT: Convert multi-range / multi-value set membership tests to a bit test - #135606

Closed
Corniel wants to merge 1 commit into
dotnet:mainfrom
Corniel:jit-group-regions
Closed

Corniel wants to merge 1 commit into
dotnet:mainfrom
Corniel:jit-group-regions

Conversation

@Corniel

@Corniel Corniel commented Oct 11, 2026 •

Copy link
Copy Markdown

Range set detection has been asked for before. After reading LLVM: Optimizing range checks by @EgorBo, I decided to give it a go. I think (I have no data to prove that though) that with the adoption of pattern matching there will be more occasions where the optimization can be applied. I've investigated 128-bit range masks too (to support all ASCII subsets) but have not included that.

I consider myself an experienced C# developer, but I am new to the JIT and C++. All C++ code was generated using opencode with Claude Sonnet 5.5.

Tests like c is >= '0' and <= '9' or >= 'A' and <= 'Z', c is 'a' or 'e' or 'i' or 'o' or 'u' or x is 2 or 3 or 5 or ... are currently left as a chain of compares and branches. FoldRangeTests only handles a single range and optSwitchDetectAndConvert only equality chains.

optSwitchConvertRangeTests (switchrecognition.cpp) now evaluates a tree of conditional/switch blocks that test one int/long local, and if there are only two outcomes and the values of one outcome fit in a 64-bit window, it creates a switch that TryLowerSwitchToBitTest lowers to a range check + bt (lsr/tbz on arm64). Sets spanning up to 127 values are handled when the part that doesn't fit is a single range (e.g. [a-zA-Z0-9_]). optSwitchConvert and the new code share optConvertToBitmapSwitch.

Not handled: long switches over a temp (tmp = x - c), sets that need two bit tables, ARM32, long on 32-bit targets.

Codegen (IsVowel): 88 -> 37 bytes, one bt. x is 2 or 3 or ... or 61 (int): 140 -> 31 bytes.

Micro-benchmarks (ns/char, x64, checked JIT): random data -35..-50% (vowels 1.31 -> 0.75, hex digit 1.24 -> 0.65, primes 1.39 -> 0.71, [a-zA-Z0-9_] 1.18 -> 0.98); no regression on always-match / always-no-match / constant input.

SuperPMI (libraries.pmi + benchmarks.*):

  • win-x64: -2857 bytes, 208 contexts changed (140 smaller, 59 larger by <= 35 bytes), PerfScore geomean in changed methods ~ -5.9%
  • win-x86: -536 bytes in the changed methods (63 files; a few larger regressions come from register allocation churn)
  • linux-x64: -2876 bytes, 203 contexts; linux-arm64: -924 bytes, no size regressions
  • win-arm64 (libraries.pmi): -1128 bytes, 27 contexts, 0 size regressions, PerfScore 24 better / 2 worse. A minimum compare cost of 7 is required on arm64, because ccmp chains are already cheap there (6: -1496 but 4 size regressions; 8: -924)
  • Throughput (instructions executed): +0.05% x64, +0.05% arm64, +0.06% x86

Tests: optRangeSetRecognition (hand written) and optRangeSetRecognitionGenerated (400 randomly generated sets over 8 integral types and 10 code shapes, compared against a reference). JIT.opt merged runner: 582 passed, 0 failed, also with JitStress 1/2, JitStressRegs 1/8 and JitMinOpts (the one JitStress=1 failure, GuardedDevirtualization/badinlinee, fails without this change too). JIT/Methodical: 2079 passed, 2 failed (InsertGCPoll, structinreg), identical without this change. Library test suites on net11.0 with this JIT (checked JIT in an overlaid testhost): System.Text.RegularExpressions 32153 passed, System.Text.Json 51350 passed, System.Private.Uri 15311 + 19 passed, no failures. Also run on x86 and with ~20 extra random fuzz seeds (the generator is not checked in).

Range set recognition JIT work - decision log

Goal: recognize constant set membership tests made of several ranges / values on one integral local
(e.g. c is >= '0' and <= '9' or >= 'A' and <= 'Z') and turn them into a range check + bit test (bt).
Code: src/coreclr/jit/switchrecognition.cpp (optSwitchConvertRangeTests, optConvertToBitmapSwitch), compiler.h.
Tests: src/tests/JIT/opt/OptSwitchRecognition/optRangeSetRecognition*.cs. Harness: .temp/verify.ps1.

Baseline findings

  • Existing: FoldRangeTests (single range -> (x-lo) u<= n), optSwitchDetectAndConvert (x==a||x==b||... -> switch -> bt).
  • Roslyn emits a decision tree (COND and SWITCH blocks), neither pass matched ranges mixed with each other. Not mentioned in a TODO.
  • Issue [RyuJIT] Recognize and optimize constant set membership tests #8418 is closed but covers only single range and equality sets.

Kept

Item Why
Interval evaluator over a tree of COND/SWITCH blocks on one local One mechanism handles all Roslyn shapes (is-patterns, ||, switch, negation, trees). Pattern matching per shape would be more code.
Ingest BBJ_SWITCH blocks Roslyn emits switches for or patterns (vowels, primes).
TYP_LONG for compare chains (64-bit targets) ~25 lines, tested.
Wide sets (span 64..127): bt + one range check for the tail [a-zA-Z0-9_], base64. ~25-40% faster on random data.
Shared helper optConvertToBitmapSwitch (+ profile weight update) Stress found missing profile update (assert); shared with old path.
Minimum tests = existing SWITCH_MIN_TESTS (3 x64) Thresholds 3 and 4 equal speed, 5 lost digit-or-upper.

Rejected / dropped

Idea Why rejected
Fold tmp = x - c temps for long switch (option A) Needs use rewriting, deleting a store (SSA use counts), multi-stmt blocks, and truncation modeling. Complexity vs rare case (0 hits in 81k method sweep). IsPrimeLong stays partially converted (167->101 bytes). Comment left in code.
Drop 64-bit support altogether Only ~25 lines, real tested coverage.
Two chained bit tables (2nd table also a bt) for any 128-value set Measured: random ~10% slower, no-match ~40% slower than compares (mispredicts, extra branch); needed 2nd switch + likelihood guesses. Kept only "tail is one range".
Branchless select between two 64-bit tables (cmov) C# micro-benchmark: no better than compares on random, clearly worse on match data (1.0-1.3 vs 0.65 ns).
SIMD (pshufb/tbl), BMI2 shrx, RISC-V bext SIMD register transfer too costly for scalar; shrx no gain over bt; Zbs only RISC-V, not pursued.
Temporary tuning knob JitRangeSetMinTests Removed after tuning.
ARM32 Skipped (bit test verbose, size regressions, same as existing code).
x86 long Not supported (x86 has no 64-bit bit table).

Open: memory table for 128-value sets (tbl[i>>6] >> i)

  • Micro-benchmark: best bit-based option, 15-25% faster than compare chain on random data, handles any 128-value set.
  • JIT plumbing: no existing API for arbitrary read-only qword data in this phase. Closest is GT_JMPTABLE
    (genEmitJumpTable, emitBBTableDataGenBeg + eeFindJitDataOffs), which holds block labels not constants;
    emitDataConst/emitBlkConst exist in the emitter (used for SIMD constants), would need a new node + codegen on every arch + AOT reloc check.
  • Corpus statistics (81k BCL methods compiled): 89 candidates reaching the span check:
    39 span<=63 (already handled), 11 span 64..127 (wide), 39 span>127 (never fits 128 either).
    So 128-bit memory table would affect at most 11 methods in the BCL, most with 3 tests and 3 members.
    => Not worth a new node + per-arch codegen at this point.

Measurements (checked JIT, ns/char, old -> new)

  • vowels random 1.31 -> 0.75; hex 1.24 -> 0.65; primes int 1.39 -> 0.71; digit-or-upper compares 0.89 -> 0.69; ident 1.18 -> 0.98.
  • Predictable "same value" case: no regression.
  • Framework sweep (81k methods): ~38 changed, -238 bytes net, largest regression +19 (Uri.CheckAuthorityHelper). No JIT asserts.
  • Generated tests: 209/400 -> 221/400 methods get bt (31 before change).

Bugs found by the harness

  • Profile weights not updated after conversion (JitStress assert in fgprofile).
  • Wrong offset for 2nd block in wide path; creating tree nodes before a bail-out trips the phase node-id check.

Not yet done

  • SuperPMI asmdiffs, throughput (TP) measurement, repo JIT test run, release-JIT build.
  • clang-format used v22 (CI version may differ).

SuperPMI asmdiffs (windows x64, checked JITs, base = JIT built without the change)

Collections: benchmarks.run, benchmarks.run_pgo, benchmarks.run_pgo_optrepeat, libraries.pmi (507k contexts, 70 missed = same as base).
Command: superpmi.py asmdiffs -core_root .temp\coreroot -base_jit_path .temp\spmi\base\... -diff_jit_path .temp\spmi\diff\... -spmi_location .temp\spmi\cache -filter benchmarks libraries.pmi
(jit-analyze is not installed, per-method sizes computed by parsing the dasm, see spmi_changes.csv.)

Run Size delta (libraries.pmi) Contexts with diffs Size improv / regress PerfScore improv / regress
First (wide path unrestricted) -2810 214 141 / 64 (-3286/+476) 169 / 40
With wide-path cost heuristic -2857 208 140 / 59 (-3282/+425) 165 / 38
Other collections: benchmarks.run -757, run_pgo -182, run_pgo_optrepeat -757 (all improvements by PerfScore, 36/8/36 contexts).
Relative PerfScore geomean in diffs: about -5.9%.

Learned from SPMI:

  • Wide path on sparse sets (x is 0 or 32 or 64 or 96) was a regression (range check + imm64 + bt + tail check > 4 compares).
    Fix: wide path requires compare cost >= 6 (single value = 1, range = 2). Ident ([a-zA-Z0-9_], cost 7) still converts.
  • Remaining regressions (+11..+35 bytes, 59 contexts) are non-wide: a 4-run set in a big dispatch (e.g. JSON lexer digits)
    becomes cmp; ja; mov r64,imm64; bt; jb; the 10-byte imm64 eats the saving. Possible follow-up: subtract min when it makes
    the table fit in 32 bits (saves 5 bytes for 3). Not done: small, perf-positive, adds branches to the heuristic.
  • Gotcha: restoring a file by Copy-Item keeps the old mtime, ninja did not rebuild -> the "stats" JIT was diffed once.

Still not done: throughput (TP) measurement, other architectures (arm64 SPMI needs cross JIT + collections), repo JIT tests, Release JIT build.

Throughput (superpmi tpdiff, Release JITs, instructions executed, windows x64)

Tools: superpmi.py tpdiff (downloads Pin), jitutils jit-tp-analyze (reads Pin traces, not asm dirs). jit-analyze was built into C:\code\dotnet-jit-utils\bin.
Gotchas: build.cmd ... -p:NoPgoOptimize=true fails in PowerShell ("-p" ambiguous) -> use /p:NoPgoOptimize=true; a failed build silently
left identical DLLs and produced a bogus 0.00% (verify base != diff with Get-FileHash before trusting results).

Variant libraries.pmi delta
first version (PGO build) +184M (+0.06%)
+ early bail on 3rd outcome, inline storage for cond succs, structural prefilter +159M (+0.05%), measured twice (PGO and NoPgoOptimize builds), so not PGO noise
Other collections: benchmarks.run +0.05%, run_pgo +0.05%, run_optrepeat +0.05%.
Bisecting (return early at various points, libraries.pmi): parse of first block only 72M; + exploration 158M; interval math + conversions only ~+1-18M.
Debug counters (36 SPMI workers): ~56k roots/worker, ~6k reach the parse, ~17k parse calls, ~50 reach >=3 tests -> the cost is the many small
failed explorations (each ~3 parses before the 3rd outcome bails), not the conversions. Inherent to a root-per-block design.
Mitigations that did NOT help much: allocation-free cond blocks (173M->173M), early outcome bail (184M->176M).
Possible further work: memoize parsed blocks per phase run; skip roots that are interior of an already failed chain (loses subset conversions).
Decision pending: +0.05% TP is borderline for dotnet/runtime; consider the memo if reviewers object.

Existing repo test (optSwitchRecognition.cs, 69 cases) run via an xunit shim

Old and new JIT, JitStress 0 and 2: all pass. (Full src/tests build not done; the new tests also only run via the shim.)
Decision: throughput memoization not pursued now (+0.05% TP accepted unless reviewers object).
Remaining: arm64 diff (needs cross JIT + arm64 collection), real src/tests build+run of the new test projects, final cleanup/PR text.

SuperPMI asmdiffs windows arm64 (cross JIT clrjit_universal_arm64_x64, base = build before the change)

Collection Size delta Contexts with diffs Size improv/regress PerfScore improv/regress
libraries.pmi -2256 110 93 / 13 83 / 26
benchmarks.run -680 23 19 / 3 16 / 7
run_pgo -92 4 4 / 0 1 / 1
jit-analyze (libraries.pmi, 58 unique files): -1396 bytes (-2.83% of changed code), no asserts/failures.
Codegen on arm64 uses the existing fallback lsr x0, x1, x0; tbz x0, #0 (no bt), still a win in size and mostly PerfScore.

Real repo test build/run (src/tests, checked x64, build.cmd checked x64 -priority 1 -tree JIT\opt, ~3 min + run.cmd ... tree JIT\opt\JIT.opt, ~4 min)

Result: 593 tests in the merged JIT.opt runner: 582 passed, 0 failed, 11 skipped (not ours). All new tests (optRangeSetRecognition, ...Generated Group0-19)
and the existing optSwitchRecognition pass with the new JIT.
generated Core_Root lacked System.Private.CoreLib.dll (copied from artifacts\bin\coreclr\windows.x64.Checked\IL); run.py crashes in the summary
step on a decimal-comma locale ('228,96') -> read artifacts\log\JIT.opt.JIT.opt.testRun.xml / the .log directly.

ARM64 PerfScore regressions (found by looking at the 26 regressing methods)

Cause: ARM64 already tests a chain of ranges well with ccmp (base IsHexDigit = sub/cmp/cset), while the bit table needs up to 4 instrs
(mov + 3 movk) for the 64-bit immediate, then lsr + tbz. Small sets (e.g. 3 ranges, cost 6) regressed (+1.5..+133 PerfScore).
Fix: compare-cost estimate (1 per value, 2 per range) now applies to all sets; threshold 8 on ARM64 (6 for wide, 0 otherwise on other targets).
Result arm64 libraries.pmi: size -2256 -> -548, PerfScore regressions 26 -> 8 of 28 contexts (19 improve). Threshold 8 is a judgement call
(hex digit = 6 excluded, primes/vowels kept); it gives up many small wins. Remaining regressions (ArraySortHelper +16 bytes) come from an
unrelated bounds-check difference, not from this pass. x64 diff unchanged by the fix.

Extra validation round

  • SPMI: win-x86 -536 bytes (63 files, regressions up to +68 bytes are register allocation churn in large methods), linux-x64 -2876 (203 ctx), linux-arm64 -924 (0 size regressions). No osx-arm64 collection exists.
  • arm64 threshold on libraries.pmi (base = JIT without change): 6 -> -1496 (46 ctx, 4 size regs, PerfScore 38/7); 7 -> -1128 (27 ctx, 0, 24/2); 8 -> -924 (19 ctx, 0, 17/1). Chose 7 (HexDigit has cost 6 and stays excluded).
  • Throughput (tpdiff, Release, NoPgoOptimize): arm64 +169M (+0.05%), x86 +154M (+0.06%).
  • JIT.opt runner under jitstress 1/2, jitstressregs 1/8, jitminopts: all pass except badinlinee under JitStress=1 (pre-existing, fails with the base JIT).
  • JIT/Methodical (2082 tests): 2 failures (InsertGCPoll, structinreg), identical with the base JIT.
  • Libraries tests: first attempt failed (libs-only testhost has no host/runtime). Second attempt worked: built -subset host (the installer/crossgen errors can be ignored, dotnet.exe/hostfxr.dll/hostpolicy.dll come out of artifacts\bin\win-x64.Release\corehost) and -subset libs.native, overlaid dotnet.exe, hostfxr (host\fxr\12.0.0), hostpolicy, Core_Root runtime files (incl. my checked clrjit.dll), a Microsoft.NETCore.App.deps.json (host ignores a framework dir without it) and the native libs (System.IO.Compression.Native etc.; missing zlib gave 1048 bogus ZLibException failures) into artifacts\bin\testhost\net11.0-windows-Release-x64. Results with dotnet.cmd build <test csproj> -t:Test -c Release -f net11.0: Regex 32153/0 failed, Json 51350/0, Uri 15311+19/0. The testhost folder is now modified (untracked artifacts only).
  • Fuzz generator bug: ranges near long.MaxValue overflowed (lo+len wrapped negative) -> a fuzz seed "failed" on a wrong test, not a JIT bug. Fixed with saturating adds; the checked-in generated test file was regenerated (old one contained 3 wrapped sets from index 247 on, it passed but was wrong).

@github-actions github-actions Bot added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Oct 11, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 11, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 5 pipeline(s).
11 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: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.

@EgorBo

EgorBo commented Oct 11, 2026

Copy link
Copy Markdown
Member

I consider myself an experienced C# developer, but I am new to the JIT and C++. All C++ code was generated using opencode with Claude Sonnet 5.5.

I appreciate the effort, but the JIT codebase is extremely complex, and even a one-line change can introduce a serious production bugs (too many edge-cases to keep in mind). I don’t think it’s a suitable target for AI-driven contributions without a thorough understanding of the changes. This PR proposes roughly 1000 LOCs of random changes - I am not sure we can proceed with this.

Also, we already do that transformation.

@Corniel

Corniel commented Oct 11, 2026

Copy link
Copy Markdown
Author

I consider myself an experienced C# developer, but I am new to the JIT and C++. All C++ code was generated using opencode with Claude Sonnet 5.5.

I appreciate the effort, but the JIT codebase is extremely complex, and even a one-line change can introduce a serious production bugs (too many edge-cases to keep in mind). I don’t think it’s a suitable target for AI-driven contributions without
a thorough understanding of the changes.

I can understand that. That's why I wanted to be totally honest about it.

This PR proposes roughly 1000 LOCs of random changes - I am not sure we can proceed with this.
Also, we already do that transformation.

What do you mean? As somebody is working on this?

@EgorBo

EgorBo commented Oct 11, 2026

Copy link
Copy Markdown
Member

What do you mean? As somebody is working on this?

No, it is already in the JIT, e.g.

{5AEE4CC3-B924-4863-B3B7-8369E466AA2B}

@Corniel

Corniel commented Oct 11, 2026

Copy link
Copy Markdown
Author

You might consider me stupid. I was pretty sure that c >= 'A' and <= 'Z' or '>= 0' and <='9' where not covered yet?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants