Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constant Divide Not Optimized?

I have the following line of code:

#define A 360
#define B 360

temp = (s16_myvar * A) / B;

My compiler (Windriver DIAB PPC in this case, using standard extended optimization settings -XO) does not seem to optimize this away to something like temp = s16_myvar. When I look at the assembly listing, it seems to be faithfully putting 360 in a register and then after doing the multiply, dividing the result by 360.

Is there a trick I could use which would get rid of the multiply and divide in the final code?

And for those of you asking, "why?", suppose that in some configurations, B is not == A and you need to scale a variable.

like image 549
MAF Avatar asked Oct 15 '25 03:10

MAF


1 Answers

Just a supposition: integer expressions like (a x) / b can be simplified to (a / b) x when b divides a and a x does not overflow. It can be that the optimizer designers just didn't go that deep or considered such expressions as unlikely/stupid.


Update:

After a remark by Olaf, the overflow condition is irrelevant, as it is a case of undefined behavior so that the run-time is free to return any value.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!