From 4fffc0754486d780db4d7decbe1c7b5c6f05587e Mon Sep 17 00:00:00 2001 From: Andy Ayers Date: Wed, 2 Dec 2026 17:11:40 -0800 Subject: [PATCH] JIT: use shorter add/sub constant encodings on Wasm When negating an add or sub constant encodes it in fewer bytes (e.g. 64), emit the opposite operation with the negated constant. Do the same in the crossgen2 Wasm thunk and stub generators, which also no longer add a zero offset. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: bfdc6001-97e4-4f7a-9de1-f9a04223c8ff --- src/coreclr/jit/emitwasm.cpp | 54 +++++++++++++++++++ .../Compiler/ObjectWriter/WasmInstructions.cs | 34 ++++++++++++ .../Target_Wasm/WasmUnboxingStubNode.cs | 3 +- .../ReadyToRun/WasmImportThunk.cs | 20 +++---- .../WasmInterpreterToR2RThunkNode.cs | 6 +-- .../WasmR2RToInterpreterThunkNode.cs | 23 +++----- .../ReadyToRun/WasmUnboxingStubNode.cs | 9 ++-- 7 files changed, 108 insertions(+), 41 deletions(-) diff --git a/src/coreclr/jit/emitwasm.cpp b/src/coreclr/jit/emitwasm.cpp index bd5035cbdaebc3..a900cbc5ae5094 100644 --- a/src/coreclr/jit/emitwasm.cpp +++ b/src/coreclr/jit/emitwasm.cpp @@ -58,6 +58,60 @@ bool emitter::isValidVectorIndex(uint8_t elemSize, uint8_t index) void emitter::emitIns(instruction ins) { + // "x + c" or "x - c" encodes shorter as "x - (-c)" or "x + (-c)" when -c needs fewer SLEB128 bytes than c + // (e.g. c == 64). That only happens for some positive constants, so negating cannot overflow. + // + const bool isI32AddSub = (ins == INS_i32_add) || (ins == INS_i32_sub); + const bool isI64AddSub = (ins == INS_i64_add) || (ins == INS_i64_sub); + if ((isI32AddSub || isI64AddSub) && m_compiler->opts.OptimizationEnabled() && emitCanPeepholeLastIns() && + (emitLastIns->idIns() == (isI32AddSub ? INS_i32_const : INS_i64_const)) && !emitLastIns->idIsCnsReloc()) + { + const cnsval_ssize_t cns = emitGetInsSC(emitLastIns); + if ((cns > 0) && (SizeOfSLEB128(-cns) < SizeOfSLEB128(cns))) + { + JITDUMP("\n -- rewriting '%s %lld' as '%s %lld'.\n", + (ins == INS_i32_add || ins == INS_i64_add) ? "add" : "sub", (long long)cns, + (ins == INS_i32_add || ins == INS_i64_add) ? "sub" : "add", (long long)-cns); + + const unsigned oldSize = emitLastIns->idCodeSize(); + if (emitLastIns->idIsLargeCns()) + { + ((instrDescCns*)emitLastIns)->idcCnsVal = -cns; + } + else + { + emitLastIns->idSmallCns(-cns); + } + + const unsigned savedSize = oldSize - emitLastIns->idCodeSize(); + if (emitLastInsIG == emitCurIG) + { + emitCurIGsize -= savedSize; + } + else + { + emitLastInsIG->igSize -= static_cast(savedSize); + } + emitLastInsIG->igFlags |= IGF_UPD_ISZ; + + switch (ins) + { + case INS_i32_add: + ins = INS_i32_sub; + break; + case INS_i32_sub: + ins = INS_i32_add; + break; + case INS_i64_add: + ins = INS_i64_sub; + break; + default: + ins = INS_i64_add; + break; + } + } + } + instrDesc* id = emitNewInstrSmall(EA_8BYTE); insFormat fmt = emitInsFormat(ins); id->idIns(ins); diff --git a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs index 7bd5d813646895..0d72ffdd6341e2 100644 --- a/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs +++ b/src/coreclr/tools/Common/Compiler/ObjectWriter/WasmInstructions.cs @@ -850,6 +850,40 @@ public static WasmExpr ConstRVA(ISymbolNode symbolNode) public static WasmExpr Add => new WasmBinaryExpr(WasmExprKind.I32Add); public static WasmExpr Sub => new WasmBinaryExpr(WasmExprKind.I32Sub); + + // Adds a constant to the i32 on top of the stack. A zero is omitted, and since "x + c" is "x - (-c)", + // whichever form encodes the constant in fewer SLEB128 bytes is used (e.g. "x - (-64)" rather than "x + 64"). + public static void AddConst(List expressions, int value) + { + if (value == 0) + { + return; + } + + if ((value > 0) && (DwarfHelper.SizeOfSLEB128(-(long)value) < DwarfHelper.SizeOfSLEB128(value))) + { + expressions.Add(Const(-value)); + expressions.Add(Sub); + } + else + { + expressions.Add(Const(value)); + expressions.Add(Add); + } + } + + // Subtracts a constant from the i32 on top of the stack, with the same choices as AddConst. + public static void SubConst(List expressions, int value) + { + if (value == int.MinValue) + { + expressions.Add(Const(value)); + expressions.Add(Sub); + return; + } + + AddConst(expressions, -value); + } public static WasmExpr Eqz => new WasmUnaryExpr(WasmExprKind.I32Eqz); public static WasmExpr Ge_s => new WasmBinaryExpr(WasmExprKind.I32Ge_s); public static WasmExpr Load(ulong offset) => new WasmMemoryArgInstruction(WasmExprKind.I32Load, 4, new WasmEncodableULong(offset)); diff --git a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_Wasm/WasmUnboxingStubNode.cs b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_Wasm/WasmUnboxingStubNode.cs index 2223be9905e93d..3fb9c1ed594305 100644 --- a/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_Wasm/WasmUnboxingStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.Compiler/Compiler/DependencyAnalysis/Target_Wasm/WasmUnboxingStubNode.cs @@ -44,8 +44,7 @@ protected override void EmitCode(NodeFactory factory, ref WasmEmitter encoder, b List expressions = new List(parameterCount + 5); expressions.Add(Local.Get(0)); expressions.Add(Local.Get(1)); - expressions.Add(I32.Const(factory.Target.PointerSize)); - expressions.Add(I32.Add); + I32.AddConst(expressions, factory.Target.PointerSize); int firstArgument = 2; if (IsInstantiating) diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs index bb923739979129..c1d39182d5f2e5 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmImportThunk.cs @@ -119,12 +119,9 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr int sizeOfStoredLocals = AlignmentHelper.AlignUp(layout.SizeOfFrameArgumentArray + layout.TransitionBlock.SizeOfTransitionBlock, 16); List expressions = new List(); - // local.get 0 + // sp -= {sizeOfStoredLocals} expressions.Add(Local.Get(0)); - // i32.const {sizeOfStoredLocals} - expressions.Add(I32.Const(sizeOfStoredLocals)); - // i32.sub - expressions.Add(I32.Sub); + I32.SubConst(expressions, sizeOfStoredLocals); // local.set 0 expressions.Add(Local.Set(0)); @@ -137,8 +134,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // Store the original caller's frame pointer (SP before allocation) at offset 4 expressions.Add(Local.Get(0)); expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(sizeOfStoredLocals)); - expressions.Add(I32.Add); + I32.AddConst(expressions, sizeOfStoredLocals); expressions.Add(I32.Store(4)); // Stash the arguments in the transition block @@ -156,8 +152,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // memory.fill: (dst, val, len) -> () expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(arg.Offset)); - expressions.Add(I32.Add); + I32.AddConst(expressions, arg.Offset); expressions.Add(I32.Const(0)); expressions.Add(I32.Const(fillSize)); expressions.Add(Memory.Fill()); @@ -196,12 +191,9 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr expressions.Add(Local.Set(portableEntrypointLocalIndex)); // // ;Setup sp arg for the final call, with the call address now coming from the portable entrypoint - // local.get 0 + // sp + {sizeofstoredlocals} expressions.Add(Local.Get(0)); - // i32.const {sizeofstoredlocals} - expressions.Add(I32.Const(sizeOfStoredLocals)); - // i32.add - expressions.Add(I32.Add); + I32.AddConst(expressions, sizeOfStoredLocals); // Reload the arguments for the final call foreach (WasmThunkArg arg in layout.Args) diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs index 911eb13d444db2..e3250493c2e4d6 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmInterpreterToR2RThunkNode.cs @@ -111,8 +111,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // Allocate frame space: sp -= FrameSize expressions.Add(Local.Get(localSavedSp)); - expressions.Add(I32.Const(FrameSize)); - expressions.Add(I32.Sub); + I32.SubConst(expressions, FrameSize); expressions.Add(Global.Set(WebCilObjectWriter.StackPointerGlobalIndex)); // Write TERMINATE_R2R_STACK_WALK (1) into the framePointer at new SP @@ -147,8 +146,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr { // Byreference struct — pass a pointer into the incoming pArgs buffer expressions.Add(Local.Get(LocalPArgs)); - expressions.Add(I32.Const(interpOffset)); - expressions.Add(I32.Add); + I32.AddConst(expressions, interpOffset); } else { diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs index 6af1ca4f4e2f07..f8eee5ab104f25 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmR2RToInterpreterThunkNode.cs @@ -117,10 +117,9 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr List expressions = new List(); - // Allocate stack space: local.get 0; i32.const totalAlloc; i32.sub; local.set 0 + // Allocate stack space: sp -= totalAlloc expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(totalAlloc)); - expressions.Add(I32.Sub); + I32.SubConst(expressions, totalAlloc); expressions.Add(Local.Set(0)); // Initialize TransitionBlock: @@ -132,8 +131,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // Second 4 bytes (m_StackPointer) = original SP (local 0 + totalAlloc) expressions.Add(Local.Get(0)); expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(totalAlloc)); - expressions.Add(I32.Add); + I32.AddConst(expressions, totalAlloc); expressions.Add(I32.Store((ulong)(transitionBlockOffset + 4))); // Store all arguments into the transition block area @@ -162,8 +160,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // memory.copy: (dst, src, len) -> () // dst: base + currentOffset expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(currentOffset)); - expressions.Add(I32.Add); + I32.AddConst(expressions, currentOffset); // src: the byref pointer passed as the wasm local expressions.Add(Local.Get(arg.WasmParamIndex)); // len: struct size @@ -177,8 +174,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr { // memory.fill: (dst, val, len) -> () expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(currentOffset + structSize)); - expressions.Add(I32.Add); + I32.AddConst(expressions, currentOffset + structSize); expressions.Add(I32.Const(0)); expressions.Add(I32.Const(padding)); expressions.Add(Memory.Fill()); @@ -207,8 +203,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr else { expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(localRetBufOffset)); - expressions.Add(I32.Add); + I32.AddConst(expressions, localRetBufOffset); expressions.Add(I32.Const(0)); expressions.Add(I32.Const(retBufSize)); expressions.Add(Memory.Fill()); @@ -220,8 +215,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr // arg2: pointer to the collected arguments and transition block (base + transitionBlockOffset) expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(transitionBlockOffset)); - expressions.Add(I32.Add); + I32.AddConst(expressions, transitionBlockOffset); // arg3: size of arguments (excluding transition block) expressions.Add(I32.Const(sizeOfArgumentArray)); @@ -236,8 +230,7 @@ protected override void EmitCode(NodeFactory factory, ref Wasm.WasmEmitter instr { // Pass pointer to local 8-byte return buffer expressions.Add(Local.Get(0)); - expressions.Add(I32.Const(localRetBufOffset)); - expressions.Add(I32.Add); + I32.AddConst(expressions, localRetBufOffset); } // Extra local to save/restore the stack pointer global across the helper call diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs index b74fb61fbe5a94..0c2c4bee1c790c 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRun/WasmUnboxingStubNode.cs @@ -107,8 +107,7 @@ protected override void EmitCode(NodeFactory factory, ref WasmEmitter instructio // The target PEP is stored immediately before this stub's PEP. expressions.Add(Local.Get(portableEntryPointIndex)); - expressions.Add(I32.Const(factory.Target.PointerSize)); - expressions.Add(I32.Sub); + I32.SubConst(expressions, factory.Target.PointerSize); expressions.Add(I32.Load(0)); expressions.Add(Local.Set(targetEntryPointLocalIndex)); @@ -138,8 +137,7 @@ private void AppendTargetCall( // Skip the MethodTable pointer at the start of the boxed object. expressions.Add(Local.Get(1)); - expressions.Add(I32.Const(pointerSize)); - expressions.Add(I32.Add); + I32.AddConst(expressions, pointerSize); int firstExplicitArgumentIndex = 2; if (hasReturnBuffer) @@ -157,8 +155,7 @@ private void AppendTargetCall( { // The target MethodDesc is stored two pointer-sized fields before this stub's PEP. expressions.Add(Local.Get(portableEntryPointIndex)); - expressions.Add(I32.Const(2 * pointerSize)); - expressions.Add(I32.Sub); + I32.SubConst(expressions, 2 * pointerSize); expressions.Add(I32.Load(0)); }