Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Native bitshift operation #50225

Open
jakobnissen opened this issue Jun 20, 2023 · 2 comments · May be fixed by #52828
Open

Feature request: Native bitshift operation #50225

jakobnissen opened this issue Jun 20, 2023 · 2 comments · May be fixed by #52828
Labels
feature Indicates new feature / enhancement requests

Comments

@jakobnissen
Copy link
Member

The definition for Base.:>>>, Base.:>> and Base.:<< do not compile to native shift instructions, because they need to handle the case where the integer is shifted by more than the integer bitwidth:

julia> @code_native debuginfo=:none dump_module=false 1 >> 1
        .text
        pushq   %rbp
        movq    %rsp, %rbp
        cmpq    $63, %rsi
        movl    $63, %ecx
        cmovbl  %esi, %ecx
        movq    %rdi, %rdx
        sarq    %cl, %rdx
        movq    %rsi, %rcx
        negq    %rcx
        shlq    %cl, %rdi
        xorl    %eax, %eax
        cmpq    $64, %rcx
        cmovbq  %rdi, %rax
        testq   %rsi, %rsi
        cmovnsq %rdx, %rax
        popq    %rbp
        retq
        nopw    %cs:(%rax,%rax)

Often, this extra complication is not necessary, and it is possible to create a more effective bitshift operation by allowing overflow. This is completely analogous to how Base.:+ is more efficient than a saturating add, because it allows overflow:

julia> f(x, i) = x >> (i & (8*sizeof(i)-1));

julia> @code_native debuginfo=:none dump_module=false f(1, 1)
        .text
        pushq   %rbp
        movq    %rsp, %rbp
        sarxq   %rsi, %rdi, %rax
        popq    %rbp
        retq
        nopl    (%rax,%rax)

I find myself using that pattern relatively often, but this bit-twiddling trick is a little obscure, so readers may not understand what the function is doing, and may not know that this trick is available.
It would be nice if Base provided these very basic operations for users interested in high performance bit-twiddling.

@jakobnissen
Copy link
Member Author

Ref: #30674

@brenhinkeller brenhinkeller added the feature Indicates new feature / enhancement requests label Aug 4, 2023
@adienes
Copy link
Member

adienes commented Aug 4, 2023

also maybe related: #50790

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Indicates new feature / enhancement requests
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants