[libc-commits] [libc] [libc][regex] Make ExprPool concat and star iterative (PR #244953)

via libc-commits libc-commits at lists.llvm.org
Mon Nov 23 06:58:22 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Jeff Bailey (kaladron)

<details>
<summary>Changes</summary>

Remove self-recursion from three ExprPool operations so their stack use no longer grows with spine length:

* make_star: unwrap nested min <= 1 repeats in a loop
* make_concat: flatten and rebuild left spines via ReverseOrderBlockStore<ExprId, 16>
* coalesce_repeat_pair: scan shared left prefixes before allocating and re-wrap only when suffixes coalesce

Spines of 16 entries or fewer stay in the inline stack buffer.  make_alt and derivative still recurse; later patches convert them.

Compliance: Henry Spencer spencer_tests.txt 268/456 Bool/Err (+0) and 84/456 Full Pos (+0); AT&T testregex 399/400 ERE Bool/Err (+0), 401/473 All Bool/Err (+0), and 18/465 Full Pos (+0); zero regressions.

Assisted-by: Automated tooling, human reviewed.

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


5 Files Affected:

- (modified) libc/src/__support/regex/CMakeLists.txt (+1) 
- (modified) libc/src/__support/regex/regex_expr_pool.cpp (+135-59) 
- (modified) libc/src/__support/regex/regex_expr_pool.h (+1) 
- (modified) libc/test/src/__support/regex/CMakeLists.txt (+1) 
- (modified) libc/test/src/__support/regex/expr_test.cpp (+85-1) 


``````````diff
diff --git a/libc/src/__support/regex/CMakeLists.txt b/libc/src/__support/regex/CMakeLists.txt
index 542f61faa91603..2c88d9b159dc36 100644
--- a/libc/src/__support/regex/CMakeLists.txt
+++ b/libc/src/__support/regex/CMakeLists.txt
@@ -10,6 +10,7 @@ add_object_library(
     libc.hdr.regex_macros
     libc.hdr.stdint_proxy
     libc.hdr.types.size_t
+    libc.src.__support.blockstore
     libc.src.__support.checked_ptr
     libc.src.__support.CPP.algorithm
     libc.src.__support.CPP.array
diff --git a/libc/src/__support/regex/regex_expr_pool.cpp b/libc/src/__support/regex/regex_expr_pool.cpp
index 080b5881b125a7..84e7a32db81d8e 100644
--- a/libc/src/__support/regex/regex_expr_pool.cpp
+++ b/libc/src/__support/regex/regex_expr_pool.cpp
@@ -18,6 +18,7 @@
 #include "src/__support/CPP/array.h"
 #include "src/__support/CPP/optional.h"
 #include "src/__support/CPP/utility.h"
+#include "src/__support/blockstore.h"
 #include "src/__support/checked_ptr.h"
 #include "src/__support/hash.h"
 #include "src/__support/macros/config.h"
@@ -107,6 +108,20 @@ class BucketProber {
   Sentinel end() const { return {}; }
 };
 
+constexpr size_t INLINE_SPINE_CAPACITY = 16;
+
+// RAII LIFO wrapper around ReverseOrderBlockStore so stack-local spine buffers
+// keep short spines stack-only (INLINE_SPINE_CAPACITY inline ExprIds, zero heap
+// allocations), iterate in reverse (right-to-left) natively, and always release
+// spilled blocks on early returns.
+struct ReverseExprIdStack
+    : ReverseOrderBlockStore<ExprId, INLINE_SPINE_CAPACITY> {
+  ReverseExprIdStack() = default;
+  ReverseExprIdStack(const ReverseExprIdStack &) = delete;
+  ReverseExprIdStack &operator=(const ReverseExprIdStack &) = delete;
+  ~ReverseExprIdStack() { destroy(this); }
+};
+
 } // namespace
 
 bool ExprPool::ensure_initialized() {
@@ -308,13 +323,17 @@ ErrorOr<ExprId> ExprPool::make_star(ExprId body) {
   // Ø* = ε and ε* = ε
   if (body == EMPTY_SET_ID || body == EMPTY_STR_ID)
     return empty_str();
-  // (R*)* = R* and (R{m,n})* = R* iff m <= 1 (since R^1 is in R{m,n} iff
-  // m <= 1, whereas (a{2,3})* excludes "a").
-  const Expr be = get(body);
+
+  // Unwrap nested repeats with min <= 1: (R{m,n})* = R* iff m <= 1 (since
+  // R^1 is in R{m,n} iff m <= 1, whereas (a{2,3})* excludes "a").
+  Expr be = get(body);
+  while (be.kind == ExprKind::Repeat && be.rep.min <= 1) {
+    body = be.rep.body;
+    be = get(body);
+  }
+  // (R*)* = R*
   if (be.kind == ExprKind::Star)
     return body;
-  if (be.kind == ExprKind::Repeat && be.rep.min <= 1)
-    return make_star(be.rep.body);
   return intern(Expr::make_star(body, be.has_repeat, be.rep_expansion));
 }
 
@@ -342,6 +361,16 @@ ErrorOr<ExprId> ExprPool::make_repeat(ExprId body, uint16_t min, uint16_t max) {
                                   scale_exp(be.rep_expansion, factor)));
 }
 
+// Interns a Concat(l, r) node with propagated nullability and repeat metadata.
+ErrorOr<ExprId> ExprPool::intern_concat_node(ExprId l, ExprId r) {
+  const Expr le = get(l);
+  const Expr re = get(r);
+  return intern(Expr::make_concat(
+      l, r, static_cast<uint8_t>(le.nullable_mask & re.nullable_mask),
+      le.has_repeat || re.has_repeat,
+      cpp::max(le.rep_expansion, re.rep_expansion)));
+}
+
 ErrorOr<ExprId> ExprPool::make_concat(ExprId l, ExprId r) {
   if (!is_valid_input(l) || !is_valid_input(r))
     return Error(REG_BADPAT);
@@ -356,81 +385,128 @@ ErrorOr<ExprId> ExprPool::make_concat(ExprId l, ExprId r) {
     return (l == EMPTY_STR_ID) ? r : l;
   }
   // (A · B) · C = A · (B · C) (Right-associative canonical form)
-  const Expr le = get(l);
-  if (le.kind == ExprKind::Concat) {
-    ErrorOr<ExprId> tail = make_concat(le.bin.right, r);
-    if (!tail.has_value())
-      return tail;
-    return make_concat(le.bin.left, *tail);
+  Expr ce = get(l);
+  if (ce.kind != ExprKind::Concat)
+    return intern_concat_node(l, r);
+
+  // Flatten the right-associated left spine iteratively so long concatenations
+  // never recurse on the call stack: (A · (B · C)) · D -> [A, B], C, D.
+  ReverseExprIdStack lefts;
+  ExprId cur = l;
+  while (ce.kind == ExprKind::Concat) {
+    if (!lefts.push_back(ce.bin.left))
+      return Error(REG_ESPACE);
+    cur = ce.bin.right;
+    ce = get(cur);
   }
-  const Expr re = get(r);
-  return intern(Expr::make_concat(
-      l, r, static_cast<uint8_t>(le.nullable_mask & re.nullable_mask),
-      le.has_repeat || re.has_repeat,
-      cpp::max(le.rep_expansion, re.rep_expansion)));
+
+  // Rebuild right-to-left (LIFO): A · (B · (C · D)).
+  ErrorOr<ExprId> acc = intern_concat_node(cur, r);
+  if (!acc.has_value())
+    return acc;
+  for (ExprId id : lefts) {
+    acc = intern_concat_node(id, *acc);
+    if (!acc.has_value())
+      return acc;
+  }
+  return acc;
 }
 
 namespace {
 
+ErrorOr<ExprId> coalesce_repeat_leaves(ExprId a, ExprId b, ExprPool &pool);
+
 // Coalesces R{m1,n1} | R{m2,n2} (and shared-prefix/shared-suffix Concat nodes)
 // when their repetition intervals overlap or are adjacent.  Returns
 // INVALID_EXPR_ID when the pair cannot be coalesced.
 ErrorOr<ExprId> coalesce_repeat_pair(ExprId a, ExprId b, ExprPool &pool) {
-  const Expr ae = pool.get(a);
-  const Expr be = pool.get(b);
+  // Scan past matching left Concat prefixes (A · X) | (A · Y) -> A · (X | Y)
+  // without allocating; collect prefixes only if the suffixes coalesce.
+  const ExprId orig_a = a;
+  size_t prefix_depth = 0;
+  Expr ae = pool.get(a);
+  Expr be = pool.get(b);
+  while ((ae.has_repeat || be.has_repeat) && ae.kind == ExprKind::Concat &&
+         be.kind == ExprKind::Concat && ae.bin.right != be.bin.right &&
+         ae.bin.left == be.bin.left) {
+    ++prefix_depth;
+    a = ae.bin.right;
+    b = be.bin.right;
+    ae = pool.get(a);
+    be = pool.get(b);
+  }
   if (!ae.has_repeat && !be.has_repeat)
     return INVALID_EXPR_ID;
-  if (ae.kind == ExprKind::Concat && be.kind == ExprKind::Concat) {
-    if (ae.bin.right == be.bin.right) {
-      ErrorOr<ExprId> left =
-          coalesce_repeat_pair(ae.bin.left, be.bin.left, pool);
-      if (!left.has_value() || *left == INVALID_EXPR_ID)
-        return left;
-      return pool.make_concat(*left, ae.bin.right);
-    }
-    if (ae.bin.left == be.bin.left) {
-      ErrorOr<ExprId> right =
-          coalesce_repeat_pair(ae.bin.right, be.bin.right, pool);
-      if (!right.has_value() || *right == INVALID_EXPR_ID)
-        return right;
-      return pool.make_concat(ae.bin.left, *right);
-    }
-  }
-  // Handle Concat(X, S) | S and Concat(P, X) | P where R{0,0} normalized to
-  // EmptyStr on one side.
-  if (ae.kind == ExprKind::Concat && ae.bin.right == b) {
-    ErrorOr<ExprId> left =
-        coalesce_repeat_pair(ae.bin.left, EMPTY_STR_ID, pool);
-    if (!left.has_value() || *left == INVALID_EXPR_ID)
-      return left;
-    return pool.make_concat(*left, b);
-  }
-  if (be.kind == ExprKind::Concat && be.bin.right == a) {
-    ErrorOr<ExprId> left =
-        coalesce_repeat_pair(EMPTY_STR_ID, be.bin.left, pool);
+
+  auto merge_with_suffix = [&](ExprId lhs, ExprId rhs,
+                               ExprId suffix) -> ErrorOr<ExprId> {
+    ErrorOr<ExprId> left = coalesce_repeat_leaves(lhs, rhs, pool);
     if (!left.has_value() || *left == INVALID_EXPR_ID)
       return left;
-    return pool.make_concat(*left, a);
-  }
-  if (ae.kind == ExprKind::Concat && ae.bin.left == b) {
-    ErrorOr<ExprId> right =
-        coalesce_repeat_pair(ae.bin.right, EMPTY_STR_ID, pool);
+    return pool.make_concat(*left, suffix);
+  };
+  auto merge_with_prefix = [&](ExprId prefix, ExprId lhs,
+                               ExprId rhs) -> ErrorOr<ExprId> {
+    ErrorOr<ExprId> right = coalesce_repeat_leaves(lhs, rhs, pool);
     if (!right.has_value() || *right == INVALID_EXPR_ID)
       return right;
-    return pool.make_concat(b, *right);
+    return pool.make_concat(prefix, *right);
+  };
+
+  // Try coalescing the stripped suffixes across the Concat and leaf shapes:
+  //   (X · S) | (Y · S) -> (X | Y) · S  (e.g. a{2,3}·b | a{4,5}·b -> a{2,5}·b)
+  //   (X · S) | S       -> (X | ε) · S  (e.g. a{1,3}·b | b -> a{0,3}·b)
+  //   (P · X) | P       -> P · (X | ε)  (e.g. b·a{1,3} | b -> b·a{0,3})
+  //   X | Y             -> R{m,n}       (direct leaf intervals)
+  ErrorOr<ExprId> merged = INVALID_EXPR_ID;
+  if (ae.kind == ExprKind::Concat && be.kind == ExprKind::Concat &&
+      ae.bin.right == be.bin.right)
+    merged = merge_with_suffix(ae.bin.left, be.bin.left, ae.bin.right);
+  else if (ae.kind == ExprKind::Concat && ae.bin.right == b)
+    merged = merge_with_suffix(ae.bin.left, EMPTY_STR_ID, b);
+  else if (be.kind == ExprKind::Concat && be.bin.right == a)
+    merged = merge_with_suffix(EMPTY_STR_ID, be.bin.left, a);
+  else if (ae.kind == ExprKind::Concat && ae.bin.left == b)
+    merged = merge_with_prefix(b, ae.bin.right, EMPTY_STR_ID);
+  else if (be.kind == ExprKind::Concat && be.bin.left == a)
+    merged = merge_with_prefix(a, EMPTY_STR_ID, be.bin.right);
+  else
+    merged = coalesce_repeat_leaves(a, b, pool);
+
+  if (!merged.has_value() || *merged == INVALID_EXPR_ID || prefix_depth == 0)
+    return merged;
+
+  // Re-wrap the coalesced suffix with the stripped shared Concat prefixes
+  // (ReverseExprIdStack iterates LIFO): P1 · (P2 · ... · merged).
+  ReverseExprIdStack prefixes;
+  ExprId cur = orig_a;
+  for (size_t i = 0; i < prefix_depth; ++i) {
+    const Expr ce = pool.get(cur);
+    if (!prefixes.push_back(ce.bin.left))
+      return Error(REG_ESPACE);
+    cur = ce.bin.right;
   }
-  if (be.kind == ExprKind::Concat && be.bin.left == a) {
-    ErrorOr<ExprId> right =
-        coalesce_repeat_pair(EMPTY_STR_ID, be.bin.right, pool);
-    if (!right.has_value() || *right == INVALID_EXPR_ID)
-      return right;
-    return pool.make_concat(a, *right);
+  ExprId acc = *merged;
+  for (ExprId id : prefixes) {
+    ErrorOr<ExprId> next = pool.make_concat(id, acc);
+    if (!next.has_value())
+      return next;
+    acc = *next;
   }
+  return acc;
+}
+
+// Coalesces leaf Repeat / Star / body / EmptyStr pairs whose repetition
+// intervals overlap or are adjacent.  Returns INVALID_EXPR_ID when they
+// cannot be coalesced.
+ErrorOr<ExprId> coalesce_repeat_leaves(ExprId a, ExprId b, ExprPool &pool) {
+  const Expr ae = pool.get(a);
+  const Expr be = pool.get(b);
   if (ae.kind != ExprKind::Repeat && be.kind != ExprKind::Repeat)
     return INVALID_EXPR_ID;
   // When b is Repeat(a, ...) and a is itself a Repeat, pick body = a so
   // get_interval(a, ae) matches [1, 1] via `id == body` symmetrically with
-  // coalesce_repeat_pair(b, a).
+  // coalesce_repeat_leaves(b, a).
   ExprId body = (ae.kind == ExprKind::Repeat &&
                  !(be.kind == ExprKind::Repeat && be.rep.body == a))
                     ? ae.rep.body
diff --git a/libc/src/__support/regex/regex_expr_pool.h b/libc/src/__support/regex/regex_expr_pool.h
index 3bebee153ac1eb..71e95154bbbaf9 100644
--- a/libc/src/__support/regex/regex_expr_pool.h
+++ b/libc/src/__support/regex/regex_expr_pool.h
@@ -117,6 +117,7 @@ class ExprPool {
   /// \returns The ExprId of the unique, stable instance in the arena,
   ///          or REG_ESPACE on failure.
   ErrorOr<ExprId> intern(Expr e);
+  ErrorOr<ExprId> intern_concat_node(ExprId l, ExprId r);
 
 public:
   /// The maximum number of nodes allowed in the pool to prevent memory
diff --git a/libc/test/src/__support/regex/CMakeLists.txt b/libc/test/src/__support/regex/CMakeLists.txt
index dcc0bb12d6acca..03659c468d11c3 100644
--- a/libc/test/src/__support/regex/CMakeLists.txt
+++ b/libc/test/src/__support/regex/CMakeLists.txt
@@ -6,6 +6,7 @@ add_libc_test(
     expr_test.cpp
   DEPENDS
     libc.hdr.regex_macros
+    libc.src.__support.error_or
     libc.src.__support.regex.regex_expr_pool
 )
 
diff --git a/libc/test/src/__support/regex/expr_test.cpp b/libc/test/src/__support/regex/expr_test.cpp
index 1c329806483086..012799b829892c 100644
--- a/libc/test/src/__support/regex/expr_test.cpp
+++ b/libc/test/src/__support/regex/expr_test.cpp
@@ -11,6 +11,7 @@
 ///
 //===----------------------------------------------------------------------===//
 #include "hdr/regex_macros.h"
+#include "src/__support/error_or.h"
 #include "src/__support/regex/regex_ast.h"
 #include "src/__support/regex/regex_expr_pool.h"
 #include "test/UnitTest/Test.h"
@@ -351,16 +352,23 @@ TEST(LlvmLibcRegexExprTest, MemoryLimits) {
   // EmptySet (1), EmptyStr (2), and 'a' (3) occupy the first 3 slots.
   const ExprId lit_a = *pool.make_lit('a');
   ExprId current = lit_a;
+  ExprId chain_24 = INVALID_EXPR_ID;
   for (size_t i = 0; i < 9997; ++i) {
     auto next = pool.make_concat(lit_a, current);
     ASSERT_TRUE(next.has_value());
     current = *next;
+    if (i == 23)
+      chain_24 = current;
   }
 
-  // Next one should fail.
+  // Next one should fail, including when flattening a left chain that spills
+  // ReverseExprIdStack past its 16-element inline block.
   auto fail = pool.make_concat(lit_a, current);
   ASSERT_FALSE(fail.has_value());
   EXPECT_EQ(fail.error(), REG_ESPACE);
+  auto spilled_fail = pool.make_concat(chain_24, current);
+  ASSERT_FALSE(spilled_fail.has_value());
+  EXPECT_EQ(spilled_fail.error(), REG_ESPACE);
 
   // A new multi-bit ByteSet at MAX_NODE_LIMIT fails without incrementing
   // byte_set_count.
@@ -432,3 +440,79 @@ TEST(LlvmLibcRegexExprTest, BoundsGuardsAndNullableMask) {
   EXPECT_EQ(pool.get(*star_bol).nullable_mask, uint8_t(0b1111));
   EXPECT_EQ(pool.get(*rep_bol_or_a).nullable_mask, uint8_t(0b1010));
 }
+
+namespace {
+
+// Compositional wrapper around ExprPool that unwraps ErrorOr<ExprId> so spine
+// tests read directly as regex algebra instead of boilerplate assertions.
+class ExprBuilder {
+  ExprPool pool;
+
+  ExprId unwrap(LIBC_NAMESPACE::ErrorOr<ExprId> res) {
+    EXPECT_TRUE(res.has_value());
+    return res.has_value() ? *res : INVALID_EXPR_ID;
+  }
+
+public:
+  ExprPool &raw() { return pool; }
+
+  ExprId lit(char c) { return unwrap(pool.make_lit(c)); }
+  ExprId star(ExprId body) { return unwrap(pool.make_star(body)); }
+  ExprId rep(ExprId body, uint16_t min, uint16_t max) {
+    return unwrap(pool.make_repeat(body, min, max));
+  }
+  ExprId cat(ExprId l, ExprId r) { return unwrap(pool.make_concat(l, r)); }
+  ExprId alt(ExprId l, ExprId r) { return unwrap(pool.make_alt(l, r)); }
+
+  // Builds a right-associated literal chain cycling `pattern` (`count`
+  // literals) followed by `tail`.  A 3-character cycle ("abc") is asymmetric
+  // at both DEPTH and DEPTH - 1, so reversing rebuild order fails immediately.
+  template <size_t N>
+  ExprId cycle_literals(const char (&pattern)[N], size_t count,
+                        ExprId tail = EMPTY_STR_ID) {
+    static_assert(N > 1, "pattern must contain at least one character");
+    constexpr size_t PERIOD = N - 1;
+    ExprId acc = tail;
+    for (size_t i = count; i > 0 && acc != INVALID_EXPR_ID; --i)
+      acc = cat(lit(pattern[(i - 1) % PERIOD]), acc);
+    return acc;
+  }
+};
+
+} // namespace
+
+TEST(LlvmLibcRegexExprTest, DeepConcatFlatteningAndPrefixCoalesce) {
+  ExprBuilder b;
+  const ExprId lit_d = b.lit('d');
+
+  // Flatten a 500-deep asymmetric left Concat spine (spilling
+  // ReverseExprIdStack's 16-item inline block): P · d == a · (b · (c · ... d)).
+  constexpr size_t DEPTH = 500;
+  const ExprId prefix = b.cycle_literals("abc", DEPTH);
+  const ExprId expected = b.cycle_literals("abc", DEPTH, lit_d);
+  EXPECT_EQ(b.cat(prefix, lit_d), expected);
+
+  // Coalesce 500-deep shared-prefix Concat spines in both argument orders:
+  //   (P · d{1,2}) | (P · d{3,4}) -> P · d{1,4}
+  //   (P · d{1,2}) | (P · d{4,5}) -> Alt (non-adjacent, unmerged)
+  const ExprId p_1_2 = b.cycle_literals("abc", DEPTH, b.rep(lit_d, 1, 2));
+  const ExprId p_3_4 = b.cycle_literals("abc", DEPTH, b.rep(lit_d, 3, 4));
+  const ExprId p_4_5 = b.cycle_literals("abc", DEPTH, b.rep(lit_d, 4, 5));
+  const ExprId p_1_4 = b.cycle_literals("abc", DEPTH, b.rep(lit_d, 1, 4));
+  EXPECT_EQ(b.alt(p_1_2, p_3_4), p_1_4);
+  EXPECT_EQ(b.alt(p_3_4, p_1_2), p_1_4);
+  EXPECT_EQ(b.raw().get(b.alt(p_1_2, p_4_5)).kind, ExprKind::Alt);
+}
+
+TEST(LlvmLibcRegexExprTest, NestedRepeatStarUnwrapping) {
+  ExprBuilder b;
+  const ExprId lit_a = b.lit('a');
+
+  // Unwrap nested repeats with min <= 1: ((a{1,2}){1,3})* -> a*
+  const ExprId rep_1_2 = b.rep(lit_a, 1, 2);
+  EXPECT_EQ(b.star(b.rep(rep_1_2, 1, 3)), b.star(lit_a));
+
+  // Stop unwrapping once min >= 2: ((a{2,3}){0,2})* -> (a{2,3})*
+  const ExprId rep_2_3 = b.rep(lit_a, 2, 3);
+  EXPECT_EQ(b.star(b.rep(rep_2_3, 0, 2)), b.star(rep_2_3));
+}

``````````

</details>


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


More information about the libc-commits mailing list