Skip to content

JIT: Raise the cutoff for lowering switches to direct branches - #138460

Open
NinoFloris wants to merge 3 commits into
dotnet:mainfrom
NinoFloris:jit/small-switch-branches
Open

NinoFloris wants to merge 3 commits into
dotnet:mainfrom
NinoFloris:jit/small-switch-branches

Conversation

@NinoFloris

@NinoFloris NinoFloris commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

I did a bit of comparing of swift vs C# codegen for https://ben-chmarks.com/gemini-neon/dlist/

The jump table (and spills that get fixed by #137509) stood out on arm64.

From https://ben-chmarks.com/benchmarks/dlist/lang/csharp/Driver.cs

for (int j = 0; j < cnt; j++) {
    ulong x = hs[at[j]];
    switch (op[j]) {
        case OP_AFTER:
            hs[lv++] = l.InsertAfter(x, vs[j]);
            break;
        case OP_BEFORE:
            hs[lv++] = l.InsertBefore(x, vs[j]);
            break;
        case OP_REMOVE:
            acc += (ulong)l.Remove(x) ^ (ulong)j;
            hs[at[j]] = hs[--lv];
            break;
        case OP_GET:
            acc += (ulong)l.Get(x) ^ (ulong)j;
            break;
        default:
            l.MoveToFront(x);
            break;
    }
}

We now stop emitting a jump table for this switch on ARM64. We chose the 7 + default cutoff empirically on an M1 Max. For dense switches like this one, LLVM’s corresponding cutoffs are 3 + default on x64 and normally 9 + default on ARM64.

See results #138460 (comment)

@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 Nov 28, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 28, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 5 pipeline(s).
10 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.

@NinoFloris

This comment was marked as outdated.

@NinoFloris

This comment was marked as outdated.

@NinoFloris

This comment was marked as outdated.

@EgorBo

EgorBo commented Nov 28, 2026 •

Copy link
Copy Markdown
Member
{64963604-D642-43C8-966D-469A2F3584CE}

so we now emit less jump tables and more conditions? it is not something that you can validate with a benchmark that hits the same conditions every time (so you benchmark the branch predictor + speculative execution). I don't think it's a good change

@NinoFloris

NinoFloris commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

The benchmark actually tests 3 patterns? Uniform slightly regresses (not sure for amd), so we could go fully neutral (or better) by making the cutoff 3, but in that case we should determine arm64's cutoff independently.

TP is more worrying, but we could do this in the emitter too, which should avoid the added BB-related work.

@NinoFloris

Copy link
Copy Markdown
Contributor Author

@EgorBot -intel -azure_linux_cobalt200 --envvars DOTNET_JitDisasm:Dispatch* DOTNET_JitDisasmOnlyOptimized:1

using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;

public class SmallSwitch
{
    private const int Count = 131072;
    private byte[] keys3, keys4, keys7;

    [Params("Uniform", "Cyclic", "HotFirst", "HotLast")]
    public string Pattern { get; set; } = "Uniform";

    [GlobalSetup]
    public void Setup()
    {
        keys3 = MakeKeys(3);
        keys4 = MakeKeys(4);
        keys7 = MakeKeys(7);
    }

    private byte[] MakeKeys(int cases)
    {
        var keys = new byte[Count];
        uint state = 174526;
        for (int i = 0; i < keys.Length; i++)
        {
            state = unchecked(state * 1664525 + 1013904223);
            int key = (int)((state >> 16) % (uint)(cases + 1));
            if (Pattern == "Cyclic")
                key = i % (cases + 1);
            else if ((state >> 24) < 230)
            {
                if (Pattern == "HotFirst") key = 0;
                if (Pattern == "HotLast") key = cases - 1;
            }
            keys[i] = (byte)key;
        }
        return keys;
    }

    [Benchmark(OperationsPerInvoke = Count)]
    public int Run3()
    {
        int x = 1;
        foreach (byte key in keys3)
            x = Dispatch3(key, x);
        return x;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Dispatch3(int key, int x) => key switch
    {
        0 => x * 3 + 5,
        1 => (x << 5) ^ 7,
        2 => x * 5 - 11,
        _ => ~x
    };

    [Benchmark(OperationsPerInvoke = Count)]
    public int Run4()
    {
        int x = 1;
        foreach (byte key in keys4)
            x = Dispatch4(key, x);
        return x;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Dispatch4(int key, int x) => key switch
    {
        0 => x * 3 + 5,
        1 => (x << 5) ^ 7,
        2 => x * 5 - 11,
        3 => (x >> 3) + 17,
        _ => ~x
    };

    [Benchmark(OperationsPerInvoke = Count)]
    public int Run7()
    {
        int x = 1;
        foreach (byte key in keys7)
            x = Dispatch7(key, x);
        return x;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Dispatch7(int key, int x) => key switch
    {
        0 => x * 3 + 5,
        1 => (x << 5) ^ 7,
        2 => x * 5 - 11,
        3 => (x >> 3) + 17,
        4 => (x * 11) ^ 85,
        5 => (x >> 6) - 85,
        6 => (x << 7) + 78,
        _ => ~x
    };
}

@NinoFloris

Copy link
Copy Markdown
Contributor Author

Summarized:

On Cobalt 200, direct branches reduced dispatch time for uniform keys at all three widths. At seven cases, uniform went from 6.263 to 5.785 ns (−7.6%) and cyclic went from 1.822 to 1.597 ns (−12.3%). On Intel, the three-case switch improved by 9.4% on uniform keys and 18.2% on cyclic keys.

Change in mean time per dispatch versus main. Negative is faster. Case counts exclude the default arm.

Input Cobalt · 3 Cobalt · 4 Cobalt · 7 Intel · 3 Intel · 4† Intel · 7†
Uniform −10.5% −13.1% −7.6% −9.4% +13.4% −0.5%
Cyclic −2.9% −0.9% −12.3% −18.2% −0.7% −8.9%
HotFirst −0.3% −0.2% −0.4% +1.1% −2.6% −0.2%
HotLast +0.5% −1.5% −5.8% −3.1% +14.2% −10.9%

† Intel 4 and 7 are controls. Both builds emitted jump tables there. Intel 4 Uniform took 13.4% longer on the PR; the Tier 1 code had a different block layout. Intel 4 HotLast took 14.2% longer even with identical printed dispatch instructions. Each toolchain had one process launch per benchmark, so those timings alone do not establish a cutoff effect.

With three cases, Cyclic repeats 0, 1, 2, default. Uniform picks among the same four outcomes in pseudorandom order. HotFirst and HotLast favor the first and last explicit case in source order.

Mean time per dispatch (ns), main → PR
Cases Input Cobalt 200 Intel Emerald Rapids
3 Uniform 5.444 → 4.875 7.886 → 7.141
3 Cyclic 1.626 → 1.579 2.955 → 2.416
3 HotFirst 1.589 → 1.585 2.087 → 2.111
3 HotLast 1.586 → 1.594 2.463 → 2.387
4 Uniform 5.715 → 4.969 8.210 → 9.307
4 Cyclic 1.589 → 1.575 2.599 → 2.582
4 HotFirst 1.624 → 1.621 2.263 → 2.204
4 HotLast 1.599 → 1.575 2.239 → 2.558
7 Uniform 6.263 → 5.785 9.703 → 9.659
7 Cyclic 1.822 → 1.597 3.097 → 2.821
7 HotFirst 1.696 → 1.690 2.471 → 2.467
7 HotLast 1.691 → 1.593 2.804 → 2.498

Cobalt 200 results · Intel Emerald Rapids results

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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