[flang-commits] [flang] [flang] Avoid undefined behaviour when parsing format expressions (PR #147539)

Tom Eccles via flang-commits flang-commits at lists.llvm.org
Wed Jul 9 05:04:06 PDT 2025


================
@@ -214,16 +215,18 @@ template <typename CHAR> void FormatValidator<CHAR>::NextToken() {
   case '7':
   case '8':
   case '9': {
-    int64_t lastValue;
     const CHAR *lastCursor;
     integerValue_ = 0;
     bool overflow{false};
     do {
-      lastValue = integerValue_;
       lastCursor = cursor_;
-      integerValue_ = 10 * integerValue_ + c - '0';
-      if (lastValue > integerValue_) {
-        overflow = true;
+      if (LLVM_LIKELY(!overflow)) {
+        overflow = llvm::MulOverflow(
+            static_cast<int64_t>(10), integerValue_, integerValue_);
+      }
+      if (LLVM_LIKELY(!overflow)) {
+        overflow = llvm::AddOverflow(
+            integerValue_, static_cast<int64_t>(c - '0'), integerValue_);
----------------
tblah wrote:

Personally I would find `overflow = overflow || MulOverflow() || AddOverflow()` easier to read but that is subjective. This is okay as it is.

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


More information about the flang-commits mailing list