If you love to explore your code and you have ever seen the assembly for you C or C++ code, a code sample like:
int a=2;
int y=a;
int z=y;
Your code's assembly, in an optimized version (C or C++ program compiled with optimization level -Os, -O2 or higher) may just assign 2 to a, y and z with out actually running the code.
How does the compiler know that?
Simple, it is Constant Propagation Analysis. A method that is employed by compilers to optimize the programs.
A program may have varied features and each of which affects the program behavior in some way or the other. While analyzing a program, these features are valuable pertaining to a particular problem. We extract only one or few specific attributes or information to study a particular behavior. As maintaining larger set information is costly hence it is desirable to collect minimal data to solve the problem.
Considering the constant propagation analysis, we will discus about just the constant values that are propagated in the program. Calculating these values may not only help us to locate the variables depending on some external inputs but may also help us optimizing our program. As we are aware of the importance of the software performance, it must not be very hard to agree with the importance of constant propagation too.
For example:
int a=2;
int b=2;
int i=0;
int c;
while(i<=5)
{
c=a+b; //Always 4
i++;
}
In the above example, irrespective of number of iterations of the while loop the value of a+b will remain constant. This value can be precomputed and stored and used it in the future until a or b are updated, which eventually saves the computation time.
Constant Propagation is a type of Program analysis that records set of all variables which have a fixed value, which is constant value propagated from all the program paths. It is a set of pairs of variables and their constant values.