Skip to content

Escape Analysis: Elide an array allocation in BitConverter.GetBytes pattern #113236

Description

@EgorBo

JIT should be able to eliminate GC allocation in this snippet:

void Test(int value, Span<byte> dest) => 
    BitConverter.GetBytes(value).AsSpan(0, 3).CopyTo(dest);

This pattern could be used as a safe alternative to "write N-bytes of a primitive to a span of bytes". Alternative zero-alloc patterns don't look pretty/involve unsafe

Sub-tasks:

cc @AndyAyersMS

Activity

  1. ghost added
    area-CodeGen-coreclr
    on Mar 6, 2025
  2. added
    untriaged
    on Mar 6, 2025
  3. dotnet-policy-service commented on Mar 6, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  4. AndyAyersMS commented on Mar 6, 2025

    @AndyAyersMS
    Member

    Looks like my upcoming escape analysis changes will indeed stack allocate here...

  5. added
    in-pr
    on Mar 7, 2025
  6. removed
    untriaged
    on Mar 12, 2025
  7. added this to the 10.0.0 milestone on Mar 12, 2025
  8. added 2 commits that reference this issue on Mar 27, 2025
    02f29b0
    812df7b
  9. added a commit that references this issue on Apr 15, 2025
    212b120
  10. 3 remaining items

  11. AndyAyersMS commented on Apr 16, 2025

    @AndyAyersMS
    Member

    So, good news and not so good news. If I forcibly inline we end up with code like the below.

    No stack allocation, but we create a bunch of messes we really ought to be able to clean up.

    ; Method Program:<<Main>$>g__Test|0_0(int,System.Span`1[ubyte]) (FullOpts)
    G_M62296_IG01:  ;; offset=0x0000
           push     rsi
           push     rbx
           sub      rsp, 88
           vxorps   xmm4, xmm4, xmm4
           vmovdqa  xmmword ptr [rsp+0x20], xmm4
           xor      eax, eax
           mov      qword ptr [rsp+0x30], rax
           mov      rbx, rdx
    						;; size=26 bbWeight=1 PerfScore 6.08
    
    G_M62296_IG02:  ;; offset=0x001A
           mov      rdx, 0x7FFCDDE54E50      ; ubyte[]
           mov      qword ptr [rsp+0x20], rdx
           lea      rdx, [rsp+0x20]
           mov      dword ptr [rdx+0x08], 4
           lea      rsi, [rsp+0x20]
           test     rsi, rsi
           je       SHORT G_M62296_IG09
    						;; size=37 bbWeight=1 PerfScore 4.50
    
    G_M62296_IG03:  ;; offset=0x003F
           lea      rdx, [rsi+0x10]
           mov      bword ptr [rsp+0x48], rdx
           mov      edx, 4
    						;; size=14 bbWeight=0.50 PerfScore 0.88
    
    G_M62296_IG04:  ;; offset=0x004D
           mov      rax, qword ptr [rsp+0x48]
           cmp      edx, 4
           jl       SHORT G_M62296_IG06
    						;; size=10 bbWeight=1 PerfScore 2.25
    
    G_M62296_IG05:  ;; offset=0x0057
           mov      dword ptr [rax], ecx
           jmp      SHORT G_M62296_IG07
    						;; size=4 bbWeight=0.50 PerfScore 1.50
    
    G_M62296_IG06:  ;; offset=0x005B
           mov      rcx, 0x2060020ED28      ; 'success'
           mov      rdx, 0x20600200008      ; ''
           call     [System.Diagnostics.Debug:Fail(System.String,System.String)]
    						;; size=26 bbWeight=0.50 PerfScore 1.75
    
    G_M62296_IG07:  ;; offset=0x0075
           test     rsi, rsi
           je       SHORT G_M62296_IG10
           add      rsi, 16
           mov      bword ptr [rsp+0x38], rsi
           mov      rax, qword ptr [rsp+0x38]
           mov      rcx, bword ptr [rbx]
           mov      edx, dword ptr [rbx+0x08]
           cmp      edx, 3
           jl       SHORT G_M62296_IG11
           movzx    rdx, word  ptr [rax]
           movzx    r8, word  ptr [rax+0x01]
           mov      word  ptr [rcx], dx
           mov      word  ptr [rcx+0x01], r8w
    						;; size=46 bbWeight=1 PerfScore 14.75
    
    G_M62296_IG08:  ;; offset=0x00A3
           add      rsp, 88
           pop      rbx
           pop      rsi
           ret      
    						;; size=7 bbWeight=1 PerfScore 2.25
    
    G_M62296_IG09:  ;; offset=0x00AA
           xor      edx, edx
           xor      eax, eax
           mov      qword ptr [rsp+0x48], rax
           jmp      SHORT G_M62296_IG04
    						;; size=11 bbWeight=0 PerfScore 0.00
    
    G_M62296_IG10:  ;; offset=0x00B5
           call     [System.ThrowHelper:ThrowArgumentOutOfRangeException()]
           int3     
    						;; size=7 bbWeight=0 PerfScore 0.00
    
    G_M62296_IG11:  ;; offset=0x00BC
           call     [System.ThrowHelper:ThrowArgumentException_DestinationTooShort()]
           int3     
    						;; size=7 bbWeight=0 PerfScore 0.00
    ; Total bytes of code: 195
  12. EgorBo commented on Apr 16, 2025

    @EgorBo
    MemberAuthor

    @AndyAyersMS perhaps, the codegen is a lot better in Release version of corelib? since yours is Checked with asserts

  13. AndyAyersMS commented on Apr 16, 2025

    @AndyAyersMS
    Member

    Could be... will need to do a proper check since the config I used to alter inlining doesn't work in release.

    Oddly if I use DOTNET_JitAggressiveInlining=1 (which works in release) we think the array escapes. So will need to look into that too.

  14. AndyAyersMS commented on Apr 17, 2025

    @AndyAyersMS
    Member

    Ok with #114749 and a targeted inlining hint we have

    ; Method Program:<<Main>$>g__Test|0_0(int,System.Span`1[ubyte]) (FullOpts)
    G_M62296_IG01:  ;; offset=0x0000
           sub      rsp, 72
           vxorps   xmm4, xmm4, xmm4
           vmovdqa  xmmword ptr [rsp+0x20], xmm4
           xor      eax, eax
           mov      qword ptr [rsp+0x30], rax
    						;; size=21 bbWeight=1 PerfScore 3.83
    
    G_M62296_IG02:  ;; offset=0x0015
           mov      rax, 0x7FFCD1814E50      ; ubyte[]
           mov      qword ptr [rsp+0x20], rax
           lea      rax, [rsp+0x20]
           mov      dword ptr [rax+0x08], 4
           lea      rax, [rsp+0x20]
           add      rax, 16
           mov      bword ptr [rsp+0x38], rax
           mov      r8, rax
           mov      dword ptr [r8], ecx
           mov      rcx, bword ptr [rdx]
           mov      edx, dword ptr [rdx+0x08]
           cmp      edx, 3
           jl       SHORT G_M62296_IG04
           movzx    rdx, word  ptr [rax]
           movzx    r8, word  ptr [rax+0x01]
           mov      word  ptr [rcx], dx
           mov      word  ptr [rcx+0x01], r8w
    						;; size=74 bbWeight=1 PerfScore 17.00
    
    G_M62296_IG03:  ;; offset=0x005F
           add      rsp, 72
           ret      
    						;; size=5 bbWeight=1 PerfScore 1.25
    
    G_M62296_IG04:  ;; offset=0x0064
           call     [System.ThrowHelper:ThrowArgumentException_DestinationTooShort()]
           int3     

    Still a bit messy, but better than what I showed above.

    Seems like we might want to boost inlining for methods that

    • allocate a small, fixed-sized array
    • return that array (probably not easy to spot this in IL, so maybe just "returns array")
  15. AndyAyersMS commented on Apr 17, 2025

    @AndyAyersMS
    Member

    R2R doesn't inline TryWriteBytes

    G_M62296_IG01:  ;; offset=0x0000
           push     rdi
           push     rsi
           push     rbx
           sub      rsp, 48
           xor      eax, eax
           mov      qword ptr [rsp+0x20], rax
           mov      qword ptr [rsp+0x28], rax
           mov      esi, ecx
           mov      rbx, rdx
                                                    ;; size=24 bbWeight=1 PerfScore 6.00
    G_M62296_IG02:  ;; offset=0x0018
           mov      ecx, 4
           call     [CORINFO_HELP_READYTORUN_NEWARR_1]
           mov      rdi, rax
           lea      rcx, bword ptr [rdi+0x10]
           mov      bword ptr [rsp+0x20], rcx
           mov      dword ptr [rsp+0x28], 4
           lea      rcx, [rsp+0x20]
           mov      edx, esi
           call     [System.BitConverter:TryWriteBytes(System.Span`1[ubyte],int):ubyte]
           add      rdi, 16
           mov      rsi, bword ptr [rbx]
           mov      eax, dword ptr [rbx+0x08]
           cmp      eax, 3
           jge      SHORT G_M62296_IG04
                                                    ;; size=59 bbWeight=1 PerfScore 15.25
    G_M62296_IG03:  ;; offset=0x0053
           call     [System.ThrowHelper:ThrowArgumentException_DestinationTooShort()]
           int3
                                                    ;; size=7 bbWeight=0.50 PerfScore 1.62
    G_M62296_IG04:  ;; offset=0x005A
           movzx    rax, word  ptr [rdi]
           movzx    rcx, word  ptr [rdi+0x01]
           mov      word  ptr [rsi], ax
           mov      word  ptr [rsi+0x01], cx
                                                    ;; size=14 bbWeight=1 PerfScore 6.00
    G_M62296_IG05:  ;; offset=0x0068
           add      rsp, 48
           pop      rbx
           pop      rsi
           pop      rdi
           ret
                                                    ;; size=8 bbWeight=1 PerfScore 2.75

    R2R evaluation

    
    Inline candidate has an arg that feeds a constant test.  Multiplier increased to 1.
    Inline candidate callsite is boring.  Multiplier increased to 2.3.
    calleeNativeSizeEstimate=461
    callsiteNativeSizeEstimate=135
    benefit multiplier=2.3
    threshold=310
    Native estimate for function size exceeds threshold for inlining 46.1 > 31 (multiplier = 2.3)
    
    
    Inline expansion aborted, inline not profitable
    Inlining [000020] failed, so bashing STMT00008 to NOP
    INLINER: during 'fgInline' result 'failed this call site' reason 'unprofitable inline' for 'Program:<<Main>$>g__Test|0_0(int,System.Span`1[ubyte])' calling 'System.BitConverter:TryWriteBytes(System.Span`1[ubyte],int):ubyte'
    INLINER: during 'fgInline' result 'failed this call site' reason 'unprofitable inline'
    

    JIT evaluation

    1 arguments are structs passed by value.  Multiplier increased to 2.
    Inline has 2 intrinsics.  Multiplier increased to 3.6.
    Inline candidate has 1 binary expressions with constants.  Multiplier increased to 4.1.
    Inline candidate callsite is boring.  Multiplier increased to 5.4.
    calleeNativeSizeEstimate=461
    callsiteNativeSizeEstimate=135
    benefit multiplier=5.4
    threshold=728
    Native estimate for function size is within threshold for inlining 46.1 <= 72.8 (multiplier = 5.4)
    

    If I unblock that, we don't stack allocate:

    G_M62296_IG01:        ; func=00, offs=0x000000, size=0x000B, bbWeight=1, PerfScore 2.75, gcrefRegs=0000 {}, byrefRegs=0000 {}, byref, nogc <-- Prolog IG
    
    IN0010: 000000 push     rsi
    IN0011: 000001 push     rbx
    IN0012: 000002 sub      rsp, 40
    IN0013: 000006 mov      esi, ecx
    IN0014: 000008 mov      rbx, rdx
    
    G_M62296_IG02:        ; offs=0x00000B, size=0x0020, bbWeight=1, PerfScore 10.25, gcrefRegs=0000 {}, byrefRegs=0008 {rbx}, BB01 [0000], byref, isz
    
    IN0001: 00000B mov      ecx, 4
    IN0002: 000010 call     [CORINFO_HELP_READYTORUN_NEWARR_1]
    IN0003: 000016 lea      rcx, bword ptr [rax+0x10]
    IN0004: 00001A mov      dword ptr [rcx], esi
    IN0005: 00001C add      rax, 16
    IN0006: 000020 mov      rsi, bword ptr [rbx]
    IN0007: 000023 mov      ecx, dword ptr [rbx+0x08]
    IN0008: 000026 cmp      ecx, 3
    IN0009: 000029 jge      SHORT G_M62296_IG04
    
    G_M62296_IG03:        ; offs=0x00002B, size=0x0007, bbWeight=0.50, PerfScore 1.62, gcrefRegs=0000 {}, byrefRegs=0000 {}, BB12 [0030], byref
    
    IN000a: 00002B call     [System.ThrowHelper:ThrowArgumentException_DestinationTooShort()]
    IN000b: 000031 int3     
    
    G_M62296_IG04:        ; offs=0x000032, size=0x000E, bbWeight=1, PerfScore 6.00, gcrefRegs=0000 {}, byrefRegs=0041 {rax rsi}, BB11 [0029], byref
    
    IN000c: 000032 movzx    rcx, word  ptr [rax]
    IN000d: 000035 movzx    rdx, word  ptr [rax+0x01]
    IN000e: 000039 mov      word  ptr [rsi], cx
    IN000f: 00003C mov      word  ptr [rsi+0x01], dx
    
    G_M62296_IG05:        ; offs=0x000040, size=0x0007, bbWeight=1, PerfScore 2.25, epilog, nogc, extend
    
    IN0015: 000040 add      rsp, 40
    IN0016: 000044 pop      rbx
    IN0017: 000045 pop      rsi
    IN0018: 000046 ret   
  16. AndyAyersMS commented on Apr 28, 2025

    @AndyAyersMS
    Member

    Current codegen (both TC=0 and PGO):

    G_M62296_IG01:  ;; offset=0x0000
           sub      rsp, 72
           vxorps   xmm4, xmm4, xmm4
           vmovdqa  xmmword ptr [rsp+0x20], xmm4
           xor      eax, eax
           mov      qword ptr [rsp+0x30], rax
    						;; size=21 bbWeight=1 PerfScore 3.83
    G_M62296_IG02:  ;; offset=0x0015
           mov      rax, 0x7FF7CBDD8188      ; ubyte[]
           mov      qword ptr [rsp+0x20], rax
           lea      rax, [rsp+0x20]
           mov      dword ptr [rax+0x08], 4
           lea      rax, [rsp+0x20]
           add      rax, 16
           mov      bword ptr [rsp+0x38], rax
           mov      r8, rax
           mov      dword ptr [r8], ecx
           mov      rcx, bword ptr [rdx]
           mov      edx, dword ptr [rdx+0x08]
           cmp      edx, 3
           jl       SHORT G_M62296_IG04
           movzx    rdx, word  ptr [rax]
           movzx    r8, word  ptr [rax+0x01]
           mov      word  ptr [rcx], dx
           mov      word  ptr [rcx+0x01], r8w
    						;; size=74 bbWeight=1 PerfScore 17.00
    G_M62296_IG03:  ;; offset=0x005F
           add      rsp, 72
           ret      
    						;; size=5 bbWeight=1 PerfScore 1.25
    G_M62296_IG04:  ;; offset=0x0064
           call     [System.ThrowHelper:ThrowArgumentException_DestinationTooShort()]
           int3 
  17. AndyAyersMS commented on Apr 28, 2025

    @AndyAyersMS
    Member

    For R2R inlining doesn't happen unless there is static PGO data (I think, a little tricky to verify right now)... the "returns new array" heuristic requires the extended default policy.

  18. removed
    in-pr
    on Apr 29, 2025
  19. AndyAyersMS commented on Jul 9, 2025

    @AndyAyersMS
    Member

    I don't think we're going to get this working in .NET 10.

    • We need to land #116651, which is held up because we generally can't embed array class handles in R2R.
    • We need to figure out a proper inlining boost for TryWriteBytes, but a broad boost seems risky. I am seeing perf issues with more inlining in R2R, which will plague us until we can sort out Support profile instrumentation for inlinees #44372. And a targeted boost may not be that great either (say aggressive inlining) as there methods for each different primitive data type.

    I'm going to move this to future... if we manage to merge #116651 maybe we can take another look.

  20. modified the milestones: 10.0.0, Future on Jul 9, 2025
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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions