Skip to content

[JIT] X64 - Recognize patterns to emit bextr and bzhi #81514

Description

@TIHan
public class C 
{
    static uint bextr(uint bits)
    {
        return (bits >> 2) & 0x3u;;
    }
    
    static uint bextr_field(ref uint bits)
    {
        return (bits >> 2) & 0x3u;;
    }
    
    static uint bzhi(int position, uint bits)
    {
        return ((1u << position) - 1) & bits; // bmi2
    }
    
    static uint bzhi_field(int position, ref uint bits)
    {
        return ((1u << position) - 1) & bits; // bmi2
    }
}

Currently emits:

C.bextr(UInt32)
    mov eax, ecx
    shr eax, 2
    and eax, 3
    ret

C.bextr_field(UInt32 ByRef)
    mov eax, [rcx]
    shr eax, 2
    and eax, 3
    ret

C.bzhi(Int32, UInt32)
    mov eax, 1
    shlx eax, eax, ecx
    dec eax
    and eax, edx
    ret

C.bzhi_field(Int32, UInt32 ByRef)
    mov eax, 1
    shlx eax, eax, ecx
    dec eax
    and eax, [rdx]
    ret

Instead, it could emit:

#include <stdint.h>

uint32_t bextr(uint32_t bits)
{
    return (bits >> 2) & 0x3u;;
}

uint32_t bextr_field(uint32_t& bits)
{
    return (bits >> 2) & 0x3u;
}

uint32_t bzhi(int32_t position, uint32_t bits)
{
    return ((1 << position) - 1) & bits; // bmi2
}

uint32_t bzhi_field(int32_t position, uint32_t& bits)
{
    return ((1 << position) - 1) & bits; // bmi2
}
bextr(unsigned int):                              # @bextr(unsigned int)
        mov     eax, 514
        bextr   eax, edi, eax
        ret
bextr_field(unsigned int&):                      # @bextr_field(unsigned int&)
        mov     eax, 514
        bextr   eax, dword ptr [rdi], eax
        ret
bzhi(int, unsigned int):                              # @bzhi(int, unsigned int)
        bzhi    eax, esi, edi
        ret
bzhi_field(int, unsigned int&):                      # @bzhi_field(int, unsigned int&)
        bzhi    eax, dword ptr [rsi], edi
        ret

We already handle transformations to blsi, blsmsk, and blsr in lowering, we just need to handle bextr and bzhi in the same way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    arch-x64area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMItenet-performancePerformance related issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions