dotnet/runtime

JIT: Simplify arithmetic operations on memory, as is already done for register

Open

#125300 opened on Mar 8, 2026

View on GitHub
 (1 comment) (0 reactions) (0 assignees)C# (17,886 stars) (5,445 forks)batch import
area-CodeGen-coreclrhelp wantedoptimization

Description

I expected the reg and mem variant to have same codegen, https://godbolt.org/z/MGzTd3s3c JitOptRepeat seems to help a little for SubMem only.

static int AddReg(int mem)
{
    int a = mem;
    int b = mem;
    int c = mem;
    int r = a + b + c;
    return r;
}

static int AddMem(ref int mem)
{
    int a = mem;
    int b = mem;
    int c = mem;
    int r = a + b + c;
    return r;
}

static int SubReg(int mem)
{
    int a = mem;
    int b = mem;
    int c = mem;
    int r = a - b - c;
    return r;
}

static int SubMem(ref int mem)
{
    int a = mem;
    int b = mem;
    int c = mem;
    int r = a - b - c;
    return r;
}
Program:AddReg(int):int (FullOpts):
       lea      eax, [rdi+2*rdi]
       ret      

Program:AddMem(byref):int (FullOpts):
       mov      eax, dword ptr [rdi]
       lea      ecx, [rax+rax]
       add      eax, ecx
       ret      

Program:SubReg(int):int (FullOpts):
       xor      eax, eax
       sub      eax, edi
       ret      

Program:SubMem(byref):int (FullOpts):
       mov      eax, dword ptr [rdi]
       mov      ecx, eax
       sub      ecx, eax
       sub      ecx, eax
       mov      eax, ecx
       ret      

Contributor guide