Skip to content

JIT: (bug) wrong result when (m & Vector128.Create(a)) == <zero with side effects> is folded to vptest with a stale memory operand #136306

Closed

Description

@EgorBo

The AND + compare-with-zero is folded to vptest that reuses the AND's contained memory operand, so the memory is read after the RHS side effect (Interlocked.Exchange) instead of before it.

Minimal Repro

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

public static class Program
{
    public static void Main()
    {
        int[] a = { 1, 0, 0, 0 };
        Vector128<int> m = Vector128.Create(1, 0, 0, 0);
        Console.WriteLine(Test(m, a));
    }

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    public static bool Test(Vector128<int> m, int[] a)
    {
        return (m & Vector128.Create(a)) == (Vector128.Create(Interlocked.Exchange(ref a[0], 0)) & Vector128<int>.Zero);
    }
}

Expected

False (m & a is evaluated first = {1,0,0,0}, then a[0] is cleared; {1,0,0,0} != 0)

Actual

True (prints False with DOTNET_JitMinOpts=1)

       mov      eax, dword ptr [rdx+0x08]
       cmp      eax, 4
       jl       SHORT G_M65395_IG04
       vmovups  xmm0, xmmword ptr [rcx]
       add      rdx, 16
       xor      eax, eax
       xchg     dword ptr [rdx], eax
       vptest   xmm0, xmmword ptr [rdx]     ; reads a[0..3] after the xchg
       sete     al
       movzx    eax, al

Regression?

Same xchg + vptest xmm0, xmmword ptr [rdx] sequence and output True on net8.0 (8.0.32), net9.0 (9.0.21), net10.0 (10.0.13) and net11.0 (11.0.0-rc.2) with the release JIT. Not a regression.

Notes

  • Safe C# only, default config.
  • Root cause: in Lowering::LowerHWIntrinsicCmpOp (lowerxarch.cpp, GT_AND/GT_AND_NOT PTEST fold) the removed AND's already-contained memory operand is reused, so it is now read at the PTEST position, after the RHS side effect (the RHS is folded to Zero + COMMA side effects).

Activity

  1. added this to the 12.0.0 milestone on Oct 22, 2026
  2. added
    area-CodeGen-coreclr
    on Oct 22, 2026
  3. dotnet-policy-service commented on Oct 22, 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. added a commit that references this issue on Oct 27, 2026
    9f06f27
  5. self-assigned this
    on Oct 27, 2026
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