Today while programming I stumbled upon the following question - are there any compilers which optimize based on mathematical assumptions?
For instance in cases like
unsigned int i,b;
(i,b not constant)
if(sqrt(i) == b)
...
In this case it would be a lot more effective to use
unsigned int i,b;
(i,b not constant)
if(i == b*b)
...
Assuming a sqrt() function, that handles unsigned integers and rounds sensefully.
Since I was not able to find useful information (probably because I did not know what to search for specifically), can someone please tell me or point me to a relevant source?
Are there compilers (for imperative languages) who optimize such things using some kind of heuristic? Or more specifically - what about gcc and microsoft visual c++ and matlab?
1 Answer 1
Compilers routinely engage in strength reduction.
One common example of which is reducing multiples to adds (as adds are typically faster than multiplies).
i*2
transformed to i+i
is faster on many machines, (and this is sometimes transformed to i<<1
instead).
Implicit multiplies commonly happen in for-loops over arrays (whose element size is> 1 byte), and can sometimes be reduced to adding, with optimization induction variable, which is similar in that the mathematical relationship between multiply and add is involved.
-
The way I understand it, this depends on a couple of facts, array (so consecutive data), word size or access of only every n-th element. So yes thats the general idea, but not based on a mathmatical decision, but rather using the way the data is read.NeinDochOah– NeinDochOah2016年01月22日 21:52:40 +00:00Commented Jan 22, 2016 at 21:52
-
If you're taking about induction variables, it is indeed based on access pattern, but it would be hard to argue that the transformation of repetitive multiply to cumulative addition didn't depend upon on the mathematical relationship between multiply and add.Erik Eidt– Erik Eidt2016年01月22日 22:02:08 +00:00Commented Jan 22, 2016 at 22:02
-
Yes and I therefore upvoted your post.NeinDochOah– NeinDochOah2016年01月22日 22:09:21 +00:00Commented Jan 22, 2016 at 22:09
Explore related questions
See similar questions with these tags.
sqrt(x)
andoperator*(y,y)
are equivalent in this context? You need to answer that question first.sqrt
of a negative to cause an error that you are removing with your change just as something to note.