Useless-Variable Elimination
Olin Shivers
Useless-Variable Elimination(UVE) is a optimization to remove unnecessary computations from Scheme programs. A useless variable is one that contributes nothing to the final outcome of the computation. We can remove these, and the computations creating them, with no loss. This is easy to detect in simple cases; however, in more complex cases(possibly including recursion), this is harder to detect. An example is a simple factorial function which takes an extra ‘bogus’ argument that is continually square rooted; it is not used in computing the factorial, but it is harder to tell it is unused.
UVE is often used to clean up after other optimizations. For example, in continuation-passing style intermediate forms, the continuation is often passed around a loop needlessly.
Useless variables are found by backwards flow analysis. First, variables who are trivially useful - such as variables returned as the final result - are added to the set of useful variables. The control-flow structure of the code is then traced backwards to mark all variables that contributed to this variable. Once we have marked all useful variables, the unmarked variables are useless.
Once we have found useless variables, we do two things; remove all references to useless variables and remove useless variables from lambda lists. In the first step, we can simply replace all useless variables to #f instead of whatever computation was used to define them. The second step is slightly harder, as we cannot delete variables from external calls; a value is still passed in, even if it is unused. This leads to two recursive dependencies to determine when it is safe to remove variables from parameter lists; you can read these in Shiver’s paper. Using these techniques, we can ‘fix’ the factorial example, removing the extra parameter and useless square root calculation.