Let's say I have something like:
#define SIZE 32
/* ... */
unsigned x;
/* ... */
x %= SIZE;
Would the x % 32
generally be reduced to x & 31
by most C/C++ compilers such as GCC?
The compiler optimizes to reduce the size of the binary instead of execution speed. If you do not specify an optimization option, gcc attempts to reduce the compilation time and to make debugging always yield the result expected from reading the source code.
Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.
No. GCC passes your assembly source through the preprocessor and then to the assembler. At no time are any optimisations performed.
Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.
Yes, any respectable compiler should perform this optimization. Specifically, a % X
operation, where X
is a constant power of two will become the equivalent of an & (X-1)
operation.
GCC will even do this with optimizations turned off:
Example (gcc -c -O0
version 3.4.4 on Cygwin):
unsigned int test(unsigned int a) {
return a % 32;
}
Result (objdump -d):
00000000 <_test>:
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 8b 45 08 mov 0x8(%ebp),%eax
6: 5d pop %ebp
7: 83 e0 1f and $0x1f,%eax ;; Here
a: c3 ret
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With