Skip to content

JIT: x64 INSERTPS source-lane fold is unreachable, so Insert(v, <lane N>) keeps a redundant shuffle #134942

Closed

Description

@AndyAyersMS

Lowering::LowerHWIntrinsic has a fold for NI_X86Base_Insert (INSERTPS) that rewrites the imm8 count_s field so the instruction reads the source lane directly, instead of first materializing that lane in lane 0 with a separate shuffle. The fold is gated on op2 still being a NI_Vector_CreateScalarUnsafe node:

if ((count_s == 0) && op2->OperIsHWIntrinsic(NI_Vector_CreateScalarUnsafe))

But the case NI_Vector_CreateScalarUnsafe: arm of the same function already removes a floating-point CreateScalarUnsafe whenever its user is another HW intrinsic, and operands are lowered before their users. For a TYP_FLOAT Insert the wrapper is therefore always gone by the time this check runs, so the guard never holds and the fold body is effectively dead. Every Insert(vector, <extracted lane N>, ...) with N != 0 keeps a movshdup / unpckhps / shufps that insertps could have encoded for free in its immediate.

Recognizing the already-unwrapped ("bare") extraction as a second entry into the same, otherwise unchanged, fold body restores the optimization.

Minimal repro

using System;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;

public static class P
{
    // Missed case: source lane 1 -> destination lane 2.
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static Vector128<float> InsertRegSrc(Vector128<float> d, Vector128<float> s)
    {
        Vector128<float> t = s + Vector128.Create(1.0f);
        return Sse41.Insert(d, Vector128.CreateScalarUnsafe(t.GetElement(1)), 0x20);
    }

    // Source lane 3 -> destination lane 1.
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static Vector128<float> InsertRegSrcLane3(Vector128<float> d, Vector128<float> s)
    {
        Vector128<float> t = s + Vector128.Create(1.0f);
        return Sse41.Insert(d, Vector128.CreateScalarUnsafe(t.GetElement(3)), 0x10);
    }

    // Same miss through the portable API.
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static Vector128<float> InsertRegSrcWithElement(Vector128<float> d, Vector128<float> s)
    {
        Vector128<float> t = s + Vector128.Create(1.0f);
        return d.WithElement(2, t.GetElement(1));
    }

    // Counterfactual: the same fold written by hand, imm 0x60 = src lane 1, dst lane 2, zmask 0.
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static Vector128<float> InsertRegSrcDirect(Vector128<float> d, Vector128<float> s)
    {
        Vector128<float> t = s + Vector128.Create(1.0f);
        return Sse41.Insert(d, t, 0x60);
    }

    // Control: source lane 0 is already optimal today.
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static Vector128<float> InsertRegSrcLane0(Vector128<float> d, Vector128<float> s)
    {
        Vector128<float> t = s + Vector128.Create(1.0f);
        return Sse41.Insert(d, Vector128.CreateScalarUnsafe(t.ToScalar()), 0x20);
    }

    // Negative control: a memory-sourced extraction must keep the contained m32 form.
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static Vector128<float> InsertMemSrc(Vector128<float> d, Vector128<float> s)
    {
        s += Vector128.Create(1.0f);
        return Sse41.Insert(d, Vector128.CreateScalarUnsafe(s.GetElement(1)), 0x20);
    }

    public static void Main()
    {
        if (!Sse41.IsSupported) { Console.WriteLine("SSE4.1 required"); return; }

        Vector128<float> d = Vector128.Create(10f, 11f, 12f, 13f);
        Vector128<float> s = Vector128.Create(20f, 21f, 22f, 23f);

        Console.WriteLine($"regSrc         ={InsertRegSrc(d, s)}");
        Console.WriteLine($"regDirect      ={InsertRegSrcDirect(d, s)}");
        Console.WriteLine($"regLane3       ={InsertRegSrcLane3(d, s)}");
        Console.WriteLine($"regWithElement ={InsertRegSrcWithElement(d, s)}");
        Console.WriteLine($"regLane0       ={InsertRegSrcLane0(d, s)}");
        Console.WriteLine($"memSrc         ={InsertMemSrc(d, s)}");
    }
}

Run with DOTNET_TieredCompilation=0 DOTNET_JitDisasm=InsertRegSrc*.

Current codegen

InsertRegSrc, x64 + VEX (DOTNET_EnableAVX512=0), 35 bytes:

vmovups   xmm0, xmmword ptr [rdx]
vmovups   xmm1, xmmword ptr [r8]
vaddps    xmm1, xmm1, [reloc @RWD00]
vmovshdup xmm1, xmm1                  ; lane 1 -> lane 0, only so that count_s can stay 0
vinsertps xmm0, xmm0, xmm1, 32        ; count_s=0, count_d=2
vmovups   xmmword ptr [rcx], xmm0
mov       rax, rcx
ret

InsertRegSrcLane3 emits a vshufps in the same position (36 bytes).

Expected codegen

31 bytes — identical to the hand-written InsertRegSrcDirect counterfactual:

vmovups   xmm0, xmmword ptr [rdx]
vmovups   xmm1, xmmword ptr [r8]
vaddps    xmm1, xmm1, [reloc @RWD00]
vinsertps xmm0, xmm0, xmm1, 96        ; count_s=1, count_d=2
vmovups   xmmword ptr [rcx], xmm0
mov       rax, rcx
ret

InsertRegSrcLane3 becomes vinsertps xmm0, xmm0, xmm1, 0xD0 (count_s=3, count_d=1), 31 bytes.

Impact

Target methods, measured with a prototype (see below) on Windows x64, FullOpts, DOTNET_TieredCompilation=0:

Method Base Prototype Delta
InsertRegSrc (src lane 1 → dst 2) 35 31 −4 B
InsertRegSrcLane3 (src lane 3 → dst 1) 36 31 −5 B
InsertRegSrcWithElement (WithElement(2, GetElement(1))) 35 31 −4 B
InsertRegSrcLane0 (control) 31 31 0
InsertRegSrcDirect (counterfactual) 31 31 0
InsertMemSrc (negative control, contained m32) 37 37 0

The win is not EVEX-dependent: with EVEX enabled the same three methods go 37/38/37 → 33/33/33, and the controls are unchanged.

SuperPMI asmdiffs, x64 Release, default 12 collections, 2,787,662 successful base compiles, 0 failing and 0 new missing contexts:

Collection (windows.x64) Contexts with diffs Code size
benchmarks.run.checked 1 −27
benchmarks.run_pgo_optrepeat.checked 1 −27
coreclr_tests.run.checked 4 −128
libraries.crossgen2.checked 6 −52
libraries_tests_no_tiered_compilation.run.Release 10 −99
realworld.run.checked 8 −351
Total 32 −684

30 methods improved, 0 regressed, 2 byte-identical (both of the byte-identical ones have SHA256-identical base/diff disassembly and come from a collection that replayed slightly nondeterministically; they are not a codegen change). Over the 32 differing methods: 55,691 → 55,007 bytes, −1.23%. Largest single win is BepuPhysics.CollisionDetection.MeshReduction:ReduceManifolds at −255 bytes, where the fold also removes redundant EVEX vmovaps copies:

-  vmovshdup xmm17, xmm0                   +  vinsertps xmm16, xmm16, xmm0, 80
-  vinsertps xmm16, xmm16, xmm17, 16
-  vmovaps   xmm16, xmm0                   +  vinsertps xmm5, xmm5, xmm0, 16
-  vinsertps xmm5, xmm5, xmm16, 16

SuperPMI tpdiff reported 0.00% of base for all 12 collections (absolute deltas −533K to +1.68M retired instructions against 10^10–10^12 baselines — i.e. below the noise floor, not a signed win).

Measurement limitations:

  • No PerfScore data. Both the base and prototype JITs were Release builds, which do not record PerfScore; every collection reported Diffed PerfScore: 0.0 / Relative PerfScore Geomean: 1.0000 for base and diff. This is a reporting gap, not a measured neutral result.
  • No microbenchmark was run. The claim is instruction/code-size removal. The removed shuffle is a real port-5 µop on the producer→insertps dependency chain, but no execution-speed number was measured.
  • Corpus reach is narrow: 32 of 2,787,662 contexts (~0.001%), so the whole-corpus effect is negligible in aggregate even though it is 1.23% on the methods it touches.

Notes

  • Scope: x64/x86 only (lowerxarch.cpp); Arm64 is untouched. Only TYP_FLOAT NI_X86Base_Insert reaches this code — any other simdBaseType bails out earlier, so integral PINSRB/W/D/Q immediate semantics are not involved. INSERTPS already requires SSE4.1; no new ISA requirement.
  • Correctness argument: INSERTPS imm8 is [7:6]=count_s, [5:4]=count_d, [3:0]=zmask. The current shape reads lane 0 of a vector whose lane 0 was defined to be src[N]; the folded shape reads lane N of src directly. count_d and zmask are copied unchanged and only count_s is rewritten. The upper lanes of the removed extraction result are unspecified by contract and never read, which is why the rewrite is legal. INSERTPS is a pure data move: it raises no FP exception and does not canonicalize NaNs, so no FP semantics are added or removed.
  • Every pre-existing guard should be reused verbatim: 4-byte element size, NI_Vector_ToScalar / constant-index NI_Vector_GetElement only, 0 <= count_s <= 3, !srcVec->isContained(), and IsInvariantInRange(srcVec, node). The isContained guard is what preserves the already-optimal insertps xmm, m32 form (confirmed by the InsertMemSrc negative control at 37 → 37 bytes, same instruction).
  • Validated behaviorally: program stdout is byte-identical between base and prototype in both ISA configurations, and a 32-case matrix (source lane 0-3 × destination lane 0-3 × zmask ∈ {0x0, 0x5}) checked against a scalar managed reference implementation of INSERTPS reports zero mismatches under both JITs and both configurations.
  • Remaining risks: (1) both JITs were Release builds, so JIT/LIR asserts around the BlockRange().Remove calls were never exercised — a Checked-build SuperPMI replay should be run before merging; (2) zmask was enumerated at 0x0 and 0x5 only, not all 16 values; (3) Vector256/Vector512 sources reaching this fold through the GetLower/ExtractVector128 narrowing path were exercised only indirectly via the corpus, not by a dedicated repro; (4) the containment guard assumes srcVec->isContained() is already final when the Insert is lowered (true because operands lower first, but an ordering assumption rather than a structural invariant); (5) validated on Windows x64 only — Linux x64 and x86 were not run, though the code path is architecture-shared within lowerxarch.cpp.

Prototype patch

Experimental patch
diff --git a/src/coreclr/jit/lowerxarch.cpp b/src/coreclr/jit/lowerxarch.cpp
index 7fbed52a6d1..568a1ddf977 100644
--- a/src/coreclr/jit/lowerxarch.cpp
+++ b/src/coreclr/jit/lowerxarch.cpp
@@ -2233,11 +2233,17 @@ GenTree* Lowering::LowerHWIntrinsic(GenTreeHWIntrinsic* node)
             // or uint) and for a source vector of any width, provided the element being
             // extracted is one of the first four. That is all count_s can encode and all
             // that resides in the low 128 bits, which is the only part insertps reads.
+            //
+            // A floating-point CreateScalarUnsafe is removed earlier in lowering when its
+            // user is another HW intrinsic, which happens for every Insert that reaches
+            // here. We therefore have to recognize the bare extraction as well, otherwise
+            // only the already free source index zero shape is ever folded.
 
-            if ((count_s == 0) && op2->OperIsHWIntrinsic(NI_Vector_CreateScalarUnsafe))
+            if ((count_s == 0) && op2->OperIsHWIntrinsic())
             {
-                GenTreeHWIntrinsic* createScalar = op2->AsHWIntrinsic();
-                GenTree*            scalarOp     = createScalar->Op(1);
+                GenTreeHWIntrinsic* createScalar =
+                    op2->OperIsHWIntrinsic(NI_Vector_CreateScalarUnsafe) ? op2->AsHWIntrinsic() : nullptr;
+                GenTree* scalarOp = (createScalar != nullptr) ? createScalar->Op(1) : op2;
 
                 if (scalarOp->OperIsHWIntrinsic() && (genTypeSize(scalarOp->AsHWIntrinsic()->GetSimdBaseType()) == 4))
                 {
@@ -2289,7 +2295,11 @@ GenTree* Lowering::LowerHWIntrinsic(GenTreeHWIntrinsic* node)
                         }
 
                         BlockRange().Remove(extract);
-                        BlockRange().Remove(createScalar);
+
+                        if (createScalar != nullptr)
+                        {
+                            BlockRange().Remove(createScalar);
+                        }
                     }
                 }
             }

Note

This issue was generated with GitHub Copilot.

Activity

  1. added
    area-CodeGen-coreclr
    on Sep 30, 2026
  2. added
    untriaged
    on Sep 30, 2026
  3. dotnet-policy-service commented on Sep 30, 2026

    @dotnet-policy-service
    Contributor

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

  4. MihuBot commented on Sep 30, 2026

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  5. added this to the 12.0.0 milestone on Oct 2, 2026
  6. removed
    untriaged
    on Oct 2, 2026
  7. JulieLeeMSFT commented on Oct 2, 2026

    @JulieLeeMSFT
    Member
  8. added a commit that references this issue on Oct 12, 2026
    523a36f
  9. locked and limited conversation to collaborators on Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

area-CodeGen-coreclrperformance

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions