Skip to content

JIT: boxing shouldn't be removed for escaping managed references #122099

@EgorBo

Description

@EgorBo

This issue was reported through other channels

[MethodImpl(MethodImplOptions.NoInlining)]
ref int Test(Struct1 x)
{
    return ref ((I1)x).Method1();
}

public struct Struct1 : I1
{
    int field;

    [UnscopedRef]
    [MethodImpl(MethodImplOptions.NoInlining)]
    public ref int Method1() => ref field;
}

public interface I1
{
    [UnscopedRef]
    ref int Method1();
}

Here in Test JIT optimizes boxing for (I1)x) into:

; Method Class1:Test(Struct1):byref:this (FullOpts)
       sub      rsp, 40
       mov      dword ptr [rsp+0x20], edx
       lea      rcx, [rsp+0x20]
       call     [Struct1:Method1():byref:this]
       nop      
       add      rsp, 40
       ret      
; Total bytes of code: 25

Presumably, it's an UB for unmanaged pointers, but for all managed we probably should keep that boxing since it's a safe C# (the reference may also expose through a byref-like return type or a ref ByRefLikeType arg parameter.

cc @dotnet/jit-contrib

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions