Integer Divide Optimization
Integer divide instructions are usually slower or much slower than other instructions such as integer addition and shift. Divide expressions with power-of-two denominators or other special bit patterns can be replaced with a faster instructions.
Example:
The integer divide expression in the code fragment below can be replaced with a shift expression.
int f (unsigned int i) { return i / 2; }
Below is the code fragment after the integer divide expression has been replaced with a shift expression.
int f (unsigned int i) { return i >> 1; }
Notes:
Failure to generate correct code for integer divide is one of the most common defects in optimizers. NULLSTONE isolated defects in twelve of twenty commercially available compilers that were evaluated.
It is possible to perform integer divide optimization for both signed and unsigned integers, and both positive and negative power-of-two denominators. Most compilers optimize some power-of-two divide expressions, but few compilers can optimize all four combinations.