[Mlir-commits] [mlir] [MLIR][Utils] Fix overflow in constantTripCount for narrow types (PR #179985)

Matthias Springer llvmlistbot at llvm.org
Fri Feb 6 01:46:40 PST 2026


================
@@ -365,6 +365,13 @@ std::optional<APInt> constantTripCount(
              << (isSigned ? "isSigned" : "isUnsigned") << ")";
       return APInt(bitwidth, 0);
     }
+    // Extend both operands to a wider bitwidth to avoid overflow when computing
+    // ub - lb. For example, with i8: ub=127, lb=-128, the difference is 255,
+    // which overflows in 8-bit signed arithmetic. We need at least one extra
+    // bit.
+    unsigned extendedWidth = bitwidth + 1;
----------------
matthias-springer wrote:

`diff` can be interpreted as an unsigned integer. (Cases where `ub <= lb`, i.e., cases where `diff` would be negative, are taken care above and don't reach here.)

Let's drop the bitwidth extension from the C++ code but leave a comment that it's never negative at this point in the code.


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


More information about the Mlir-commits mailing list