Source code analysis of likely and unlikey Functions
When I look at the code, I often encounter the likely and unlikely functions. I probably know that they are used to detect the return value, but I don't know what they are. Today, I am so upset that I will go to the source code.
In include/Linux/compiler. H of the kernel code tree
void ftrace_likely_update(struct ftrace_branch_data *f, int val, int expect);#define likely_notrace(x)__builtin_expect(!!(x), 1)#define unlikely_notrace(x)__builtin_expect(!!(x), 0)#define __branch_check__(x, expect) ({int ______r;static struct ftrace_branch_data__attribute__((__aligned__(4)))__attribute__((section("_ftrace_annotated_branch"))) ______f = {.func = __func__,.file = __FILE__,.line = __LINE__,};______r = likely_notrace(x);ftrace_likely_update(&______f, ______r, expect); ______r;})/* * Using __builtin_constant_p(x) to ignore cases where the return * value is always the same. This idea is taken from a similar patch * written by Daniel Walker. */# ifndef likely# define likely(x)(__builtin_constant_p(x) ? !!(x) : __branch_check__(x, 1))# endif# ifndef unlikely# define unlikely(x)(__builtin_constant_p(x) ? !!(x) : __branch_check__(x, 0))# endif
I can't find the macro definition of _ builtin_constant_p. It should be to check whether X is internally Changshu. If yes, likely and unlikely are both processing !! (X), the original two logical non.
In this way, data X is compressed to values 0 and 1!
If it is not a built-in constant, execute _ branch_check __, and _ branch_check _ seems very troublesome.
______r = likely_notrace(x);
This line of code is OK, and other code will not affect the value of _____ R, while ____ r is the return value of _ branch_check.
So let's look at likely_notrace.
#define likely_notrace(x)__builtin_expect(!!(x), 1)
Returns 1 if it is 1, otherwise it is 0.
The same applies to unlikely, but the expected return value is 0.
Update again if you find it later...