Skip to content

JIT: Suboptimal codegen for simple CONST - VAR #126442

Open

Description

@BoyBaykiller

https://godbolt.org/z/x3e349nEW

uint ConstSubVar(uint x)
{
    return 32 - x;
}
Program:ConstSubVar(uint):uint:this (FullOpts):
       mov      eax, esi
       neg      eax
       add      eax, 32
       ret 

Should be:

Program:ConstSubVar(uint):uint:this (FullOpts):
       mov      eax, 32
       sub      eax, esi
       ret      

We canonicalize into (cns1 + (-op2)) in morph:

/* Check for "cns1 - op2" , we change it to "(cns1 + (-op2))" */
noway_assert(op1);
if (op1->IsCnsIntOrI())
{
noway_assert(varTypeIsIntegralOrI(tree));
// The type of the new GT_NEG node cannot just be op2->TypeGet().
// Otherwise we may sign-extend incorrectly in cases where the GT_NEG
// node ends up feeding directly into a cast, for example in
// GT_CAST<ubyte>(GT_SUB(0, s_1.ubyte))
if (op1->IsIntegralConst(0))
{
tree->ChangeOper(GT_NEG);
tree->gtType = genActualType(op2->TypeGet());
tree->AsOp()->gtOp1 = op2;
tree->AsOp()->gtOp2 = nullptr;
DEBUG_DESTROY_NODE(op1);
return tree;
}
tree->AsOp()->gtOp2 = op2 = gtNewOperNode(GT_NEG, genActualType(op2->TypeGet()), op2);
fgMorphTreeDone(op2);
oper = GT_ADD;
tree->ChangeOper(oper);
goto CM_ADD_OP;
}

Activity

  1. added
    untriaged
    on Apr 2, 2026
  2. added
    area-CodeGen-coreclr
    on Apr 2, 2026
  3. dotnet-policy-service commented on Apr 2, 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. BoyBaykiller commented on Apr 2, 2026

    @BoyBaykiller
    ContributorAuthor

    I could work on this. Where would be a good place to turn the canonicalized form back into just the subtract (assuming thats the correct solution). Maybe in Lowering::LowerAdd?

  5. EgorBo commented on Apr 2, 2026

    @EgorBo
    Member

    Maybe in Lowering::LowerAdd?

    I think so

  6. removed
    untriaged
    on Apr 2, 2026
  7. added this to the Future milestone on Apr 2, 2026
  8. BoyBaykiller commented on Apr 3, 2026

    @BoyBaykiller
    ContributorAuthor

    I added this transformation in LowerAdd:

    if (op1->OperIs(GT_NEG) && op2->IsIntegralConst())
    {
        node->ChangeOper(GT_SUB, GenTree::ValueNumberUpdate::PRESERVE_VN);
        node->gtOp1 = op2;
        node->gtOp2 = op1->gtGetOp1();
    
        BlockRange().Remove(op1);
        ContainCheckBinary(node);
    
        return node->gtNext;
    }

    Unfortunately, the diffs are a net size increase: https://gist.github.com/BoyBaykiller/eae58ed0fd4221d42d120472d28bf045.

    The main issue is that we tend to need an extra mov to place the subtract result into the destination register. Meanwhile the neg+add chain can do it in place:

    -       neg      eax
    -       add      eax, 63
    -						;; size=20 bbWeight=0.50 PerfScore 2.50
    +       mov      r8d, 63
    +       sub      r8d, eax
    +       mov      eax, r8d
    +						;; size=27 bbWeight=0.50 PerfScore 2.62

    On the other hand in cases where previously a mov was done we can now do that with the subtract:

    -       mov      rcx, rsi
    -       neg      rcx
    -       add      rcx, 0xD1FFAB1E
    -						;; size=32 bbWeight=4 PerfScore 13.00
    +       mov      ecx, 0xD1FFAB1E
    +       sub      rcx, rsi
    +						;; size=27 bbWeight=4 PerfScore 12.00

    I need register allocation info in order to make optimal decission and avoid regressions. So I need to move this to some later phase, do you know where?

  9. tannergooding commented on Apr 3, 2026

    @tannergooding
    Member

    There isn't really a later phase. We have:

    • Lower - sets up basic preferencing info for register allocation
    • LSRA - does the actual register allocation
    • Codegen - generates the instructions using the selected registers

    This is likely one of those cases that simply don't matter and where trying to micro-optimize out a mov instruction or a neg; add in favor of a sub isn't worth the extra complexity for the case where the non-constant is already in the register you want the result to be in. There may be a small subset of cases where you can peephole the optimization, but even that is probably questionable overall and will go away with APX and the non-RMW forms of instructions

  10. BoyBaykiller commented on Apr 3, 2026

    @BoyBaykiller
    ContributorAuthor

    Hm ok. I was looking at how clang handles this. It doesn't seem to canonicalize into add+neg form (https://godbolt.org/z/Kbr54r3zj). But how does it avoid the extra mov then? - Through better register alloc.

    For example here we have a regression:

    unsigned SubTest(unsigned x)
    {
        unsigned y = ((x >> 1) & 0x55555555u) | x;
    
        return 31 - y;
    }
            mov      eax, ecx
            shr      eax, 1
            and      eax, 0x55555555
            or       eax, ecx
    -       neg      eax
    -       add      eax, 31
    +       mov      ecx, 31
    +       sub      ecx, eax
    +       mov      eax, ecx
    -						;; size=16 bbWeight=1 PerfScore 1.75
    +						;; size=20 bbWeight=1 PerfScore 2.00

    Because we place y into eax, at the time when the sub comes we have to put the constant 31 into a different register and then mov the result into eax again. Meanwhile clang stores y into ecx and then copies into eax as part of sub:

            mov     ecx, edi
            shr     ecx
            mov     eax, 31
            and     ecx, 1431655765
            or      ecx, edi
            sub     eax, ecx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclr

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions