Linux Kernel: Unlikely / Likely Macros

At one point I was debugging some issue in the linux kernel and I came across an odd “if” statement. It was something along the lines of:

if(likely(buf)){
  ... do something fancy...
}

First I thought to myself…if likely what? Its likely that car runs on gas? I really had no idea what it meant.  It turns out the likely and unlikely macros actually inform the C compiler that a block of code will “likely” be called more often than say the else case, essentially branch prediction.  This little hint of information will change how the compiler boils the code down to assembly and can give your code a performance increase.  The likely and unlikely are defined in the “compiler.h” of the linux kernel.

#define likely(x)        __builtin_expect(!!(x), 1)
#define unlikely(x)     __builtin_expect(!!(x), 0)

So if the case of likely is called, you expect !!x (not not of x) or x to be true (equal to 1).

As of GCC version >= 2.96 that __builtin_expect feature allows us developers the ability to tell the compiler branch prediction information that it in turn can use to create more efficient assembly code. According to the GCC manual page:

if (__builtin_expect (x, 0))
                foo ();
 
     [This] would indicate that we do not expect to call `foo', since we
     expect `x' to be zero.

Behind the scenes GCC will setup the assembly code to execute sequentially for the more ‘likely’ case, and save the jump for the more ‘unlikely’ case. Since the jump assembly commands are more costly and time consuming it makes sense to help inform the compiler of how your code should be run. If you know where your bottleneck is in code, this optimization can be helpful. This is especially why it is done in Kernel code!