Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am using an int type to store a value. By the semantics of the program, the value always varies in a very small range (0 - 36), and int (not a char) is used only because the CPU efficiency.

It seems like that many special arithmetical optimizations can be performed on such a small range of integers. Many function calls on those integers might be optimized into a small set of "magical" operations, and some functions may even be optimized into table look-ups.

So, is it possible to tell the compiler that this int is always in that small range, and is it possible for the compiler to do those optimizations?

share|improve this question
1  
value range optimizations exists in many compilers, eg. llvm but I'm not aware of any language hint to declare it. – Remus Rusanu 4 hours ago

Yes, it is possible. For example, for gcc you can use __builtin_unreachable to tell the compiler about impossible conditions, like so:

if ( value < 0 || value > 36 ) __builtin_unreachable();

We can wrap condition above in the macro:

#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)

And use it like so:

assume(x >= 0 && x <= 10);

As you can see, gcc performs optimizations based on this information:

#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)

int func(int x){
  assume(x >=0 && x <= 10);

    if ( x > 11 ){
      return 2;
    }else{
      return 17;
    }
}

Produces:

func(int):
    mov     eax, 17
    ret

One downside, however, that if your code ever breaks such assumptions, you get undefined behavior.

share|improve this answer
    
Can such optimizations reduce code size? – Xofo 4 hours ago
    
@Xofo probably. I think this can help too when put as a default case in switches. – Asu 4 hours ago
1  
@Xofo, didn't get it, in my example this already happening, as return 2 branch eliminated from the code by the compiler. – deniss 4 hours ago
2  
However, it seems that gcc cannot optimize functions to magical operations or table lookup as OP expected. – jingyu9575 1 hour ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.