KEMBAR78
Optimize unboxing for nullable · Issue #104954 · dotnet/runtime · GitHub
Skip to content

Optimize unboxing for nullable #104954

@EgorBo

Description

@EgorBo
int? Unbox(object o) => (int?)o;

Currently generates:

; Method Prog:Foo(System.Object):System.Nullable`1[int] (FullOpts)
G_M28087_IG01:
       sub      rsp, 40
       mov      r8, rcx
G_M28087_IG02:
       lea      rcx, [rsp+0x20]
       mov      rdx, 0x7FF8318BB750      ; System.Nullable`1[int]
       call     CORINFO_HELP_UNBOX_NULLABLE
       mov      rax, qword ptr [rsp+0x20]
G_M28087_IG03:
       add      rsp, 40
       ret      
; Total bytes of code: 37

we should be able to avoid the unbox helper call here by inlining the fast path. E.g.

Nullable<int> stackLocal;
if (obj == null)
{
    stackLocal = {0};
}
else if (obj->pMT == int)
{
    stackLocal._hasValue = 1;
    stackLocal._value = *((int*)(obj + 8);
}
else
{
    CORINFO_HELP_UNBOX_NULLABLE(&stackLocal, obj, clsHandle); // cold fallback (no return?)
}

NOTE: no, we can't unbox int? out of boxed uint - it's InvalidCastException so we're fine here.

Metadata

Metadata

Assignees

Labels

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

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions