[libc-commits] [libc] 4c0d3e8 - [libc][regex] Make ExprPool alt spines iterative (#245590)

via libc-commits libc-commits at lists.llvm.org
Tue Nov 24 13:46:16 PST 2026


Author: Jeff Bailey
Date: 2026-11-24T21:46:10Z
New Revision: 4c0d3e841c0c8e7d3afbdb4e56992ea99d2b628f

URL: https://github.com/llvm/llvm-project/commit/4c0d3e841c0c8e7d3afbdb4e56992ea99d2b628f
DIFF: https://github.com/llvm/llvm-project/commit/4c0d3e841c0c8e7d3afbdb4e56992ea99d2b628f.diff

LOG: [libc][regex] Make ExprPool alt spines iterative (#245590)

Wide alternations in ExprPool previously recursed once per branch.
Failed coalescing scans also re-scanned remaining branches, causing
cubic compile times.

Convert make_alt and spine coalescing to iterative loops backed by
ReverseOrderBlockStore<ExprId, 16>:

* insert_sorted_no_coalesce: direct O(K) insertion after failed scans
* coalesce_into_spine: iterative tail/kept coalescing without recursion
* splice_into_sorted_spine: direct sorted rebuild with zero throwaway
Alt nodes

Two-spine merges stay symmetric, and optimised x86-64 frames stay under
256 bytes. derivative still recurses; a later patch converts it.

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.

Added: 
    

Modified: 
    libc/src/__support/regex/regex_expr_pool.cpp
    libc/src/__support/regex/regex_expr_pool.h
    libc/test/src/__support/regex/expr_test.cpp

Removed: 
    


################################################################################
diff  --git a/libc/src/__support/regex/regex_expr_pool.cpp b/libc/src/__support/regex/regex_expr_pool.cpp
index ac52cce3b39927..9779f8c26c09d4 100644
--- a/libc/src/__support/regex/regex_expr_pool.cpp
+++ b/libc/src/__support/regex/regex_expr_pool.cpp
@@ -114,16 +114,33 @@ constexpr size_t INLINE_SPINE_CAPACITY = 16;
 // 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
+struct ScopedReverseExprIdStack
     : ReverseOrderBlockStore<ExprId, INLINE_SPINE_CAPACITY> {
-  ReverseExprIdStack() = default;
-  ReverseExprIdStack(const ReverseExprIdStack &) = delete;
-  ReverseExprIdStack &operator=(const ReverseExprIdStack &) = delete;
-  ~ReverseExprIdStack() { destroy(this); }
+  ScopedReverseExprIdStack() = default;
+  ScopedReverseExprIdStack(const ScopedReverseExprIdStack &) = delete;
+  ScopedReverseExprIdStack &
+  operator=(const ScopedReverseExprIdStack &) = delete;
+  ~ScopedReverseExprIdStack() { destroy(this); }
 };
 
+// Pops the head branch from a right-associated Alt spine (or a single non-Alt
+// node), advancing `spine` to the remaining tail or EMPTY_SET_ID.
+ExprId pop_alt_head(ExprId &spine, const ExprPool &pool) {
+  LIBC_ASSERT(spine != INVALID_EXPR_ID && spine != EMPTY_SET_ID);
+  const Expr e = pool.get(spine);
+  if (e.kind == ExprKind::Alt) {
+    spine = e.bin.right;
+    return e.bin.left;
+  }
+  ExprId head = spine;
+  spine = EMPTY_SET_ID;
+  return head;
+}
+
 } // namespace
 
+struct ExprPool::ReverseExprIdStack : ScopedReverseExprIdStack {};
+
 bool ExprPool::ensure_initialized() {
   if (block_count > 0)
     return true;
@@ -371,6 +388,41 @@ ErrorOr<ExprId> ExprPool::intern_concat_node(ExprId l, ExprId r) {
       cpp::max(le.rep_expansion, re.rep_expansion)));
 }
 
+// Interns a canonical right-associated, strictly sorted Alt(l, r) node with
+// propagated nullability and repeat metadata.
+ErrorOr<ExprId> ExprPool::intern_alt_node(ExprId l, ExprId r) {
+  const Expr le = get(l);
+  const Expr re = get(r);
+  LIBC_ASSERT(l != EMPTY_SET_ID && r != EMPTY_SET_ID);
+  LIBC_ASSERT(le.kind != ExprKind::Alt);
+  LIBC_ASSERT(l < ((re.kind == ExprKind::Alt) ? re.bin.left : r));
+  return intern(Expr::make_alt(
+      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)));
+}
+
+// Prepends head onto an existing Alt spine (or returns head if tail is empty).
+ErrorOr<ExprId> ExprPool::prepend_alt_node(ExprId head, ExprId tail) {
+  return (tail == EMPTY_SET_ID) ? ErrorOr<ExprId>(head)
+                                : intern_alt_node(head, tail);
+}
+
+// Folds valid items right-to-left (LIFO) onto tail as an Alt spine, skipping
+// slots cleared to INVALID_EXPR_ID during coalescing.
+ErrorOr<ExprId> ExprPool::fold_alt_right(ReverseExprIdStack &items,
+                                         ExprId tail) {
+  ErrorOr<ExprId> acc = tail;
+  for (ExprId id : items) {
+    if (id == INVALID_EXPR_ID)
+      continue;
+    acc = prepend_alt_node(id, *acc);
+    if (!acc.has_value())
+      return acc;
+  }
+  return acc;
+}
+
 ErrorOr<ExprId> ExprPool::make_concat(ExprId l, ExprId r) {
   if (!is_valid_input(l) || !is_valid_input(r))
     return Error(REG_BADPAT);
@@ -484,8 +536,8 @@ ErrorOr<ExprId> coalesce_repeat_pair(ExprId a, ExprId b, ExprPool &pool) {
     return merged;
 
   // Re-wrap the coalesced suffix with the stripped shared Concat prefixes
-  // (ReverseExprIdStack iterates LIFO): P1 · (P2 · ... · merged).
-  ReverseExprIdStack prefixes;
+  // (LIFO iteration): P1 · (P2 · ... · merged).
+  ScopedReverseExprIdStack prefixes;
   ExprId cur = orig_a;
   for (size_t i = 0; i < prefix_depth; ++i) {
     const Expr ce = pool.get(cur);
@@ -552,30 +604,187 @@ ErrorOr<ExprId> coalesce_repeat_leaves(ExprId a, ExprId b, ExprPool &pool) {
                           cpp::max(lhs->max, rhs->max));
 }
 
-// Attempts to coalesce a single non-Alt branch `item` with any branch in
-// `spine`, returning INVALID_EXPR_ID if no branch coalesces.
-ErrorOr<ExprId> coalesce_item_into_spine(ExprId item, ExprId spine,
-                                         ExprPool &pool) {
-  const Expr item_e = pool.get(item);
-  const Expr spine_e = pool.get(spine);
-  if (!item_e.has_repeat && !spine_e.has_repeat)
-    return INVALID_EXPR_ID;
-  if (spine_e.kind != ExprKind::Alt)
-    return coalesce_repeat_pair(item, spine, pool);
-  ErrorOr<ExprId> head_c = coalesce_repeat_pair(item, spine_e.bin.left, pool);
-  if (!head_c.has_value())
-    return head_c;
-  if (*head_c != INVALID_EXPR_ID)
-    return pool.make_alt(*head_c, spine_e.bin.right);
-  ErrorOr<ExprId> tail_c =
-      coalesce_item_into_spine(item, spine_e.bin.right, pool);
-  if (!tail_c.has_value() || *tail_c == INVALID_EXPR_ID)
-    return tail_c;
-  return pool.make_alt(spine_e.bin.left, *tail_c);
+// Attempts to coalesce `candidate` into `acc_item`, updating `acc_item` when
+// their repetition intervals overlap or are adjacent.
+ErrorOr<bool> try_coalesce_into(ExprId &acc_item, ExprId candidate,
+                                ExprPool &pool) {
+  ErrorOr<ExprId> c = coalesce_repeat_pair(acc_item, candidate, pool);
+  if (!c.has_value())
+    return Error(c.error());
+  if (*c == INVALID_EXPR_ID)
+    return false;
+  acc_item = *c;
+  return true;
 }
 
 } // namespace
 
+// Inserts item into a sorted Alt spine without repeat coalescing.
+ErrorOr<ExprId> ExprPool::insert_sorted_no_coalesce(ExprId item, ExprId spine) {
+  ReverseExprIdStack prefix;
+  ExprId cur = spine;
+  while (cur != EMPTY_SET_ID) {
+    ExprId next = cur;
+    const ExprId head = pop_alt_head(next, *this);
+    if (item == head)
+      return spine;
+    if (item < head)
+      break;
+    if (!prefix.push_back(head))
+      return Error(REG_ESPACE);
+    cur = next;
+  }
+
+  // Splice item at its sorted position and rebuild the skipped prefix.
+  ErrorOr<ExprId> tail = prepend_alt_node(item, cur);
+  if (!tail.has_value())
+    return tail;
+  return fold_alt_right(prefix, *tail);
+}
+
+// Rebuilds sorted (kept, tail) with item spliced directly into its canonical
+// slot so no throwaway intermediate Alt nodes are interned in the pool.
+ErrorOr<ExprId> ExprPool::splice_into_sorted_spine(ExprId item,
+                                                   ReverseExprIdStack &kept,
+                                                   ExprId tail) {
+  // Coalescing at least one Repeat yields max >= 1 and never [1, 1], so the
+  // merged leaf is Star or Repeat (never EmptyStr or an Alt body) and Concat
+  // wrappers never collapse to a bare Alt suffix or prefix.
+  LIBC_ASSERT(item != EMPTY_SET_ID && get(item).kind != ExprKind::Alt);
+
+  // Every live entry in kept preceded tail in the sorted spine (id <
+  // tail_head), so item >= tail_head iff item belongs in tail.
+  if (tail != EMPTY_SET_ID) {
+    const Expr te = get(tail);
+    const ExprId tail_head = (te.kind == ExprKind::Alt) ? te.bin.left : tail;
+    if (item >= tail_head) {
+      ErrorOr<ExprId> new_tail = insert_sorted_no_coalesce(item, tail);
+      if (!new_tail.has_value())
+        return new_tail;
+      return fold_alt_right(kept, *new_tail);
+    }
+  }
+
+  // Otherwise item < head(tail) (or tail is empty); fold kept right-to-left
+  // (LIFO) and splice item at its sorted slot.
+  ErrorOr<ExprId> acc = tail;
+  bool placed = false;
+  for (ExprId id : kept) {
+    if (id == INVALID_EXPR_ID)
+      continue;
+    LIBC_ASSERT(id != item);
+    if (!placed && item > id) {
+      acc = prepend_alt_node(item, *acc);
+      if (!acc.has_value())
+        return acc;
+      placed = true;
+    }
+    acc = prepend_alt_node(id, *acc);
+    if (!acc.has_value())
+      return acc;
+  }
+  return placed ? acc : prepend_alt_node(item, *acc);
+}
+
+// Scans a repeat-bearing Alt spine for branches that coalesce with item,
+// alternating tail and kept sweeps until fixed point before splicing the result
+// back in.  Absorbing a branch in kept can widen acc_item so it coalesces with
+// a branch left in tail:
+//   a{2,3} | (ε | a | b{1,2}·a{0,3}) -> a{1,3} | ε | b{1,2}·a{0,3}
+//                                    -> a{0,3} | b{1,2}·a{0,3}
+//                                    -> b{0,2}·a{0,3}
+// Each absorption strictly reduces |live(kept)| + |tail|.
+ErrorOr<ExprId> ExprPool::coalesce_into_spine(ExprId item, ExprId spine) {
+  ReverseExprIdStack kept;
+  ExprId acc_item = item;
+  ExprId tail = spine;
+  bool any_merged = false;
+  bool kept_changed = false;
+  do {
+    // Sweep remaining tail branches, lazily copying skipped heads into kept
+    // only when a merge hits so non-coalescing scans allocate nothing.
+    ExprId scan = tail;
+    while (scan != EMPTY_SET_ID) {
+      // Alt::has_repeat summarizes the entire remaining sub-spine.
+      if (!get(acc_item).has_repeat && !get(scan).has_repeat)
+        break;
+      ExprId next_scan = scan;
+      const ExprId head = pop_alt_head(next_scan, *this);
+      if (!any_merged && head == acc_item)
+        return spine;
+      ErrorOr<bool> merged = try_coalesce_into(acc_item, head, *this);
+      if (!merged.has_value())
+        return Error(merged.error());
+      if (*merged) {
+        while (tail != scan) {
+          if (!kept.push_back(pop_alt_head(tail, *this)))
+            return Error(REG_ESPACE);
+        }
+        tail = next_scan;
+        scan = next_scan;
+        any_merged = true;
+        continue;
+      }
+      scan = next_scan;
+    }
+    if (!any_merged)
+      return insert_sorted_no_coalesce(item, spine);
+
+    // Re-check kept branches in case acc_item widened or changed.
+    kept_changed = false;
+    for (ExprId &id : kept) {
+      if (id == INVALID_EXPR_ID)
+        continue;
+      if (id == acc_item) {
+        // Duplicate absorbed without changing acc_item; no extra sweep needed.
+        id = INVALID_EXPR_ID;
+        continue;
+      }
+      ErrorOr<bool> merged = try_coalesce_into(acc_item, id, *this);
+      if (!merged.has_value())
+        return Error(merged.error());
+      if (*merged) {
+        id = INVALID_EXPR_ID;
+        kept_changed = true;
+      }
+    }
+  } while (kept_changed);
+
+  return splice_into_sorted_spine(acc_item, kept, tail);
+}
+
+// Inserts a single non-Alt branch into a sorted Alt spine (or single node),
+// coalescing overlapping or adjacent Repeat intervals to a fixed point.
+ErrorOr<ExprId> ExprPool::insert_into_spine(ExprId item, ExprId spine) {
+  LIBC_ASSERT(item != EMPTY_SET_ID && spine != EMPTY_SET_ID);
+  if (item == spine)
+    return item;
+
+  const Expr ie = get(item);
+  const Expr se = get(spine);
+  LIBC_ASSERT(ie.kind != ExprKind::Alt);
+
+  // Base case: combine two non-Alt branches directly.
+  if (se.kind != ExprKind::Alt) {
+    if (ie.has_repeat || se.has_repeat) {
+      ErrorOr<bool> merged = try_coalesce_into(item, spine, *this);
+      if (!merged.has_value())
+        return Error(merged.error());
+      if (*merged)
+        return item;
+    }
+    if (item > spine)
+      cpp::swap(item, spine);
+    return intern_alt_node(item, spine);
+  }
+
+  // Fast path: no Repeat nodes anywhere, so only sorted insertion is needed.
+  if (!ie.has_repeat && !se.has_repeat)
+    return insert_sorted_no_coalesce(item, spine);
+
+  return coalesce_into_spine(item, spine);
+}
+
 ErrorOr<ExprId> ExprPool::make_alt(ExprId l, ExprId r) {
   if (!is_valid_input(l) || !is_valid_input(r))
     return Error(REG_BADPAT);
@@ -587,69 +796,69 @@ ErrorOr<ExprId> ExprPool::make_alt(ExprId l, ExprId r) {
     return (l == EMPTY_SET_ID) ? r : l;
   }
 
+  // Single-branch fast paths: insert a non-Alt node into a spine (or leaf).
   const Expr le = get(l);
   const Expr re = get(r);
-  if (le.kind != ExprKind::Alt && re.kind != ExprKind::Alt) {
-    ErrorOr<ExprId> coalesced = coalesce_repeat_pair(l, r, *this);
-    if (!coalesced.has_value() || *coalesced != INVALID_EXPR_ID)
-      return coalesced;
-    if (l > r)
-      cpp::swap(l, r);
-    return intern(Expr::make_alt(
-        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)));
+  if (le.kind != ExprKind::Alt)
+    return insert_into_spine(l, r);
+  if (re.kind != ExprKind::Alt)
+    return insert_into_spine(r, l);
+
+  // Merge two right-associated sorted Alt spines symmetrically in ascending
+  // ExprId order so multi-way alternations canonicalize to a single
+  // deduplicated tree, preserve make_alt(l, r) == make_alt(r, l), and keep
+  // derivative state spaces under '*' and '{m,n}' finite.
+  const bool any_repeat = le.has_repeat || re.has_repeat;
+  ReverseExprIdStack merged;
+  ExprId cur_l = l;
+  ExprId cur_r = r;
+  while (cur_l != cur_r && cur_l != EMPTY_SET_ID && cur_r != EMPTY_SET_ID) {
+    // When Repeat nodes are present, stop as soon as either side reaches its
+    // final non-Alt leaf so insert_into_spine(leaf, other_spine) can bridge
+    // cross-spine intervals (e.g. a{2,5} bridges a and a* in (a|a*)|(ε|a{2,5})
+    // -> ε|a*).  Because both inputs start as Alt spines and Alt::right is
+    // never EMPTY_SET_ID, both cur_l and cur_r remain non-empty on exit.
+    if (any_repeat &&
+        (get(cur_l).kind != ExprKind::Alt || get(cur_r).kind != ExprKind::Alt))
+      break;
+    ExprId next_l = cur_l;
+    ExprId next_r = cur_r;
+    const ExprId hl = pop_alt_head(next_l, *this);
+    const ExprId hr = pop_alt_head(next_r, *this);
+    if (!merged.push_back(cpp::min(hl, hr)))
+      return Error(REG_ESPACE);
+    if (hl <= hr)
+      cur_l = next_l;
+    if (hr <= hl)
+      cur_r = next_r;
   }
 
-  if (le.has_repeat || re.has_repeat) {
-    if (le.kind != ExprKind::Alt) {
-      ErrorOr<ExprId> c = coalesce_item_into_spine(l, r, *this);
-      if (!c.has_value() || *c != INVALID_EXPR_ID)
-        return c;
-    } else if (re.kind != ExprKind::Alt) {
-      ErrorOr<ExprId> c = coalesce_item_into_spine(r, l, *this);
-      if (!c.has_value() || *c != INVALID_EXPR_ID)
-        return c;
-    }
+  // Without Repeat nodes, the loop exits only on exhaustion or a shared tail;
+  // fold the merged sorted heads onto whichever tail remains:
+  // (a | c) | (b | c | d) -> a | b | c | d.
+  if (!any_repeat) {
+    LIBC_ASSERT(cur_l == cur_r || cur_l == EMPTY_SET_ID ||
+                cur_r == EMPTY_SET_ID);
+    return fold_alt_right(merged, (cur_l != EMPTY_SET_ID) ? cur_l : cur_r);
   }
 
-  // Merge two right-associated sorted Alt spines in ascending ExprId order so
-  // multi-way alternations canonicalize to a single deduplicated tree and
-  // derivative state spaces under '*' and '{m,n}' stay finite.
-  ExprId hl = (le.kind == ExprKind::Alt) ? le.bin.left : l;
-  ExprId tl = (le.kind == ExprKind::Alt) ? le.bin.right : EMPTY_SET_ID;
-  ExprId hr = (re.kind == ExprKind::Alt) ? re.bin.left : r;
-  ExprId tr = (re.kind == ExprKind::Alt) ? re.bin.right : EMPTY_SET_ID;
-  ExprId head = hl;
-  ErrorOr<ExprId> rest = EMPTY_SET_ID;
-  if (hl == hr) {
-    rest = make_alt(tl, tr);
-  } else if (hl < hr) {
-    rest = make_alt(tl, r);
-  } else {
-    head = hr;
-    rest = make_alt(l, tr);
+  // With Repeat nodes, seed acc with insert_into_spine(leaf, other_spine) and
+  // fold merged right-to-left (LIFO) so cross-spine intervals coalesce
+  // symmetrically: (a | a*) | (ε | a{2,5}) -> ε | a*.
+  LIBC_ASSERT(cur_l != EMPTY_SET_ID && cur_r != EMPTY_SET_ID);
+  ErrorOr<ExprId> acc = cur_l;
+  if (cur_l != cur_r) {
+    acc = (get(cur_l).kind != ExprKind::Alt) ? insert_into_spine(cur_l, cur_r)
+                                             : insert_into_spine(cur_r, cur_l);
+    if (!acc.has_value())
+      return acc;
   }
-  if (!rest.has_value())
-    return rest;
-  // When merging two Alt spines, `head` (or a newly coalesced interval in
-  // `*rest`) may now coalesce across the two spines or out-of-order ExprIds.
-  const Expr he = get(head);
-  const Expr re_rest = get(*rest);
-  if (le.kind == ExprKind::Alt && re.kind == ExprKind::Alt &&
-      (he.has_repeat || re_rest.has_repeat)) {
-    ErrorOr<ExprId> c = coalesce_item_into_spine(head, *rest, *this);
-    if (!c.has_value() || *c != INVALID_EXPR_ID)
-      return c;
+  for (ExprId id : merged) {
+    acc = insert_into_spine(id, *acc);
+    if (!acc.has_value())
+      return acc;
   }
-  ExprId rest_head = (re_rest.kind == ExprKind::Alt) ? re_rest.bin.left : *rest;
-  if (head >= rest_head)
-    return make_alt(head, *rest);
-  return intern(Expr::make_alt(
-      head, *rest,
-      static_cast<uint8_t>(he.nullable_mask | re_rest.nullable_mask),
-      he.has_repeat || re_rest.has_repeat,
-      cpp::max(he.rep_expansion, re_rest.rep_expansion)));
+  return acc;
 }
 
 } // namespace regex

diff  --git a/libc/src/__support/regex/regex_expr_pool.h b/libc/src/__support/regex/regex_expr_pool.h
index 71e95154bbbaf9..5a77f08f239d94 100644
--- a/libc/src/__support/regex/regex_expr_pool.h
+++ b/libc/src/__support/regex/regex_expr_pool.h
@@ -107,6 +107,8 @@ class ExprPool {
   bool allocate_block();
   bool grow_hashtable();
 
+  struct ReverseExprIdStack;
+
   /// Core hash-consing function (Interning).
   ///
   /// Guarantees that for any two identical structural definitions of an Expr,
@@ -118,6 +120,14 @@ class ExprPool {
   ///          or REG_ESPACE on failure.
   ErrorOr<ExprId> intern(Expr e);
   ErrorOr<ExprId> intern_concat_node(ExprId l, ExprId r);
+  ErrorOr<ExprId> intern_alt_node(ExprId l, ExprId r);
+  ErrorOr<ExprId> prepend_alt_node(ExprId head, ExprId tail);
+  ErrorOr<ExprId> fold_alt_right(ReverseExprIdStack &items, ExprId tail);
+  ErrorOr<ExprId> insert_sorted_no_coalesce(ExprId item, ExprId spine);
+  ErrorOr<ExprId>
+  splice_into_sorted_spine(ExprId item, ReverseExprIdStack &kept, ExprId tail);
+  ErrorOr<ExprId> coalesce_into_spine(ExprId item, ExprId spine);
+  ErrorOr<ExprId> insert_into_spine(ExprId item, ExprId spine);
 
 public:
   /// The maximum number of nodes allowed in the pool to prevent memory

diff  --git a/libc/test/src/__support/regex/expr_test.cpp b/libc/test/src/__support/regex/expr_test.cpp
index 012799b829892c..c686fb378180e6 100644
--- a/libc/test/src/__support/regex/expr_test.cpp
+++ b/libc/test/src/__support/regex/expr_test.cpp
@@ -353,22 +353,38 @@ TEST(LlvmLibcRegexExprTest, MemoryLimits) {
   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) {
+  ExprId alt_even = EMPTY_SET_ID;
+  ExprId alt_odd = EMPTY_SET_ID;
+  for (size_t i = 0; pool.size() < ExprPool::MAX_NODE_LIMIT; ++i) {
     auto next = pool.make_concat(lit_a, current);
     ASSERT_TRUE(next.has_value());
     current = *next;
     if (i == 23)
       chain_24 = current;
+    // Build two 20-branch Alt spines (spilling ReverseExprIdStack past 16)
+    // before filling the remaining pool slots.
+    if (i < 40) {
+      ExprId &target = (i % 2 == 0) ? alt_even : alt_odd;
+      auto alt_next = pool.make_alt(target, current);
+      ASSERT_TRUE(alt_next.has_value());
+      target = *alt_next;
+    }
   }
 
-  // Next one should fail, including when flattening a left chain that spills
-  // ReverseExprIdStack past its 16-element inline block.
+  // Next one should fail, including when flattening or merging chains/spines
+  // that spill 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);
+  auto alt_insert_fail = pool.make_alt(current, alt_even);
+  ASSERT_FALSE(alt_insert_fail.has_value());
+  EXPECT_EQ(alt_insert_fail.error(), REG_ESPACE);
+  auto alt_merge_fail = pool.make_alt(alt_even, alt_odd);
+  ASSERT_FALSE(alt_merge_fail.has_value());
+  EXPECT_EQ(alt_merge_fail.error(), REG_ESPACE);
 
   // A new multi-bit ByteSet at MAX_NODE_LIMIT fails without incrementing
   // byte_set_count.
@@ -455,15 +471,70 @@ class ExprBuilder {
 
 public:
   ExprPool &raw() { return pool; }
+  Expr get(ExprId id) const { return pool.get(id); }
 
   ExprId lit(char c) { return unwrap(pool.make_lit(c)); }
   ExprId star(ExprId body) { return unwrap(pool.make_star(body)); }
+  ExprId star(char c) { return star(lit(c)); }
   ExprId rep(ExprId body, uint16_t min, uint16_t max) {
     return unwrap(pool.make_repeat(body, min, max));
   }
+  ExprId rep(char c, uint16_t min, uint16_t max) {
+    return rep(lit(c), 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)); }
 
+  template <typename... Rest>
+  ExprId alt(ExprId first, ExprId second, Rest... rest) {
+    return alt(alt(first, second), rest...);
+  }
+
+  // Returns the idx-th distinct two-character literal pair ("a!", "a\"", ...)
+  // for building wide Alt spines without Repeat nodes.
+  ExprId distinct_branch(size_t idx) {
+    return cat(lit(static_cast<char>('a' + (idx / 60))),
+               lit(static_cast<char>('!' + (idx % 60))));
+  }
+
+  // Walks a right-associated Alt spine, verifies right-associativity and
+  // strictly ascending ExprId order, and returns the total branch count.
+  size_t verify_alt_spine(ExprId spine) const {
+    if (spine == INVALID_EXPR_ID)
+      return 0;
+    size_t count = 0;
+    ExprId prev = INVALID_EXPR_ID;
+    ExprId walk = spine;
+    while (walk != EMPTY_SET_ID) {
+      const Expr we = pool.get(walk);
+      const bool is_alt = (we.kind == ExprKind::Alt);
+      const ExprId head = is_alt ? we.bin.left : walk;
+      EXPECT_NE(pool.get(head).kind, ExprKind::Alt);
+      if (prev != INVALID_EXPR_ID)
+        EXPECT_LT(prev, head);
+      prev = head;
+      ++count;
+      walk = is_alt ? we.bin.right : EMPTY_SET_ID;
+    }
+    return count;
+  }
+
+  // Counts occurrences of `target` as a top-level branch of an Alt spine.
+  size_t count_branch(ExprId spine, ExprId target) const {
+    if (spine == INVALID_EXPR_ID)
+      return 0;
+    size_t hits = 0;
+    ExprId walk = spine;
+    while (walk != EMPTY_SET_ID) {
+      const Expr we = pool.get(walk);
+      const bool is_alt = (we.kind == ExprKind::Alt);
+      if ((is_alt ? we.bin.left : walk) == target)
+        ++hits;
+      walk = is_alt ? we.bin.right : EMPTY_SET_ID;
+    }
+    return hits;
+  }
+
   // 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.
@@ -516,3 +587,205 @@ TEST(LlvmLibcRegexExprTest, NestedRepeatStarUnwrapping) {
   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));
 }
+
+TEST(LlvmLibcRegexExprTest, WideAltSpineInsertAndBridging) {
+  ExprBuilder b;
+  constexpr size_t BRANCH_COUNT = 600;
+  constexpr size_t ASC_COUNT = 64;
+  // Pre-intern 600 distinct branches in ascending ExprId order.
+  for (size_t i = 0; i < BRANCH_COUNT; ++i)
+    ASSERT_NE(b.distinct_branch(i), INVALID_EXPR_ID) << "iteration " << i;
+
+  const ExprId z_1_2 = b.rep('z', 1, 2);
+  const ExprId z_3_4 = b.rep('z', 3, 4);
+  const ExprId z_5_6 = b.rep('z', 5, 6);
+  const ExprId z_1_6 = b.rep('z', 1, 6);
+
+  // Ascending insertion onto a repeat-bearing spine exercises the formerly
+  // cubic path (scanning past growing prefixes and spilling prefix in
+  // insert_sorted_no_coalesce) and matches descending construction.
+  ExprId asc_spine = z_1_2;
+  ExprId desc_64 = z_1_2;
+  for (size_t i = 0; i < ASC_COUNT; ++i) {
+    asc_spine = b.alt(b.distinct_branch(i), asc_spine);
+    desc_64 = b.alt(b.distinct_branch(ASC_COUNT - 1 - i), desc_64);
+    ASSERT_NE(asc_spine, INVALID_EXPR_ID) << "iteration " << i;
+  }
+  EXPECT_EQ(asc_spine, desc_64);
+  EXPECT_EQ(b.verify_alt_spine(asc_spine), ASC_COUNT + 1);
+
+  // Build a 601-branch spine in descending order (O(BRANCH_COUNT) pool nodes)
+  // so bridging and tail insertion spill ReverseExprIdStack across 38 blocks.
+  ExprId spine = z_1_2;
+  for (size_t i = BRANCH_COUNT; i > 0; --i) {
+    spine = b.alt(b.distinct_branch(i - 1), spine);
+    ASSERT_NE(spine, INVALID_EXPR_ID) << "iteration " << i;
+  }
+
+  // Bridging z{1,2} | z{5,6} | z{3,4} -> z{1,6} across 601 branches commutes,
+  // stays strictly sorted, and replaces all three repeats.
+  const ExprId with_5_6 = b.alt(spine, z_5_6);
+  const ExprId bridged_lr = b.alt(with_5_6, z_3_4);
+  const ExprId bridged_rl = b.alt(z_3_4, with_5_6);
+  EXPECT_EQ(bridged_lr, bridged_rl);
+  EXPECT_EQ(b.verify_alt_spine(bridged_lr), BRANCH_COUNT + 1);
+  EXPECT_EQ(b.count_branch(bridged_lr, z_1_6), size_t(1));
+  EXPECT_EQ(b.count_branch(bridged_lr, z_1_2), size_t(0));
+  EXPECT_EQ(b.count_branch(bridged_lr, z_3_4), size_t(0));
+  EXPECT_EQ(b.count_branch(bridged_lr, z_5_6), size_t(0));
+
+  // Appending a fresh higher-ID branch spills all 601 prefix entries.
+  const ExprId tail_appended = b.alt(bridged_lr, b.lit('~'));
+  EXPECT_EQ(b.verify_alt_spine(tail_appended), BRANCH_COUNT + 2);
+}
+
+TEST(LlvmLibcRegexExprTest, TwoSpineAltMergeSpillAndCommutativity) {
+  ExprBuilder b;
+
+  // Merge two 48-branch Alt spines (spilling ReverseExprIdStack's 16-item
+  // inline block) with shared branches, both plain and with bridged Repeat
+  // intervals: (L | z{1,2} | z{5,6}) | (R | z{3,4}) -> L | R | z{1,6}.
+  ExprId left_plain = EMPTY_SET_ID;
+  ExprId right_plain = EMPTY_SET_ID;
+  for (size_t i = 0; i < 24; ++i) {
+    const ExprId shared = b.distinct_branch(60 + i);
+    left_plain = b.alt(left_plain, b.distinct_branch(i * 2), shared);
+    right_plain = b.alt(right_plain, b.distinct_branch(i * 2 + 1), shared);
+    ASSERT_NE(left_plain, INVALID_EXPR_ID) << "iteration " << i;
+    ASSERT_NE(right_plain, INVALID_EXPR_ID) << "iteration " << i;
+  }
+  const ExprId plain_lr = b.alt(left_plain, right_plain);
+  EXPECT_EQ(plain_lr, b.alt(right_plain, left_plain));
+  EXPECT_EQ(b.alt(left_plain, left_plain), left_plain);
+
+  const ExprId left_rep = b.alt(left_plain, b.rep('z', 1, 2), b.rep('z', 5, 6));
+  const ExprId right_rep = b.alt(right_plain, b.rep('z', 3, 4));
+  const ExprId rep_want = b.alt(plain_lr, b.rep('z', 1, 6));
+  EXPECT_EQ(b.alt(left_rep, right_rep), rep_want);
+  EXPECT_EQ(b.alt(right_rep, left_rep), rep_want);
+
+  // Cross-spine Repeat merges that break commutativity if one spine is
+  // flattened asymmetrically into the other:
+  //   (a | a*) | (ε | a{2,5})      -> ε | a*
+  //   (ε | a)  | (b{1,2} | a{1,2}) commutes in both orders
+  const ExprId a_or_star = b.alt(b.lit('a'), b.star('a'));
+  const ExprId eps_or_a25 = b.alt(EMPTY_STR_ID, b.rep('a', 2, 5));
+  const ExprId eps_or_star = b.alt(EMPTY_STR_ID, b.star('a'));
+  EXPECT_EQ(b.alt(a_or_star, eps_or_a25), eps_or_star);
+  EXPECT_EQ(b.alt(eps_or_a25, a_or_star), eps_or_star);
+
+  const ExprId eps_or_a = b.alt(EMPTY_STR_ID, b.lit('a'));
+  const ExprId b12_or_a12 = b.alt(b.rep('b', 1, 2), b.rep('a', 1, 2));
+  EXPECT_EQ(b.alt(eps_or_a, b12_or_a12), b.alt(b12_or_a12, eps_or_a));
+
+  // Disjoint two-spine merge where low_alt's ExprId precedes high_alt's head.
+  const ExprId low_alt = b.alt(b.distinct_branch(100), b.distinct_branch(101));
+  const ExprId high_alt = b.alt(b.distinct_branch(102), b.distinct_branch(103));
+  ASSERT_LT(low_alt, b.get(high_alt).bin.left);
+  const ExprId merged_disjoint = b.alt(low_alt, high_alt);
+  EXPECT_EQ(merged_disjoint, b.alt(high_alt, low_alt));
+  EXPECT_EQ(b.verify_alt_spine(merged_disjoint), size_t(4));
+}
+
+TEST(LlvmLibcRegexExprTest, AltCoalesceCascadesBetweenKeptAndTail) {
+  ExprBuilder b;
+
+  // Absorbing earlier ε widens a{1,3} -> a{0,3}, unlocking later b{1,2}·a{0,3}:
+  //   a{2,3} | (ε | a | b{1,2}·a{0,3}) -> b{0,2}·a{0,3}.
+  const ExprId concat_spine = b.alt(EMPTY_STR_ID, b.lit('a'),
+                                    b.cat(b.rep('b', 1, 2), b.rep('a', 0, 3)));
+  const ExprId concat_want = b.cat(b.rep('b', 0, 2), b.rep('a', 0, 3));
+  EXPECT_EQ(b.alt(b.rep('a', 2, 3), concat_spine), concat_want);
+  EXPECT_EQ(b.alt(concat_spine, b.rep('a', 2, 3)), concat_want);
+
+  // Absorbing earlier ε turns a{1,∞} into a*, unlocking later b{1,2}·a*:
+  //   a{2,2} | (ε | a | a{3,∞} | b{1,2}·a*) -> b{0,2}·a*.
+  const ExprId star_spine =
+      b.alt(EMPTY_STR_ID, b.lit('a'), b.rep('a', 3, REPEAT_INF),
+            b.cat(b.rep('b', 1, 2), b.star('a')));
+  EXPECT_EQ(b.alt(b.rep('a', 2, 2), star_spine),
+            b.cat(b.rep('b', 0, 2), b.star('a')));
+
+  // Absorbing earlier ε widens a{1,3} -> a{0,3}, unlocking nested
+  // (a{0,3}){2,3}:
+  //   a{2,3} | (ε | a | (a{0,3}){2,3}) -> (a{0,3}){1,3}.
+  const ExprId a_0_3 = b.rep('a', 0, 3);
+  const ExprId nested_spine =
+      b.alt(EMPTY_STR_ID, b.lit('a'), b.rep(a_0_3, 2, 3));
+  EXPECT_EQ(b.alt(b.rep('a', 2, 3), nested_spine), b.rep(a_0_3, 1, 3));
+
+  // Preserving an unrelated middle branch m while bridging z{1,2} and z{5,6}:
+  //   (z{1,2} | m | z{5,6}) | z{3,4} -> m | z{1,6}.
+  const ExprId z_1_2 = b.rep('z', 1, 2);
+  const ExprId m = b.lit('m');
+  const ExprId z_5_6 = b.rep('z', 5, 6);
+  ASSERT_LT(z_1_2, m);
+  ASSERT_LT(m, z_5_6);
+  EXPECT_EQ(b.alt(b.alt(z_1_2, m, z_5_6), b.rep('z', 3, 4)),
+            b.alt(m, b.rep('z', 1, 6)));
+}
+
+TEST(LlvmLibcRegexExprTest, AltCoalescedBranchPlacement) {
+  ExprBuilder b;
+  // Intern in ascending ExprId order (a < b* < d < b{2,3} < f < b{1,3}) so
+  // coalesced results land at each sorted position along the spine.
+  const ExprId a = b.lit('a');
+  const ExprId star_b = b.star('b');
+  const ExprId d = b.lit('d');
+  const ExprId b_2_3 = b.rep('b', 2, 3);
+  const ExprId f = b.lit('f');
+  const ExprId b_1_3 = b.rep('b', 1, 3);
+  ASSERT_LT(a, star_b);
+  ASSERT_LT(star_b, d);
+  ASSERT_LT(d, b_2_3);
+  ASSERT_LT(b_2_3, f);
+  ASSERT_LT(f, b_1_3);
+
+  // Coalesced branch lands at the front: (d | b{2,3}) | b* -> b* | d.
+  EXPECT_EQ(b.alt(b.alt(d, b_2_3), star_b), b.alt(star_b, d));
+
+  // Coalesced branch lands between earlier skipped branches:
+  //   (a | d | b{2,3}) | b*     -> a | b* | d
+  //   (a | d | b{2,3} | f) | b* -> a | b* | d | f
+  EXPECT_EQ(b.alt(b.alt(a, d, b_2_3), star_b), b.alt(a, star_b, d));
+  EXPECT_EQ(b.alt(b.alt(a, d, b_2_3, f), star_b), b.alt(a, star_b, d, f));
+
+  // Coalesced branch sorts past a later branch:
+  //   (a | b{2,3} | f) | b -> a | f | b{1,3}.
+  EXPECT_EQ(b.alt(b.alt(a, b_2_3, f), b.lit('b')), b.alt(a, f, b_1_3));
+
+  // Coalesced branch lands right between skipped and remaining branches
+  // (k < c{0,5} < c{0,2} < w < c{3,5}).
+  const ExprId k = b.lit('k');
+  const ExprId c_0_5 = b.rep('c', 0, 5);
+  const ExprId c_0_2 = b.rep('c', 0, 2);
+  const ExprId w = b.lit('w');
+  const ExprId c_3_5 = b.rep('c', 3, 5);
+  ASSERT_LT(k, c_0_5);
+  ASSERT_LT(c_0_5, w);
+  EXPECT_EQ(b.alt(c_3_5, b.alt(c_0_2, w)), b.alt(c_0_5, w));
+  EXPECT_EQ(b.alt(c_3_5, b.alt(k, c_0_2, w)), b.alt(k, c_0_5, w));
+
+  // Coalescing unwraps to a branch already later in the spine (q* and
+  // (q{2,3})*): (R{0,3}){0,1} | ((R{0,3}){2,∞} | R*) -> R*.
+  const ExprId q_0_3 = b.rep('q', 0, 3);
+  const ExprId q03_2_inf = b.rep(q_0_3, 2, REPEAT_INF);
+  const ExprId star_q = b.star('q');
+  ASSERT_LT(q03_2_inf, star_q);
+  EXPECT_EQ(b.alt(b.rep(q_0_3, 0, 1), b.alt(q03_2_inf, star_q)), star_q);
+
+  const ExprId q_2_3 = b.rep('q', 2, 3);
+  const ExprId r_0_3 = b.rep(q_2_3, 0, 3);
+  const ExprId r03_2_inf = b.rep(r_0_3, 2, REPEAT_INF);
+  const ExprId star_q23 = b.star(q_2_3);
+  ASSERT_LT(r03_2_inf, star_q23);
+  EXPECT_EQ(b.alt(b.rep(r_0_3, 0, 1), b.alt(r03_2_inf, star_q23)), star_q23);
+
+  // Coalescing unwraps to a branch already earlier in the spine
+  // (p* < (p{0,3}){2,∞}): (p{0,3}){0,1} | (p* | (p{0,3}){2,∞}) -> p*.
+  const ExprId star_p = b.star('p');
+  const ExprId p_0_3 = b.rep('p', 0, 3);
+  const ExprId p03_2_inf = b.rep(p_0_3, 2, REPEAT_INF);
+  ASSERT_LT(star_p, p03_2_inf);
+  EXPECT_EQ(b.alt(b.rep(p_0_3, 0, 1), b.alt(star_p, p03_2_inf)), star_p);
+}


        


More information about the libc-commits mailing list