Repository navigation
Description
emitter::IsRedundantStackMov (src/coreclr/jit/emitxarch.cpp) recognizes an adjacent store/reload pair targeting the same local stack slot in the same register, but then gates the elision on !HasSideEffect(ins, size). emitter::HasSideEffect classifies every integer INS_mov with size != EA_PTRSIZE as side-effecting, because a 32-bit register destination zero-extends into the upper 32 bits.
That classification is correct for a register destination, but it is applied uniformly to both directions, so:
- For a store after a load (
IF_RWR_SRDthenIF_SWR_RRD) the current instruction writes memory and writes no register at all, so the register zero-extension side effect is categorically irrelevant — yet the elision is still blocked. - For a load after a store (
IF_SWR_RRDthenIF_RWR_SRD) atEA_4BYTE, the reload's only extra effect is zeroing bits 63:32 of the destination. When those bits are already provably zero the reload is a pure no-op — but unlike the register-to-register path inemitter::IsRedundantMov, which consultsAreUpperBitsZerofor exactly this case,IsRedundantStackMovhas no such refinement.
The result is an asymmetry that is easy to see: the same C# at 64-bit width gets the reload elided, and at 32-bit width does not.
Minimal repro
using System;
using System.Runtime.CompilerServices;
public static class Repro2
{
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Modify(ref int value) => value ^= 17;
[MethodImpl(MethodImplOptions.NoInlining)]
public static int R02_StoreReload(int x)
{
int v = x; // address-exposed, stack-homed
Modify(ref v);
v = v + 1;
return v;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static long ModifyL(ref long value)
{
value ^= 17;
return value;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static long R02_StoreReloadLong(long x)
{
long v = x; // structurally identical, 64-bit
ModifyL(ref v);
v = v + 1;
return v;
}
public static int Main()
{
Console.WriteLine("R02_StoreReload(5)={0}", R02_StoreReload(5));
Console.WriteLine("R02_StoreReload(int.MaxValue)={0}", R02_StoreReload(int.MaxValue));
Console.WriteLine("R02_StoreReloadLong(0)={0}", R02_StoreReloadLong(0));
return 100;
}
}Built net10.0, Optimize=true, run under corerun with DOTNET_TieredCompilation=0, DOTNET_ReadyToRun=0, DOTNET_JitDisasm=R02_*, Windows x64.
Current codegen
Repro2:R02_StoreReload(int):int — 38 bytes:
mov dword ptr [rsp+0x20], ecx
lea rcx, [rsp+0x20]
call [Repro2:Modify(byref)]
mov eax, dword ptr [rsp+0x20]
inc eax
mov dword ptr [rsp+0x20], eax
mov eax, dword ptr [rsp+0x20] ; <-- redundant reload: 8B 44 24 20The 64-bit counterfactual, same JIT and same run, already elides its reload:
mov rax, qword ptr [rsp+0x20]
inc rax
mov qword ptr [rsp+0x20], rax
; <-- reload elided by IsRedundantStackMovExpected codegen
Repro2:R02_StoreReload(int):int — 34 bytes:
mov eax, dword ptr [rsp+0x20]
inc eax
mov dword ptr [rsp+0x20], eaxinc eax is a 32-bit operation, so on x64 it already zeroes bits 63:32 of rax. The reload's zero-extension is therefore a no-op and removing it preserves the full 64-bit architectural value of rax, not merely its low half.
Impact
- Measured target delta (prototype patch applied, same pinned base):
R02_StoreReload(int)38 → 34 bytes (-4, -10.5%), instruction count 10 → 9, one fewer stack load, PerfScore 9.25 → 8.25. Program output is byte-identical before and after. R02_StoreReloadLong(long)and abytevariant are unchanged, as expected — thelongform was already optimal and thebyteform reloads withmovzx, which the change deliberately does not touch.- Net code-size impact: -17,878 bytes across 2,567 candidate-attributable improvements in 12 cached Windows x64 SuperPMI collections. The run compared 2,787,663 contexts where both fresh Release x64 JITs compiled successfully. There were zero attributable code-size regressions and no PerfScore changes.
The raw SuperPMI aggregate was 2,569 diffs and -17,625 bytes. Two apparent regressions
(+224 and +29 bytes) were excluded because a source-identical baseline-vs-baseline control
reproduced the same contexts and +253-byte total while reporting no textual assembly differences.
The only asymmetric misses were eight contexts in libraries_tests.run.windows.x64.Release.mch;
all missing or non-matched contexts were excluded from the matched-success total above.
SuperPMI evidence is under the candidate's superpmi directory: superpmi-summary.json,
matched-summary.json, run-manifest.json, the console/tool logs, and the source-identical
control summary and log.
Measurement limitations:
- The replay data does not distinguish the two move directions in aggregate. The targeted repro exercises load-after-store; store-after-load remains covered by corpus replay but not by a separately named micro-repro.
- The redundancy originates upstream, from address-exposed local homing. If a future front-end change removes the store/reload pair earlier, the peephole win here evaporates.
The corpus result establishes that this is a recurring sized code-size win rather than only a single-method peephole observation.
Notes
Scope and correctness assumptions for a fix:
- The existing guards should all remain: optimizations enabled,
emitCanPeepholeLastIns()(which prevents elision across labels, call sites, GC-interruptible boundaries and instruction-group breaks), noGCREF/BYREFoperand size, same instruction, same operand size, same local/offset/register. - Direction 1 (store after load) is safe on its own terms: the store writes back to memory the exact bytes that were just read from it, and writes no register. This direction is not exercised by the repro above and has not been validated empirically.
- Direction 2 (load after store) must stay narrow:
ins == INS_mov,size == EA_4BYTE, andAreUpperBitsZero(ireg, size).AreUpperBitsZeroperforms a bounded backward scan and aborts onINS_calland on sign-extending instructions; in the repro it correctly looks past the interveningmov [rsp+0x20], eax(a memory destination that does not writeeax) and finds the 32-bitinc eax. - On x86
EA_PTRSIZE == EA_4BYTE, so direction 2 must be a no-op there; the prototype guards it withTARGET_AMD64. - Do not generalize to volatile or interlocked accesses, masked/AVX forms, differing widths,
movzx/movsx,GCREF/BYREFslots, or heap address-mode forms. The local-slot descriptor form is the intended scope. - Remaining risks: unverified effect on debugger variable-location mapping for the elided slot; unmeasured compile-time cost of the additional
AreUpperBitsZeroquery; and the unmeasured corpus behavior noted above. A cleaner refactor would giveHasSideEffectan explicit "register destination" parameter rather than calling it uniformly from both directions.
Prototype patch
Experimental only — repro- and SuperPMI-validated, and not proposed as-is.
Experimental patch
diff --git a/src/coreclr/jit/emitxarch.cpp b/src/coreclr/jit/emitxarch.cpp
index b3ebd8af62e..c8ab331521e 100644
--- a/src/coreclr/jit/emitxarch.cpp
+++ b/src/coreclr/jit/emitxarch.cpp
@@ -10547,19 +10547,40 @@ bool emitter::IsRedundantStackMov(instruction ins, insFormat fmt, emitAttr size,
int varNum = emitLastIns->idAddr()->iiaLclVar.lvaVarNum();
int lastOffs = emitLastIns->idAddr()->iiaLclVar.lvaOffset();
- const bool hasSideEffect = HasSideEffect(ins, size);
-
// Check if the last instruction and current instructions use the same register and local memory.
if (varNum == varx && lastReg1 == ireg && lastOffs == offs)
{
// Check if we did a switched mov in the last instruction and don't have a side effect
- if ((((emitLastIns->idInsFmt() == IF_RWR_SRD) && (fmt == IF_SWR_RRD)) ||
- ((emitLastIns->idInsFmt() == IF_SWR_RRD) && (fmt == IF_RWR_SRD))) &&
- !hasSideEffect) // or if the format is different from the last instruction
+ if (((emitLastIns->idInsFmt() == IF_RWR_SRD) && (fmt == IF_SWR_RRD)) ||
+ ((emitLastIns->idInsFmt() == IF_SWR_RRD) && (fmt == IF_RWR_SRD)))
{
- JITDUMP("\n -- suppressing mov because last instruction already moved from dst to src and the mov has "
- "no side-effects.\n");
- return true;
+ bool hasSideEffect = HasSideEffect(ins, size);
+
+ if (hasSideEffect && (ins == INS_mov))
+ {
+ if (fmt == IF_SWR_RRD)
+ {
+ // The upper-bit side effect that HasSideEffect models only applies to a register
+ // destination. Here the destination is the stack slot we just loaded from, so the
+ // store leaves memory exactly as it already is and no register is written.
+ hasSideEffect = false;
+ }
+#ifdef TARGET_AMD64
+ else if (size == EA_4BYTE)
+ {
+ // Reloading the slot would only zero-extend the upper 32 bits of "ireg", which is a
+ // no-op when those bits are already known to be zero.
+ hasSideEffect = !AreUpperBitsZero(ireg, size);
+ }
+#endif // TARGET_AMD64
+ }
+
+ if (!hasSideEffect)
+ {
+ JITDUMP("\n -- suppressing mov because last instruction already moved from dst to src and the mov has "
+ "no side-effects.\n");
+ return true;
+ }
}
// Check if we did same move in last instruction, side effects don't matter since they already happened
if (emitLastIns->idInsFmt() == fmt)Note
This issue was generated with GitHub Copilot.
Activity
dotnet-policy-service commentedon Sep 30, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
p6laris commentedon Oct 1, 2026
Related, in the same function:
IsRedundantStackMovdoesn't look at embedded masks, and masked stores to locals reach it throughemitInsStoreInd. Today avmovups [rsp] {k1}, zmm0followed byvmovups zmm0, [rsp]loses the reload (#135004). That's in the load-after-store and same-move paths, so the store-after-load change here isn't affected. The suggestedHasSideEffectrefactor would touch the same code, though.JulieLeeMSFT commentedon Oct 2, 2026
cc @Ruihan-Yin , @dhartglassMSFT .