Use unaligned loads and stores in UnalignedCopy64/128

Merged
BR
18d ago
+10-26

Summary

UnalignedCopy64 and UnalignedCopy128 copied through Unsafe.As refs. That emits plain ldobj/stobj with no unaligned. prefix, which lets the JIT assume the address is aligned for long or Guid. Callers pass arbitrary byte offsets: op + 1, literal pointers and match sources. On ARM32 the JIT may therefore emit LDRD/STRD or LDM/STM, which trap on misaligned addresses. #157 documented this as a known limitation; this PR fixes it.

Changes

  • UnalignedCopy64 and UnalignedCopy128 now use Unsafe.ReadUnaligned and Unsafe.WriteUnaligned, which emit the unaligned. prefix. Their <safety> comments drop the ARM32 caveat.
  • The readonly Unsafe.As extension is removed from UnsafeReadonly. Nothing calls it any more, and it is the API that allowed the aligned-load pattern.
  • CopyHelpers.cs:49 still uses Unsafe.As for the SSSE3 shuffle-pattern table. That path runs only on x86, so it is left as is.

Performance

  • x64 codegen is identical. I compared DOTNET_JitDisasm output on net11.0 before and after: mov qword for the 64-bit copy and vmovups xmm for the 128-bit copy. The only difference is one fewer inlinee, the removed wrapper.
  • Benchmarks (net10.0, in-process, Default job): within noise.
BenchmarkBeforeAfter
BlockCompressHtml22.59 µs ± 0.4422.09 µs ± 0.10
BlockDecompressHtml9.76 µs ± 0.159.54 µs ± 0.07

The UnalignedCopy64/UnalignedCopy128 micro-benchmarks measure under 1 ns, below resolution, so the disassembly comparison is the meaningful check for them.

Notes for reviewers

  • Not run on ARM32. I don't have ARM32 hardware or an emulator set up, so the ARM32 fix rests on the IL semantics, not on observed output.
  • Benchmarks ran with --inProcess. Since #157, BenchmarkDotNet's generated boilerplate fails to build under the memory-safety rules (CS9377), so the default out-of-process toolchain can't run. That is unrelated to this change and is being fixed separately.

Testing

  • dotnet build -c Release: succeeded.
  • dotnet test --project Snappier.Tests -c Release: 1,544 passed, 0 failed, across net8.0, net9.0, net10.0, net11.0 and net48.

🤖 Generated with Claude Code