Science  People  Locations  Timeline
Index: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Home > Constant folding


Constant folding, in computing, is the process of simplifying expressions at compile-time which consist only of constants, which are usually simple literals like 2. An example is this: i = 320*200*32;

Most modern compilers would not generate two multiply instructions for this statement. Instead, they identify constructs like these, and compute their values at compile time, substituting them in, usually in the IR (intermediate representation) tree.

Constant folding and constant propagation can work together to effect many reductions of expressions by interleaving them repeatedly until no more changes are possible. Take this pseudocode for example:

int x = 14; int y = 7 - x/2; return y*(28/x+2);

If we execute constant propagation on this, we obtain

int x = 14; int y = 7 - 14/2; return y*(28/x+2);

If we execute constant folding on this, we get:

int x = 14; int y = 0; return y*(28/x+2);

If we execute constant propagation on this, we get:

int x = 14; int y = 0; return 0;

Sometimes constant folding must be done early so that expressions which can only contain constants, and not expressions, such as array initializers in C, can accept simple arithmetic expressions. However, this doesn't preclude doing it later again after constant propagation.

Constant folding is similar to constant propagation, however constant folding must be done before the high-level language is translated to three-address-code to make code like above work. Constant propagation is done on the three-address-code (preferably on SSA form)



Read more »

Non User