Skip to content

JIT: (bug) call argument evaluation reverses two volatile reads #133524

Open

Description

@EgorBo

Repro

With a monotonically increasing value, the first Volatile.Read can never observe a larger value than the second.

using System;
using System.Runtime.CompilerServices;
using System.Threading;

class Program {
    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static bool Test(ref int value) =>
        Sink(Volatile.Read(ref value), Volatile.Read(ref value) + 1);

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static bool Sink(int first, int secondPlusOne) => first > secondPlusOne - 1;

    static void Main() {
        int value = 0, stop = 0;
        var publisher = new Thread(() => {
            for (int i = 1; i <= 100_000_000 && Volatile.Read(ref stop) == 0; i++)
                Volatile.Write(ref value, i);
        });
        publisher.Start();
        int reversed = 0;
        for (int i = 0; i < 2_000_000; i++)
            if (Test(ref value))
                reversed++;
        Volatile.Write(ref stop, 1);
        publisher.Join();
        Console.WriteLine($"Reversed monotonic reads: {reversed}; expected 0");
    }
}

Expected

Reversed monotonic reads: 0; expected 0

Actual

Reversed monotonic reads: 413; expected 0

The count is timing-dependent but was non-zero on every run (9, 199, 413).

The generated code for a two-reference variant shows the reversal deterministically
(Sink(Volatile.Read(ref first), Volatile.Read(ref second) + 1) under DOTNET_JitDisasm):

mov edx, dword ptr [rdx] ; read for the SECOND argument
inc edx
mov ecx, dword ptr [rcx] ; read for the FIRST argument
call Sink

Platform

Windows x64, .NET 11.0.0-rc.1.26425.128.

Activity

  1. added this to the 12.0.0 milestone on Sep 9, 2026
  2. added
    area-CodeGen-coreclr
    on Sep 9, 2026
  3. dotnet-policy-service commented on Sep 9, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  4. assigned and unassigned on Sep 9, 2026
  5. changed the title [-]JIT: call argument evaluation reverses two volatile reads[/-] [+]JIT: (bug) call argument evaluation reverses two volatile reads[/+] on Sep 10, 2026
  6. self-assigned this
    on Sep 14, 2026
  7. EgorBo commented on Sep 18, 2026

    @EgorBo
    MemberAuthor

    Affected SDK versions:

    • 8.0.425
    • 9.0.318
    • 10.0.401
    • 11.0.100-rc.2.26467.112
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions