The existing sorting order in defined CompareSCEVComplexity sorts AddRecExprs by loop depth, but does not pay attention to dominance of loops. This can lead us to the following buggy situation:
for (...) { // loop1 op1 = {A,+,B} } for (...) { // loop2 op2 = {A,+,B} s = add op1, op2 }
In this case there is no guarantee that in operand list of s op2 comes before op1 (loop depth is the same, so they will be sorted just lexicographically), so we can incorrectly treat s as a recurrence of loop1, which is wrong.
This patch changes the sorting logic so that it places the dominated recs before the dominating recs. This ensures that when we pick the first recurrency in the operands order, it will be the bottom-most in terms of domination tree. The attached test set includes some tests that produce incorrect SCEV estimations and crashes with oldlogic.
Can we assert DT.dominates(LHead, RHead) || DT.dominates(RHead, LHead) here?