Lably
Skip to content

Constant folding

Type of compiler optimization

  • 7 min read
  • 4 chapters

Related on Lably

Through Compiler and Constant (computer programming)

It is often used together with constant propagation, which substitutes variables whose values are known to be constant. An advanced form of constant propagation known as sparse conditional constant propagation can more accurately propagate constants and simultaneously remove dead code.

Constant folding

Constant folding is the process of recognizing and evaluating constant expressions at compile time rather than computing them at runtime. Terms in constant expressions are typically simple literals, such as the integer literal 2, but they may also be variables whose values are known at compile time. Consider the statement:

<span id="mwGg"></span><span class="n" id="mwGw">i</span><span class="w" id="mwHA"> </span><span class="o" id="mwHQ">=</span><span class="w" id="mwHg"> </span><span class="mi" id="mwHw">320</span><span class="w" id="mwIA"> </span><span class="o" id="mwIQ">*</span><span class="w" id="mwIg"> </span><span class="mi" id="mwIw">200</span><span class="w" id="mwJA"> </span><span class="o" id="mwJQ">*</span><span class="w" id="mwJg"> </span><span class="mi" id="mwJw">32</span><span class="p" id="mwKA">;</span>

Most 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).

Constant folding can make use of arithmetic identities. If x is numeric, the value of 0 * x is zero even if the compiler does not know the value of x. (Note that this is not valid for IEEE floats, since x could be Infinity or NaN.)

Constant folding may apply to more than just numbers. Concatenation of string literals and constant strings can be constant folded. Code such as "abc" + "def" may be replaced with "abcdef".

Sign in to keep reading

3 more chapters are free with a Lably account.

More in Computing and communication