]> git.sesse.net Git - stockfish/commitdiff
Help GCC to optimize msb() to single instruction
authorAndrey Neporada <neporada@gmail.com>
Sat, 3 Dec 2016 08:37:07 +0000 (12:37 +0400)
committerMarco Costalba <mcostalba@users.noreply.github.com>
Sat, 3 Dec 2016 08:37:07 +0000 (09:37 +0100)
GCC compiles builtin_clzll to “63 ^ BSR”. BSR is processor instruction "Bit Scan Reverse".
So old msb() function is basically 63 - 63 ^ BSR.
Unfortunately, GCC fails to simplify this expression.

Old function compiles to

    bsrq    %rdi, %rdi
    movl    $63, %eax
    xorq    $63, %rdi
    subl    %edi, %eax
    ret

New function compiles to

    bsrq    %rdi, %rax
    ret

BTW, Clang compiles both function to the same (optimal) code.

No functional change.

src/bitboard.h

index 715f6c4af485bf8bb7f1313601cb6710024ae0f2..f41abeb28c0013ece24cb98a08dd700c1fd0a98c 100644 (file)
@@ -291,7 +291,7 @@ inline Square lsb(Bitboard b) {
 
 inline Square msb(Bitboard b) {
   assert(b);
 
 inline Square msb(Bitboard b) {
   assert(b);
-  return Square(63 - __builtin_clzll(b));
+  return Square(63 ^ __builtin_clzll(b));
 }
 
 #elif defined(_WIN64) && defined(_MSC_VER)
 }
 
 #elif defined(_WIN64) && defined(_MSC_VER)