[flang-commits] [flang] Simplify StringLength implementation (PR #98771)

via flang-commits flang-commits at lists.llvm.org
Sat Jul 13 13:22:48 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-flang-runtime

Author: None (serge-sans-paille)

<details>
<summary>Changes</summary>

This implementation relies on arithmetic conversion, let's see what happens when we do

    std::size_t length{std::strlen(string)};
    if (length <= std::numeric_limits<std::int64_t>::max())
        return static_cast<std::int64_t>(length);

1) if size_t == uint32_t (or lower), then the comparison operator
   invokes integral promotion to uint64_t, the comparison happens, it's
   fine.

2) if size_t == uint64_t, then the comparison is done between unsigned
   types, which implies a conversion of
   std::numeric_limits<std::int64_t>::max() to uint64_t, which happens
   without accuracy loss, fine

3) if size_t == uint128_t (or higher), then we invoke integral promotion
   of std::int64_t, it's also fine.

So this snippet has the same behavior as the existing one, while being easier to read.

---
Full diff: https://github.com/llvm/llvm-project/pull/98771.diff


1 Files Affected:

- (modified) flang/runtime/command.cpp (+2-6) 


``````````diff
diff --git a/flang/runtime/command.cpp b/flang/runtime/command.cpp
index e642248a25e68..a555e26f96a66 100644
--- a/flang/runtime/command.cpp
+++ b/flang/runtime/command.cpp
@@ -47,13 +47,9 @@ pid_t RTNAME(GetPID)() { return getpid(); }
 // Returns the length of the \p string. Assumes \p string is valid.
 static std::int64_t StringLength(const char *string) {
   std::size_t length{std::strlen(string)};
-  if constexpr (sizeof(std::size_t) < sizeof(std::int64_t)) {
+  if (length <= std::numeric_limits<std::int64_t>::max())
     return static_cast<std::int64_t>(length);
-  } else {
-    std::size_t max{std::numeric_limits<std::int64_t>::max()};
-    return length > max ? 0 // Just fail.
-                        : static_cast<std::int64_t>(length);
-  }
+  return 0;
 }
 
 static void FillWithSpaces(const Descriptor &value, std::size_t offset = 0) {

``````````

</details>


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


More information about the flang-commits mailing list