Skip to content

Vector{128,256}<T>.ToScalar suboptimal codegen \ { double } #12733

Closed

Description

@gfoidl

Vector128<long>.ToScalar() stores the xmm to the stack, then reads r64 from there via a mov.

vmovapd  xmmword ptr [rsp], xmm0
mov      rax, qword ptr [rsp]

Ideally this would use movq (c++ intrinsic: _mm_cvtsi128_si64), so asm becomes:

-   vmovapd  xmmword ptr [rsp], xmm0
-   mov      rax, qword ptr [rsp]
+   movq     rax, xmm0

Vector128<double>.ToScalar() produces expected code (vmovsd) -- no issue there.
Same CQ issue for int, and for Vector256<T>.
Didn't check other types, than noted here.

category:cq
theme:vector-codegen
skill-level:intermediate
cost:medium

Activity

  1. gfoidl commented on May 22, 2019

    @gfoidl
    MemberAuthor

    /cc: @tannergooding please have a look here

  2. fiigii commented on May 22, 2019

    @fiigii
    Contributor

    I remember that ToScalar on integer types are not intrinsic now. You can use Sse2.X64.ConvertToInt64 for Vector128<long>.

  3. gfoidl commented on May 22, 2019

    @gfoidl
    MemberAuthor

    Thanks.

    Sse2.X64.ConvertToInt64

    Is better, but still not ideal:

    vmovupd  xmm0, xmmword ptr [rsp+08H]
    vmovd    rax, xmm0

    It is documented as __int64 _mm_cvtsi128_si64 (__m128i a) MOVQ reg/m64, xmm, but JIT didn't emit the movq.

  4. mikedn commented on May 22, 2019

    @mikedn
    Contributor

    Is that output from the JIT's own disassembler? It's probably movq but displayed as movd.

  5. gfoidl commented on May 22, 2019

    @gfoidl
    MemberAuthor

    Looked at the JIT-dump and in VS-dissambly view (both in release with optimization on, tiering disabled).

    SharpLab with CoreCLR shows the same.

  6. fiigii commented on May 22, 2019

    @fiigii
    Contributor

    Right, vmovd rax, xmm0 is actually vmovq rax, xmm0.
    movd is an alias of movq on r64.

  7. fiigii commented on May 22, 2019

    @fiigii
    Contributor

    SharpLab with CoreCLR shows the same.

    BTW, in this link, vzeroupper is generated for Vector128 code. That should not be there, I will take a look.

  8. gfoidl commented on May 22, 2019

    @gfoidl
    MemberAuthor

    movd is an alias of movq on r64.

    👍

    So codegen could be

    vmovd    rax, xmmword ptr [rsp+08H]

    or

    vmovq    rax, xmmword ptr [rsp+08H]

    There is the extra vmovupd (see https://github.com/dotnet/coreclr/issues/24710#issuecomment-494720476)

    I will take a look.

    Thanks.

    My code to show this
    using System;
    using System.Runtime.CompilerServices;
    using System.Runtime.Intrinsics;
    using System.Runtime.Intrinsics.X86;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Vector128<sbyte> vec = Vector128.Create((byte)0x42).AsSByte();
                long l = ToLong(vec);
                double d = ToDouble(vec);
    
                if (double.IsNaN(d) || l == long.MaxValue)
                    Environment.Exit(1);
            }
    
            [MethodImpl(MethodImplOptions.NoInlining)]
            private static long ToLong(Vector128<sbyte> vec)
            {
                //return vec.AsInt64().ToScalar();
                return Sse2.X64.ConvertToInt64(vec.AsInt64());
            }
    
            [MethodImpl(MethodImplOptions.NoInlining)]
            private static double ToDouble(Vector128<sbyte> vec)
            {
                return vec.AsDouble().ToScalar();
            }
        }
    }
    dasm for that code
    ; Assembly listing for method Program:ToLong(struct):long
    ; Emitting BLENDED_CODE for X64 CPU with AVX - Unix
    ; optimized code
    ; rsp based frame
    ; partially interruptible
    ; Final local variable assignments
    ;
    ;  V00 arg0         [V00,T00] (  1,  1   )  simd16  ->  [rsp+0x08]
    ;# V01 OutArgs      [V01    ] (  1,  1   )  lclBlk ( 0) [rsp+0x00]   "OutgoingArgSpace"
    ;
    ; Lcl frame size = 0
    
    G_M6413_IG01:
           C5F877               vzeroupper
           6690                 nop
    
    G_M6413_IG02:
           C5F910442408         vmovupd  xmm0, xmmword ptr [rsp+08H]
           C4E1F97EC0           vmovd    rax, xmm0
    
    G_M6413_IG03:
           C3                   ret
    
    ; Total bytes of code 17, prolog size 5 for method Program:ToLong(struct):long
    ; ============================================================
    ; Assembly listing for method Program:ToDouble(struct):double
    ; Emitting BLENDED_CODE for X64 CPU with AVX - Unix
    ; optimized code
    ; rsp based frame
    ; partially interruptible
    ; Final local variable assignments
    ;
    ;  V00 arg0         [V00,T00] (  1,  1   )  simd16  ->  [rsp+0x08]
    ;# V01 OutArgs      [V01    ] (  1,  1   )  lclBlk ( 0) [rsp+0x00]   "OutgoingArgSpace"
    ;
    ; Lcl frame size = 0
    
    G_M24050_IG01:
           C5F877               vzeroupper
           6690                 nop
    
    G_M24050_IG02:
           C5FB10442408         vmovsd   xmm0, xmmword ptr [rsp+08H]
    
    G_M24050_IG03:
           C3                   ret
    
    ; Total bytes of code 12, prolog size 5 for method Program:ToDouble(struct):double
    ; ============================================================
  9. gfoidl commented on May 22, 2019

    @gfoidl
    MemberAuthor

    vzeroupper is generated for Vector128 code. That should not be there,

    Isn't this needed for VEX? No matter if Vector128 or Vector256.

  10. fiigii commented on May 22, 2019

    @fiigii
    Contributor

    It is a bit complex, please see https://github.com/dotnet/coreclr/issues/21062.
    But I am sure that codegen has something wrong.

  11. AndyAyersMS commented on May 22, 2019

    @AndyAyersMS
    Member

    Marking as future; if there's something surgical we can fix, or there's a bug, we can move to 3.0.

  12. omariom commented on May 24, 2019

    @omariom
    Contributor

    It might be related. xmm0 is spilled to the stack.

    private static long AsLong(double dbl)
    {
        return *(long*)&dbl;
    } 
  13. transferred this issue fromdotnet/coreclron Jan 31, 2020
  14. added this to the Future milestone on Jan 31, 2020
  15. gfoidl commented on Mar 11, 2020

    @gfoidl
    MemberAuthor

    @omariom for reference: this is tracked by #11413 (thx @EgorBo for the remainder).

  16. hypeartist commented on Apr 20, 2020

    @hypeartist
  17. gfoidl commented on Apr 20, 2020

    @gfoidl
    MemberAuthor

    @hypeartist this uses also the stack [rcx] and doesn't operate with registers solely.

  18. added
    JitUntriaged
    on Oct 28, 2020
  19. removed
    JitUntriaged
    on Oct 30, 2022
  20. AndyAyersMS commented on Jun 13, 2026

    @AndyAyersMS
    Member

    Note

    This comment was generated with Copilot CLI assistance.

    This now produces optimal codegen on current main. Closing as fixed.

    Repro:

    [MethodImpl(MethodImplOptions.NoInlining)]
    public static long V128LongToScalar(Vector128<long> v) => v.ToScalar();
    
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static long V256LongToScalar(Vector256<long> v) => v.ToScalar();
    
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static int V128IntToScalar(Vector128<int> v) => v.ToScalar();

    Current codegen (x64, AVX):

    ; Repro:V128LongToScalar(Vector128`1[long]):long
           mov      rax, qword ptr [rcx]
           ret
    
    ; Repro:V256LongToScalar(Vector256`1[long]):long
           mov      rax, qword ptr [rcx]
           ret
    
    ; Repro:V128IntToScalar(Vector128`1[int]):int
           mov      eax, dword ptr [rcx]
           ret

    (The implicit-byref ABI passes a pointer to the vector, so the JIT now folds straight to a scalar load — no spill round-trip.)

  21. locked and limited conversation to collaborators on Jul 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclr

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions