@@ -1890,12 +1890,28 @@ bool PhaseIdealLoop::is_counted_loop(Node* x, IdealLoopTree*&loop, BasicType iv_
18901890 // Since stride > 0 and limit_correction <= stride + 1, we can restate this with no over- or underflow into:
18911891 // max_int - canonicalized_correction - limit_correction >= limit
18921892 // Since canonicalized_correction and limit_correction are both constants, we can replace them with a new constant:
1893- // final_correction = canonicalized_correction + limit_correction
1893+ // (v) final_correction = canonicalized_correction + limit_correction
1894+ //
18941895 // which gives us:
18951896 //
18961897 // Final predicate condition:
18971898 // max_int - final_correction >= limit
18981899 //
1900+ // However, we need to be careful that (v) does not over- or underflow.
1901+ // We know that:
1902+ // canonicalized_correction = stride - 1
1903+ // and
1904+ // limit_correction <= stride + 1
1905+ // and thus
1906+ // canonicalized_correction + limit_correction <= 2 * stride
1907+ // To prevent an over- or underflow of (v), we must ensure that
1908+ // 2 * stride <= max_int
1909+ // which can safely be checked without over- or underflow with
1910+ // (vi) stride != min_int AND abs(stride) <= max_int / 2
1911+ //
1912+ // We could try to further optimize the cases where (vi) does not hold but given that such large strides are
1913+ // very uncommon and the loop would only run for a very few iterations anyway, we simply bail out if (vi) fails.
1914+ //
18991915 // (2) Loop Limit Check Predicate for (ii):
19001916 // Using (ii): init < limit
19011917 //
@@ -1926,6 +1942,10 @@ bool PhaseIdealLoop::is_counted_loop(Node* x, IdealLoopTree*&loop, BasicType iv_
19261942 // there is no overflow of the iv phi after the first iteration. In this case, we don't need to check (ii)
19271943 // again and can skip the predicate.
19281944
1945+ // Check (vi) and bail out if the stride is too big.
1946+ if (stride_con == min_signed_integer (iv_bt) || (ABS (stride_con) > max_signed_integer (iv_bt) / 2 )) {
1947+ return false ;
1948+ }
19291949
19301950 // Accounting for (LE3) and (LE4) where we use pre-incremented phis in the loop exit check.
19311951 const jlong limit_correction_for_pre_iv_exit_check = (phi_incr != nullptr ) ? stride_con : 0 ;
0 commit comments