[Mlir-commits] [mlir] [mlir][scf] Fix unsigned narrow type trip count calculation (PR #178060)

Matthias Springer llvmlistbot at llvm.org
Tue Jan 27 05:30:00 PST 2026


================
@@ -336,7 +336,10 @@ std::optional<APInt> constantTripCount(
       // case applies, so the static trip count is unknown.
       return std::nullopt;
     }
-    if (stepCst.isNegative())
+    // For unsigned values, negative step is impossible; for signed, check the
+    // sign bit properly using APSInt.
+    APSInt stepSInt(stepCst, /*isUnsigned=*/!isSigned);
+    if (stepSInt.isNegative())
       return APInt(bitwidth, 0);
----------------
matthias-springer wrote:

In case of `LB > UB`, I'd say the trip count should be zero regardless of the step. The name "lower bound" sounds like it's guaranteed to be the smaller number. (Otherwise, what is the termination criteria for the loop?)

But what about `LB < UB` and a negative step size? In that case, we would have infinite iterations.

In summary: I think we should `return std::nullopt;` here.

And update this sentence in the documentation in the header file: `A negative step or a lower bound greater than the upper bound are considered invalid and will yield a zero trip count.`

https://github.com/llvm/llvm-project/pull/178060


More information about the Mlir-commits mailing list