Source code analysis of likely and unlikey Functions

Source: Internet
Author: User


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...









Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.