问题
I am trying to optimize expression evaluation in a compiler.
The arithmetical expressions are all C-style, and they may contain variables. I hope to simplify the expressions as much as possible.
For example, (3+100*A*B+100)*3+100 may be simplified to 409+300*A*B.
It mainly depends on the distributive law, the associative law and the commutative law.
The main difficulty I encounter is how to combine these arithmetical laws and traditional stack-scan evaluating algorithms.
Can anyone share experiences related to this or similar problems in the context of compiler building?
回答1:
Apply constant folding combined with strength reduction during the code generation pass of the compilation. Most compiler texts will provide an algorithm to implement this.
回答2:
Compilers usually have some internal normalization rules like "constants to the left". This means a + 3 would be transformed into 3 + a, but not vice versa.
In your example,
(3+100*A*B+100)*3+100 would be normalized into
(3+100+(100*A*B))*3+100.
Now it is clear to optimize 3+100.
Another transformation might be a*C1+C2 into (a+(C2/C1))*C1 under the condition that C1 and C2 are constants. Intuitively, this normalizes "add before multiply".
Those normalizations are not optimizations. The intention is mostly to group constants together, so constant folding is more effective.
来源:https://stackoverflow.com/questions/17018463/how-to-simplify-a-c-style-arithmetical-expression-containing-variables-during-co