How to simplify a C-style arithmetic expression containing variables during code generation?

I am trying to optimize the evaluation of an expression in the compiler.

Arithmetic expressions are all C-style, and they can contain variables. I hope to simplify the expressions as much as possible.

For example, (3+100*A*B+100)*3+100 can be simplified to 409+300*A*B

It mainly depends on distribution law, associative law and commutative law.

The main difficulty that I am facing is how to combine these arithmetic laws and traditional stack scan estimation algorithms.

Can someone share experiences related to this or similar issues in the context of creating a compiler?

+7
source share
2 answers

Apply permanent folding , combined with a reduction in strength during the passage of the compilation code. Most compiler texts will provide an algorithm for implementing this.

+1
source

Compilers usually have some internal normalization rules, such as "constants on the left." This means that a + 3 will be converted to 3 + a , but not vice versa.

In your example, (3+100*A*B+100)*3+100 will be normalized to (3+100+(100*A*B))*3+100 . Now you can optimize 3+100 .

Another conversion may be a*C1+C2 to (a+(C2/C1))*C1 , provided that C1 and C2 are constants. Intuitively, this normalizes "add to multiplication."

These normalizations are not optimizations. The goal is to group constants together, so constant bending is more efficient.

+1
source

All Articles