I am looking for an optimization algorithm that would make use of invariants in regions of code. For example
if (n == 0) f(n);
should be changed to
if (n == 0) f(0);
or
if (n >= 0) {
// ...
if (n <= 0) f(n);
if (n < 0) ...
}
should be changed to
if (n >= 0) {
// ...
if (n <= 0) f(0);
if (false) ...
}
Now I could come up with an algorithm that does this for these simple cases (basically traverse a dominator tree of the function, keep track of all given conditions, annotate uses and then do a formal evaluation). But I wonder if there are any more general algorithms that do the above transform and perhaps more sophisticated optimizations.
For example I could image this case:
if (i % 2 == 0) {
bool cond1 = i % 3 == 0;
bool cond2 = i % 6 == 0;
}
Here cond1
and cond2
always have the same value and thus one computation can be elided, but I have no idea on how to implement such a transform.
My compiler uses SSA form somewhat similar to LLVM IR.