Constant folding

Constant folding

Constant folding and constant propagation are related compiler optimizations used by many modern compilers. An advanced form of constant propagation known as sparse conditional constant propagation can more accurately propagate constants and simultaneously remove dead code.

Contents

Constant folding

Constant folding is the process of simplifying constant expressions at compile time. Terms in constant expressions are typically simple literals, such as the integer 2, but can also be variables whose values are never modified, or variables explicitly marked as constant. Consider the statement:

 i = 320 * 200 * 32;

Most modern compilers would not actually generate two multiply instructions and a store for this statement. Instead, they identify constructs such as these, and substitute the computed values at compile time (in this case, 2,048,000), usually in the intermediate representation (IR) tree.

In some compilers, constant folding is done early so that statements such as C's array initializers can accept simple arithmetic expressions. However, it is also common to include further constant folding rounds in later stages in the compiler, as well.

Constant folding can be done in a compiler's front end on the IR tree that represents the high-level source language, before it is translated into three-address code, or in the back end, as an adjunct to constant propagation.

Constant folding and cross compilation

In implementing a cross compiler, care must be taken to ensure that the behaviour of the arithmetic operations on the host architecture matches that on the target architecture, as otherwise enabling constant folding will change the behaviour of the program. This is of particular importance in the case of floating point operations, whose precise implementation may vary widely.

Constant propagation

Constant propagation is the process of substituting the values of known constants in expressions at compile time. Such constants include those defined above, as well as intrinsic functions applied to constant values. Consider the following pseudocode:

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

Propagating x yields:

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

Continuing to propagate yields the following (which would likely be further optimized by dead code elimination of both x and y.)

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

Constant propagation is implemented in compilers using reaching definition analysis results. If a variable's all reaching definitions are the same assignment which assigns a same constant to the variable, then the variable has a constant value and can be replaced with the constant.

Constant propagation can also cause conditional branches to simplify to one or more unconditional statements, when the conditional expression can be evaluated to true or false at compile time to determine the only possible outcome.

The optimizations in action

Constant folding and propagation are typically used together to achieve many simplifications and reductions, by interleaving them iteratively until no more changes occur. Consider this pseudocode, for example:

 int a = 30;
 int b = 9 - a / 5;
 int c;
  
 c = b * 4;
 if (c > 10) {
    c = c - 10;
 }
 return c * (60 / a);

Applying constant propagation once, followed by constant folding, yields:

 int a = 30;
 int b = 3;
 int c;
  
 c = 3 * 4;
 if (c > 10) {
    c = c - 10;
 }
 return c * 2;

As a and b have been simplified to constants and their values substituted everywhere they occurred, the compiler now applies dead code elimination to discard them, reducing the code further:

 int c;
  
 c = 12;
 if (12 > 10) {
    c = 2;
 }
 return c * 2;

The compiler can now detect that the if statement will always evaluate to true, c itself can be eliminated, shrinking the code even further:

 return 4;

If this pseudocode constituted the body of a function, the compiler could further take advantage of the knowledge that it evaluates to the constant integer 4 to eliminate unnecessary calls to the function, producing further performance gains.

Further reading

  • Muchnick, Steven S. Advanced Compiler Design and Implementation. Morgan Kaufmann. 1997.

See also


Wikimedia Foundation. 2010.

Игры ⚽ Нужна курсовая?

Look at other dictionaries:

  • Constant Folding — Le constant folding est l optimisation faite par les compilateurs au premier stade de la compilation d un programme. En C, c est l optimisation qui donne la possibilité d avoir des expressions constantes dans les declarations dans l en tête,… …   Wikipédia en Français

  • Constant folding — Le constant folding est une des premières optimisations effectuée lors de la compilation d un programme. Elle consiste à remplacer une expression constante par sa valeur, calculée statiquement par le compilateur. Par exemple, le code suivant en C …   Wikipédia en Français

  • Protein folding — Protein thermodynamics redirects here. For the thermodynamics of reactions catalyzed by proteins, see Enzyme. Protein before and after folding. Protein folding is the process by which a protein structure assumes its functional shape or… …   Wikipedia

  • Compiler optimization — is the process of tuning the output of a compiler to minimize or maximize some attributes of an executable computer program. The most common requirement is to minimize the time taken to execute a program; a less common one is to minimize the… …   Wikipedia

  • IP Pascal — is an implementation of the Pascal programming language using the IP portability platform, a multiple machine, operating system and language implementation system. Overview IP Pascal implements the language Pascaline (named after Blaise Pascal s… …   Wikipedia

  • Свёртка констант — (англ. constant folding) и распространение констант (так же продвижение констант, дублирование констант, англ. constant propagation)  часто используемые в современных компиляторах оптимизации, уменьшающие избыточные вычисления,… …   Википедия

  • Control flow graph — Simplified control flowgraphs[1] A control flow graph (CFG) in computer science is a representation, using graph notation, of all paths that might be traversed through a program during its execution …   Wikipedia

  • Peephole optimization — In compiler theory, peephole optimization is a kind of optimization performed over a very small set of instructions in a segment of generated code. The set is called a peephole or a window . It works by recognising sets of instructions that don t …   Wikipedia

  • Sun Studio (software) — infobox software name = Sun Studio developer = Sun Microsystems latest release version = Sun Studio 12 latest release date = June 04, 2007 latest preview version = [http://developers.sun.com/sunstudio/downloads/express/index.jsp Sun Studio… …   Wikipedia

  • Program optimization — For algorithms to solve other optimization problems, see Optimization (mathematics). In computer science, program optimization or software optimization is the process of modifying a software system to make some aspect of it work more efficiently… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”