llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[x86] bitReverse of a byte or half-word can probably be optimized

Open Validark opened this issue 2 years ago • 12 comments

Godbolt link

const std = @import("std");

inline fn pext(src: u64, mask: u64) u64 {
    return asm ("pext %[mask], %[src], %[ret]"
        : [ret] "=r" (-> u64),
        : [src] "r" (src),
          [mask] "r" (mask),
    );
}

const T = u8;

export fn byteReverseDefault(x: T) u64 {
    return @bitReverse(x);
}

export fn byteReversePext(x: u8) u64 {
    return pext(@as(u64, x) * 0x0101010101010101, @as(u64, @bitCast(@as(@Vector(8, u8), @splat(1)) << ~std.simd.iota(u3, 8))));
}

export fn byteReverseVector(x: T) T {
    const vec = @as(@Vector(@bitSizeOf(T), T), @splat(x));
    const mask = @as(@Vector(@bitSizeOf(T), T), @splat(1)) << ~std.simd.iota(std.math.Log2Int(T), @bitSizeOf(T));
    return @bitCast((vec & mask) == mask);
}
byteReverseDefault:
        rol     dil, 4
        mov     eax, edi
        shr     dil, 2
        and     al, 51
        and     dil, 51
        shl     al, 2
        or      dil, al
        mov     eax, edi
        shr     dil
        and     al, 85
        and     dil, 85
        add     al, al
        or      dil, al
        movzx   eax, dil
        ret

byteReversePext:
        movabs  rcx, 72340172838076673
        mov     eax, edi
        imul    rcx, rax
        movabs  rax, 72624976668147840
        pext    rax, rcx, rax
        ret

.LCPI2_0:
        .byte   128
        .byte   64
        .byte   32
        .byte   16
        .byte   8
        .byte   4
        .byte   2
        .byte   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
byteReverseVector: ; the compiler will not give you this emit in godbolt
        vpbroadcastq    xmm1, qword ptr [rip + .LCPI2_0]
        vmovd   xmm0, edi
        vpbroadcastb    xmm0, xmm0
        vpand   xmm0, xmm0, xmm1
        vpcmpeqb        xmm0, xmm0, xmm1
        vpmovmskb       eax, xmm0
        ret

Validark avatar Jan 29 '24 08:01 Validark

define dso_local i64 @byteReverseDefault(i8 zeroext %0) local_unnamed_addr {
Entry:
  %1 = tail call i8 @llvm.bitreverse.i8(i8 %0)
  %2 = zext i8 %1 to i64
  ret i64 %2
}
declare i8 @llvm.bitreverse.i8(i8) #1

define dso_local i64 @byteReversePext(i8 zeroext %0) local_unnamed_addr {
Entry:
  %1 = zext i8 %0 to i64
  %2 = mul nuw i64 %1, 72340172838076673
  %3 = tail call i64 asm "pext ${2}, ${1}, ${0}", "=r,r,r,~{dirflag},~{fpsr},~{flags}"(i64 %2, i64 72624976668147840) #4
  ret i64 %3
}

define dso_local zeroext i8 @byteReverseVector(i8 zeroext %0) local_unnamed_addr {
Entry:
  %1 = insertelement <1 x i8> poison, i8 %0, i64 0
  %2 = shufflevector <1 x i8> %1, <1 x i8> poison, <8 x i32> zeroinitializer
  %3 = and <8 x i8> %2, <i8 -128, i8 64, i8 32, i8 16, i8 8, i8 4, i8 2, i8 1>
  %4 = icmp ne <8 x i8> %3, zeroinitializer
  %5 = bitcast <8 x i1> %4 to i8
  ret i8 %5
}

RKSimon avatar Jan 29 '24 10:01 RKSimon

@llvm/issue-subscribers-backend-x86

Author: Niles Salter (Validark)

[Godbolt link](https://zig.godbolt.org/z/f6PTsr3nj)
const std = @<!-- -->import("std");

inline fn pext(src: u64, mask: u64) u64 {
    return asm ("pext %[mask], %[src], %[ret]"
        : [ret] "=r" (-&gt; u64),
        : [src] "r" (src),
          [mask] "r" (mask),
    );
}

const T = u8;

export fn byteReverseDefault(x: T) u64 {
    return @<!-- -->bitReverse(x);
}

export fn byteReversePext(x: u8) u64 {
    return pext(@<!-- -->as(u64, x) * 0x0101010101010101, @<!-- -->as(u64, @<!-- -->bitCast(@<!-- -->as(@<!-- -->Vector(8, u8), @<!-- -->splat(1)) &lt;&lt; ~std.simd.iota(u3, 8))));
}

export fn byteReverseVector(x: T) T {
    const vec = @<!-- -->as(@<!-- -->Vector(@<!-- -->bitSizeOf(T), T), @<!-- -->splat(x));
    const mask = @<!-- -->as(@<!-- -->Vector(@<!-- -->bitSizeOf(T), T), @<!-- -->splat(1)) &lt;&lt; ~std.simd.iota(std.math.Log2Int(T), @<!-- -->bitSizeOf(T));
    return @<!-- -->bitCast((vec &amp; mask) == mask);
}
byteReverseDefault:
        rol     dil, 4
        mov     eax, edi
        shr     dil, 2
        and     al, 51
        and     dil, 51
        shl     al, 2
        or      dil, al
        mov     eax, edi
        shr     dil
        and     al, 85
        and     dil, 85
        add     al, al
        or      dil, al
        movzx   eax, dil
        ret

byteReversePext:
        movabs  rcx, 72340172838076673
        mov     eax, edi
        imul    rcx, rax
        movabs  rax, 72624976668147840
        pext    rax, rcx, rax
        ret

.LCPI2_0:
        .byte   128
        .byte   64
        .byte   32
        .byte   16
        .byte   8
        .byte   4
        .byte   2
        .byte   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
        .zero   1
byteReverseVector: ; the compiler will not give you this emit in godbolt
        vpbroadcastq    xmm1, qword ptr [rip + .LCPI2_0]
        vmovd   xmm0, edi
        vpbroadcastb    xmm0, xmm0
        vpand   xmm0, xmm0, xmm1
        vpcmpeqb        xmm0, xmm0, xmm1
        vpmovmskb       eax, xmm0
        ret

llvmbot avatar Jan 29 '24 10:01 llvmbot

Is this not a duplicate of #31158? Seems like quite a lot of measurements have been performed there.

GnomedDev avatar May 16 '24 23:05 GnomedDev

Is this not a duplicate of #31158? Seems like quite a lot of measurements have been performed there.

I don't see that anyone else realized it could be done with a multiply + pext?

Validark avatar May 17 '24 03:05 Validark

It doesn't discuss the PMOVMSKB/PTESTM trick either.

RKSimon avatar May 17 '24 06:05 RKSimon

It doesn't discuss the PMOVMSKB/PTESTM trick either.

Guess I'm just too cool for school 😎

Validark avatar May 17 '24 12:05 Validark

I was looking into this and it seems like it is faster to broadcast it to the MSB using a multiply:

bitReverse8_mulmovmsk:
        mov     eax, edi
        movabs  rcx, -9205322385119247871
        imul    rcx, rax
        movq    xmm0, rcx
        pmovmskb        eax, xmm0
        ret

Its SSE2 compatible, as it avoids using vpbroadcastb. Seems competitive for 16-bit as well:

bitReverse16_mulmovmsk:
        movzx   eax, dil
        movabs  rcx, -9205322385119247871
        imul    rax, rcx
        shr     edi, 8
        imul    rdi, rcx
        movq    xmm0, rdi
        movq    xmm1, rax
        punpcklqdq      xmm0, xmm1
        pmovmskb        eax, xmm0
        ret

https://godbolt.org/z/3GKh96qsc

WalterKruger avatar Jan 29 '26 06:01 WalterKruger

I was looking into this and it seems like it is faster to broadcast it to the MSB using a multiply:

bitReverse8_mulmovmsk: mov eax, edi movabs rcx, -9205322385119247871 imul rcx, rax movq xmm0, rcx pmovmskb eax, xmm0 ret

Is this better then using pext?

byteReversePext:
        movabs  rcx, 72340172838076673
        mov     eax, edi
        imul    rcx, rax
        movabs  rax, 72624976668147840
        pext    rax, rcx, rax
        ret

I would think staying in GPR's would be more efficient, at least for machines that natively support pext. On AMD machines before Zen 3, however, you definitely want to avoid pext.

Its SSE2 compatible, as it avoids using vpbroadcastb. Seems competitive for 16-bit as well:

bitReverse16_mulmovmsk: movzx eax, dil movabs rcx, -9205322385119247871 imul rax, rcx shr edi, 8 imul rdi, rcx movq xmm0, rdi movq xmm1, rax punpcklqdq xmm0, xmm1 pmovmskb eax, xmm0 ret https://godbolt.org/z/3GKh96qsc

That's a great idea!

Validark avatar Jan 29 '26 19:01 Validark

Is this better then using pext? I would think staying in GPR's would be more efficient...

It seems strange to me as well. But I ran a micro-benchmark of just doing bit reverses in a loop on my Zen4 machine and the movmsk version was about 30% faster. This correlates to llvm-mca, which claims pext is about as fast on a base-line CPU, but on Zen4 it says it should be decently faster:

  • pext: Total Cycles: 259
  • mulmovmsk: Total Cycles: 133

WalterKruger avatar Jan 30 '26 00:01 WalterKruger

It seems strange to me as well. But I ran a micro-benchmark of just doing bit reverses in a loop on my Zen4 machine and the movmsk version was about 30% faster. This correlates to llvm-mca, which claims pext is about as fast on a base-line CPU, but on Zen4 it says it should be decently faster:

  • pext: Total Cycles: 259
  • mulmovmsk: Total Cycles: 133

What machine did you test on?

Validark avatar Feb 14 '26 11:02 Validark

On intel targets, pext is on the same pipe as imul, so I wonder if you're getting pipe bound in a tight loop?

RKSimon avatar Mar 19 '26 19:03 RKSimon

Interesting Zen 5 context from https://www.numberworld.org/blogs/2024_8_7_zen5_avx512_teardown/

Update August 16th: The official Zen5 optimization manual claims that PDEP/PEXT do not share ports with IMUL/CRC. So 3 of the ALUs can do IMUL/CRC while the other 3 can do PDEP/PEXT. While retesting this, it took considerable effort to exceed 3 IPC by mixing IMUL and PEXT (maxing out at 3.5 IPC). In my initial tests months, I never exceeded 3 IPC and thus (incorrectly) assumed that all of these instructions shared the same 3 ports. When in reality, they do not share ports, but a different (unknown) bottleneck made it appear as though they shared ports.

Validark avatar Mar 29 '26 22:03 Validark