Skip to content

Invalid codegen with Unsafe.As on FullOpts when accessing a struct field through ulong->struct cast. #88950

Closed
@neon-sunset

Description

@neon-sunset

Description

Given:

struct Example
{
   object? Value;
   ulong Inner;

   struct ExampleInner { int Offset; int Length }
   
   public int Offset
   {
      get
      {
         var inner = Inner;
         return Unsafe.As<ulong, ExampleInner>(ref inner).Offset;
      }
   }
   
   public int Length
   {
      get
      {
         var inner = Inner;
         return Unsafe.As<ulong, ExampleInner>(ref inner).Length;
      }
   }
}

It appears that accessing ExampleInner fields stored as ulong produces invalid codegen on FullOpts but not on MinOpts or with Unsafe.BitCast: the produced assembly reads the Length field at the offset of 8 bytes instead of 12.

Reproduction Steps

  1. Create new console application
  2. Paste https://gist.github.com/neon-sunset/fed48339292c0cc1f153bf30ffb1ebca into Program.cs
  3. dotnet run -c release

Expected behavior

Output:

--- MinOpts
Offset: 1234
Length: 5678
--- As
Offset: 1234
Length: 5678
--- Bitcast
Offset: 1234
Length: 5678

Actual behavior

Output:

--- MinOpts
Offset: 1234
Length: 5678
--- As
Offset: 1234
Length: 1234 <--- Unexpected
--- Bitcast
Offset: 1234
Length: 5678

Regression?

Yes, does not reproduce on .NET 7 and .NET 6.

Known Workarounds

None, bitcast produces worse codegen.

Configuration

Reproduced on:

.NET SDK:
 Version:   8.0.100-preview.7.23364.31
 Commit:    378e8abf4f

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  14.0
 OS Platform: Darwin
 RID:         osx-arm64
 Base Path:   /usr/local/share/dotnet/sdk/8.0.100-preview.7.23364.31/
.NET SDK:
 Version:   8.0.100-preview.7.23363.19
 Commit:    bef7f10d1d

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.22621
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\8.0.100-preview.7.23363.19\

Other information

No response

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