Skip to content

Unnecessary sign-extension for some never-negative expressions #119680

Open

Description

@xtqqczze
nint M1(uint mask) {
    return BitOperations.TrailingZeroCount(mask) / sizeof(ushort);
}

nint M2(uint mask) {
    return (nint)(uint.TrailingZeroCount(mask) / sizeof(ushort));
}
C:M1(uint):nint:this (FullOpts):
       xor      eax, eax
       tzcnt    eax, esi
       shr      eax, 1
       cdqe     
       ret      

C:M2(uint):nint:this (FullOpts):
       xor      eax, eax
       tzcnt    eax, esi
       shr      eax, 1
       ret    

godbolt.org

Activity

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

    @dotnet-policy-service
    Contributor

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

  4. added
    help wanted
    and removed
    untriaged
    on Sep 13, 2025
  5. added this to the Future milestone on Sep 13, 2025
  6. p6laris commented on Sep 27, 2026

    @p6laris

    I'd be happy to take a look at this if no one else is on it.

    If I'm reading it right, IntegralRange::ForNode doesn't handle GT_UDIV/GT_RSZ/GT_RSH. The division is still UDIV(tzcnt, 2) at morph time, so this check in fgOptimizeCast fails and the sign-extend stays:

    if (genActualTypeIsInt(src) && cast->TypeIs(TYP_LONG) && srcRange.IsNonNegative())

    I was thinking of adding those cases to ForNode, unless there's a better place for it that I'm missing.

  7. xtqqczze commented on Sep 27, 2026

    @xtqqczze
    ContributorAuthor

    Might be worth checking whether this overlaps with #132450.

  8. p6laris commented on Sep 27, 2026

    @p6laris

    Thanks for the pointer! I took a look, and I think they're separate, though I might be wrong. #132450 seems to handle cast round trips like CAST(long <- CAST(int <- X)), while here there's only a single cast over UDIV(tzcnt, 2), and ForNode doesn't seem to know that's non-negative. So I'd expect the cdqe to still be there with that change, but I'll double-check.

  9. p6laris commented on Sep 27, 2026

    @p6laris

    @xtqqczze Double-checked: with #132450 applied, M1 still emits the cdqe, so I opened #134739 for this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrhelp wanted

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions