Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate range information to C++ compiler?

Is there any way to indicate to the compiler that you know the value of a particular variable must be within a particular range at a certain point in the code, to assist the compiler with optimizing? I'm writing a library that makes it possible to know the range of some variables at compile time, and it would be nifty if it could somehow communicate this information to the compiler so that the compiler could use it for optimization. I'd like to add support for any compilers where it would work even if it couldn't be made to work for all of them (it sounds like the sort of thing that some compilers could have as an extension, but I haven't found any). I know I could write something like this:

if(x < COMPILE_TIME_MIN or x > COMPILE_TIME_MAX)
    return;
// compiler will assume for code below that x is in range COMPILE_TIME_MIN..COMPILE_TIME_MAX

But that's a runtime check. Maybe there's some trick to get the compiler to make an assumption about the range without such a check?

like image 917
Joseph Garvin Avatar asked Dec 12 '11 22:12

Joseph Garvin


2 Answers

Any such "hint" would be compiler-specific.

As an example, Visual C++ allows you to provide such a hint using the __assume intrinsic.

(Other compilers may also provide such intrinsics, but I am not familiar enough with other compilers to provide any further information. Consult your compiler's documentation if you are interested.)

like image 76
James McNellis Avatar answered Nov 01 '22 20:11

James McNellis


It's not standard, but with gcc, there comes a command called __builtin_expect, with macros defined as likely and unlikely that serve your purpose. See here for example which talks about using them in kernel-space, but __builtin_expect is a gcc extension and could be used in user-space also (see this question), even if likely and unlikely are not defined.

like image 38
Shahbaz Avatar answered Nov 01 '22 18:11

Shahbaz