ConstraintAnalysis: Optimize loops - #8980
Conversation
tlively
left a comment
There was a problem hiding this comment.
Nice!
I'm concerned we'll still need a more conservative fallback, though. Consider this loop:
x = 0
y = 100
while (x < y) {
++x;
++x;
++y;
}
This loop will also execute 100 times, and hopefully we are able to analyze all the individual operations, but the loop condition does not contain a constant, so this particular widening heuristic will not apply.
| // comment). | ||
| if (auto* M = std::get_if<Literal>(&branch.constraint.term)) { | ||
| auto localConstraints = constraints.get(branch.local); | ||
| if (localConstraints.size() == 1 && |
There was a problem hiding this comment.
Probably worth a comment about why we only handle the case where there is only a single constraint.
It also might be easier to read if we invert the conditions and early return false when our expectations are not met.
Loops where the bound changes (not just |
|
Are you saying the pass will already stop early with that sample program because it is not sophisticated enough to prove that the loop condition still holds after the first iteration? Or are you saying that the pass will hang on loops like this, and that's ok because they're rare? If the former, that is surprising because I would expect the pass to be powerful enough for this analysis. If the latter, then I think it would be worth adding a fallback widening mechanism to avoid performance cliffs. You already track the visitation count in debug code, so widening to top when the visitation count gets too high should be simple enough. |
One Weird Trick is enough: eagerly extend ranges of constants:
This is simpler than the typical approach used in Abstract Interpretation,
as we do it eagerly (immediately on a branch). This eagerness might
lose some precision, but not in cases we care about, I don't think:
if
xis a constant and we branch on it, then it must be a loop variablethat will increment (if it isn't in a loop, the constant
xwould have beenpropagated to the branch by other passes).