Repository navigation
Conversation
|
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. |
|
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch |
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. |
I can understand that. That's why I wanted to be totally honest about it.
What do you mean? As somebody is working on this? |
|
You might consider me stupid. I was pretty sure that |

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'orx is 2 or 3 or 5 or ...are currently left as a chain of compares and branches.FoldRangeTestsonly handles a single range andoptSwitchDetectAndConvertonly equality chains.optSwitchConvertRangeTests(switchrecognition.cpp) now evaluates a tree of conditional/switch blocks that test oneint/longlocal, and if there are only two outcomes and the values of one outcome fit in a 64-bit window, it creates a switch thatTryLowerSwitchToBitTestlowers to a range check +bt(lsr/tbzon 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_]).optSwitchConvertand the new code shareoptConvertToBitmapSwitch.Not handled:
longswitches over a temp (tmp = x - c), sets that need two bit tables, ARM32,longon 32-bit targets.Codegen (
IsVowel): 88 -> 37 bytes, onebt.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.*):
Tests:
optRangeSetRecognition(hand written) andoptRangeSetRecognitionGenerated(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
FoldRangeTests(single range ->(x-lo) u<= n),optSwitchDetectAndConvert(x==a||x==b||...-> switch ->bt).Kept
||, switch, negation, trees). Pattern matching per shape would be more code.BBJ_SWITCHblocksorpatterns (vowels, primes).TYP_LONGfor compare chains (64-bit targets)bt+ one range check for the tail[a-zA-Z0-9_], base64. ~25-40% faster on random data.optConvertToBitmapSwitch(+ profile weight update)SWITCH_MIN_TESTS(3 x64)Rejected / dropped
tmp = x - ctemps for long switch (option A)IsPrimeLongstays partially converted (167->101 bytes). Comment left in code.bt) for any 128-value setcmov)pshufb/tbl), BMI2shrx, RISC-Vbextshrxno gain overbt; Zbs only RISC-V, not pursued.JitRangeSetMinTestslongOpen: memory table for 128-value sets (
tbl[i>>6] >> i)GT_JMPTABLE(
genEmitJumpTable,emitBBTableDataGenBeg+eeFindJitDataOffs), which holds block labels not constants;emitDataConst/emitBlkConstexist in the emitter (used for SIMD constants), would need a new node + codegen on every arch + AOT reloc 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)
Uri.CheckAuthorityHelper). No JIT asserts.bt(31 before change).Bugs found by the harness
Not yet done
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.)
Learned from SPMI:
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.
becomes
cmp; ja; mov r64,imm64; bt; jb; the 10-byte imm64 eats the saving. Possible follow-up: subtract min when it makesthe table fit in 32 bits (saves 5 bytes for 3). Not done: small, perf-positive, adds branches to the heuristic.
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), jitutilsjit-tp-analyze(reads Pin traces, not asm dirs). jit-analyze was built into C:\code\dotnet-jit-utils\bin.Gotchas:
build.cmd ... -p:NoPgoOptimize=truefails in PowerShell ("-p" ambiguous) -> use/p:NoPgoOptimize=true; a failed build silentlyleft identical DLLs and produced a bogus 0.00% (verify base != diff with Get-FileHash before trusting results).
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)
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
-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 withdotnet.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).