[haiku-gsoc] Bitwise manipulations

  • From: Ayush Agrawal <echo.27.04.96@xxxxxxxxx>
  • To: haiku-gsoc@xxxxxxxxxxxxx
  • Date: Sat, 24 Jun 2017 03:22:00 +0530

Going through the source code of TCP, I came across instances where using
small bit hacks could have helped avoid branching.

Example: use of min_c at lines 2031, 2038 etc in TCPEndpoint.cpp.

min_c is defined as: #define min_c(a,b) ((a)>(b)?(b):(a)) in SupportDefs.h
and also in fssh_defs.h.
An alternate to minimum of two number is: min = b ^ ((a^b) & -(a<b)) .

The advantage of using the latter is that it avoids any branching howsoever
which in turn is good for instruction level pipelining at the hardware
level since the risk of flushing the pipeline due to speculative branching
is eliminated.

There are other examples like:
1) line 390; source: tcp.cpp; can be replaced with something like:
              header.acknowledgement = htonl(segment.acknowledge) &
-((segment.flag & TCP_FLAG_ACKNOWLEDGE) > 0)
2) line 398; source: TCPEndpoint.cpp; can be replaced with:
              return now + (UINT_MAX & -(now <= base)) - base)  ... may be
not the best solution but something on the same line

Similarly at line 79 (BufferQueue.h), max_c at line 1613 (TCPEndpoint.cpp)
and some other examples.

I feel the only disadvantage of using such bit hacks is that they make the
code obscure. But they are really good for performance (alteast as per my
understanding).

So what I wanted to know is, are there any inherent problems associated
with using bit hacks such as these? If the only problem is that the code
produced is difficult to understand, can't that be dealt with comments. Or
altogether we can bundle up these hacks in a nice header file and give
proper names to them (like bit_min_c or some prefix to help differentiate
them) to avoid confusion.

If found useful, I would like to implement a header file that provides at
least the operations discussed at:
https://graphics.stanford.edu/~seander/bithacks.html.

When searching through the already available bit manipulating APIs in
haiku, I could only find result for bitmaps
(headers/private/kernel/util/Bitmap.h) and not hacks like these. There are
some available functions individually used by ntfs (ntfs/libntfs/bitmap.c)
and graphics driver (/drivers/graphics/et6x00/bits.c).

However on comparing the bitmap with the one available in Linux:
https://github.com/torvalds/linux/blob/master/include/linux/bitmap.h,
https://github.com/torvalds/linux/blob/master/lib/bitmap.c , there is quite
a difference. Many of the methods offered under Linux is missing in our
implementation (I rapidly searched through the code, so if i missed out on
some already present implementation let me know).

So in a nutshell I would like to use such bit hacks if there is no problem
with that and I would also like to create a header file for the most common
types if you all think it will be beneficial.

Thnx.

Other related posts: