[Mlir-commits] [mlir] [MLIR] Fix parsed integers exceeding the expected bitwidth (PR #119971)

Oleksandr Alex Zinenko llvmlistbot at llvm.org
Sun Dec 15 14:08:50 PST 2024


================
@@ -710,12 +711,36 @@ class AsmParser {
   virtual ParseResult parseFloat(const llvm::fltSemantics &semantics,
                                  APFloat &result) = 0;
 
+  /// Parse an integer value from the stream.
+  ParseResult parseInteger(APInt &result, unsigned bitWidth,
+                           IntegerType::SignednessSemantics signedness) {
+    auto loc = getCurrentLocation();
+    APInt apintResult;
+    OptionalParseResult parseResult = parseOptionalInteger(apintResult);
+    if (!parseResult.has_value() || failed(*parseResult))
+      return emitError(loc, "expected integer value");
+
+    // Unlike the parseOptionalInteger used below for integral types, the
+    // virtual APInt version does not check for whether the parsed integer fits
+    // in the width we want or whether its signednes matches the requested one.
+    // Check here.
+    if (signedness == IntegerType::Unsigned && apintResult.isNegative())
+      return emitError(loc, "negative integer when unsigned expected");
+    APInt sextOrTrunc = apintResult.sextOrTrunc(bitWidth);
+    if (sextOrTrunc.sextOrTrunc(apintResult.getBitWidth()) != apintResult)
+      return emitError(loc, "integer value too large");
+
+    result = sextOrTrunc;
+    return success();
+  }
+
   /// Parse an integer value from the stream.
   template <typename IntT>
   ParseResult parseInteger(IntT &result) {
+    static_assert(std::is_integral<IntT>::value);
----------------
ftynse wrote:

Could we rather SFINAE this away? Like use `std::enable_if_t<std::is_integral_v<IntT>>` as a result type?

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


More information about the Mlir-commits mailing list