1717 * not O(tree). Property-less types are not cached at all — their class-only
1818 * hash is cheaper to recompute than to look up.
1919 * - the memo itself: a flat open-addressing table whose 128-bit key folds the
20- * operation, the argument count and the arguments' hashes together. 24 bytes
21- * per slot, no per-entry allocation.
20+ * operation, the argument count and the arguments' hashes together, 24 bytes
21+ * per slot. Results are borrowed, not owned: each result object carries the
22+ * list of memo keys mapping to it (an entry in the weak pt_memo_results
23+ * hash), and its death tombstones those slots. The memo therefore pins no
24+ * graphs — an entry lives exactly as long as some live scope holds the
25+ * result anyway. Owning the results instead was measured (July 2026) to
26+ * cost ~100MB of summed worker peaks on parallel runs, while the entries
27+ * that die are the cheap ones: recomputing them is CPU-neutral even at a
28+ * hit rate drop from ~90% to ~70%.
2229 *
2330 * The hash is 128 bits precisely so the key can be trusted without keeping the
2431 * arguments alive to re-verify a hit: over the ~10^5 distinct keys of a run the
@@ -66,7 +73,8 @@ static constexpr uint32_t MEMO_ARGS_LIMIT = 16;
6673 * because a coarse hash would be an unsound key. */
6774static constexpr uint32_t HASH_DEPTH_LIMIT = 64 ;
6875
69- /* Safety net on memo growth; a self-analysis run settles at ~1.5e5 entries. */
76+ /* Safety net on memo growth; with dead results invalidating their entries, a
77+ * self-analysis run peaks at ~3.5e4 live entries. */
7078static constexpr uint32_t MEMO_ENTRIES_LIMIT = 1 << 19 ;
7179
7280/* Initial slot count of the memo table; must be a power of two. */
@@ -78,21 +86,40 @@ struct Hash128
7886 uint64_t b;
7987};
8088
81- /* An occupied memo slot owns its result; result == NULL marks an empty slot. */
89+ /* An occupied memo slot borrows its result; result == NULL marks an empty
90+ * slot, result == MEMO_TOMBSTONE a deleted one (the probe chain must stay
91+ * intact, so deletion cannot empty a slot). */
8292struct MemoSlot
8393{
8494 Hash128 key;
8595 zend_object *result;
8696};
8797
98+ #define MEMO_TOMBSTONE ((zend_object *) 1 )
99+
100+ /* Each memoized result object carries this list of the memo keys mapping to
101+ * it (several keys can produce the same shared instance), held as IS_PTR in
102+ * the weak pt_memo_results hash. The engine deletes the entry when the object
103+ * dies, and the value dtor tombstones the listed slots. */
104+ struct KeyList
105+ {
106+ zend_object *obj;
107+ uint32_t count;
108+ uint32_t cap;
109+ Hash128 keys[4 ]; /* inline head; grown by erealloc */
110+ };
111+
88112static HashTable pt_type_hashes; /* weak: zend_object* -> Hash128 packed in the bucket zval */
89113static HashTable pt_ce_kinds; /* zend_class_entry* -> kind|slots */
90114static HashTable pt_obj_serials; /* weak: zend_object* -> IS_LONG serial (identity-hashed objects) */
115+ static HashTable pt_memo_results; /* weak: zend_object* -> IS_PTR KeyList */
91116static MemoSlot *pt_memo_slots = NULL ;
92117static uint32_t pt_memo_mask = 0 ;
93118static uint32_t pt_memo_count = 0 ;
119+ static uint32_t pt_memo_tombstones = 0 ;
94120static uint64_t pt_next_serial = 1 ;
95121static bool pt_cache_inited = false ;
122+ static bool pt_invalidate_active = false ;
96123
97124
98125static zend_class_entry *pt_guard_ce = NULL ;
@@ -404,16 +431,41 @@ static void typeHashDtor(zval *zv)
404431
405432/* {{{ the memo */
406433
407- /* Returns the slot for the key: either the occupied slot holding it, or the
408- * empty slot where it belongs. The table's load never reaches 1 (memoGrow()
409- * keeps it at 3/4 at most), so the probe always terminates. */
410- static zend_always_inline MemoSlot *memoFind (Hash128 key)
434+ /* Occupied slot holding the key, or NULL. The table's live+tombstone load
435+ * never reaches 1 (memoGrow() keeps it at 3/4 at most), so the probe always
436+ * terminates. */
437+ static zend_always_inline MemoSlot *memoLookup (Hash128 key)
411438{
412439 /* FNV-1a's low bits mix worst; fold the high half in before masking. */
413440 uint32_t idx = (uint32_t ) (key.a ^ (key.a >> 32 )) & pt_memo_mask;
414441 for (;;) {
415442 MemoSlot *slot = &pt_memo_slots[idx];
416- if (slot->result == NULL || (slot->key .a == key.a && slot->key .b == key.b )) {
443+ if (slot->result == NULL ) {
444+ return NULL ;
445+ }
446+ if (slot->result != MEMO_TOMBSTONE && slot->key .a == key.a && slot->key .b == key.b ) {
447+ return slot;
448+ }
449+ idx = (idx + 1 ) & pt_memo_mask;
450+ }
451+ }
452+
453+ /* Slot to insert the key into: the occupied slot already holding it, else the
454+ * first tombstone on its probe path, else the terminating empty slot. */
455+ static zend_always_inline MemoSlot *memoInsertPos (Hash128 key)
456+ {
457+ uint32_t idx = (uint32_t ) (key.a ^ (key.a >> 32 )) & pt_memo_mask;
458+ MemoSlot *tombstone = NULL ;
459+ for (;;) {
460+ MemoSlot *slot = &pt_memo_slots[idx];
461+ if (slot->result == NULL ) {
462+ return tombstone != NULL ? tombstone : slot;
463+ }
464+ if (slot->result == MEMO_TOMBSTONE ) {
465+ if (tombstone == NULL ) {
466+ tombstone = slot;
467+ }
468+ } else if (slot->key .a == key.a && slot->key .b == key.b ) {
417469 return slot;
418470 }
419471 idx = (idx + 1 ) & pt_memo_mask;
@@ -425,16 +477,100 @@ static void memoGrow()
425477 uint32_t oldCapacity = pt_memo_mask + 1 ;
426478 MemoSlot *oldSlots = pt_memo_slots;
427479
428- pt_memo_slots = (MemoSlot *) ecalloc (oldCapacity * 2 , sizeof (MemoSlot));
429- pt_memo_mask = oldCapacity * 2 - 1 ;
480+ /* Tombstones are dropped by the rehash; only grow the table when live
481+ * entries alone justify it, otherwise rehash at the same size. */
482+ uint32_t newCapacity = ((uint64_t ) pt_memo_count * 4 > (uint64_t ) oldCapacity * 2 ) ? oldCapacity * 2 : oldCapacity;
483+ pt_memo_slots = (MemoSlot *) ecalloc (newCapacity, sizeof (MemoSlot));
484+ pt_memo_mask = newCapacity - 1 ;
485+ pt_memo_tombstones = 0 ;
430486 for (uint32_t i = 0 ; i < oldCapacity; i++) {
431- if (oldSlots[i].result != NULL ) {
432- *memoFind (oldSlots[i].key ) = oldSlots[i];
487+ if (oldSlots[i].result != NULL && oldSlots[i]. result != MEMO_TOMBSTONE ) {
488+ *memoInsertPos (oldSlots[i].key ) = oldSlots[i];
433489 }
434490 }
435491 efree (oldSlots);
436492}
437493
494+ /* {{{ weak-result mode: invalidation on result death + key-list upkeep */
495+
496+ static void memoInvalidate (const KeyList *list)
497+ {
498+ for (uint32_t i = 0 ; i < list->count ; i++) {
499+ Hash128 key = list->keys [i];
500+ uint32_t idx = (uint32_t ) (key.a ^ (key.a >> 32 )) & pt_memo_mask;
501+ for (;;) {
502+ MemoSlot *slot = &pt_memo_slots[idx];
503+ if (slot->result == NULL ) {
504+ break ;
505+ }
506+ if (slot->result == list->obj && slot->key .a == key.a && slot->key .b == key.b ) {
507+ slot->result = MEMO_TOMBSTONE ;
508+ pt_memo_count--;
509+ pt_memo_tombstones++;
510+ break ;
511+ }
512+ idx = (idx + 1 ) & pt_memo_mask;
513+ }
514+ }
515+ }
516+
517+ /* Value dtor of pt_memo_results: runs when a memoized result object dies (and
518+ * on bulk cleanup, where pt_invalidate_active is off and the memo is reset
519+ * separately). */
520+ static void memoResultDtor (zval *zv)
521+ {
522+ KeyList *list = (KeyList *) Z_PTR_P (zv);
523+ if (pt_invalidate_active) {
524+ memoInvalidate (list);
525+ }
526+ efree (list);
527+ }
528+
529+ static void memoTrackResult (zend_object *obj, Hash128 key)
530+ {
531+ zval *existing = zend_hash_index_find (&pt_memo_results, zend_object_to_weakref_key (obj));
532+ if (existing != NULL ) {
533+ KeyList *list = (KeyList *) Z_PTR_P (existing);
534+ if (list->count == list->cap ) {
535+ list->cap *= 2 ;
536+ list = (KeyList *) erealloc (list, sizeof (KeyList) + (list->cap - 4 ) * sizeof (Hash128));
537+ Z_PTR_P (existing) = list;
538+ }
539+ list->keys [list->count ++] = key;
540+ return ;
541+ }
542+
543+ KeyList *list = (KeyList *) emalloc (sizeof (KeyList));
544+ list->obj = obj;
545+ list->count = 1 ;
546+ list->cap = 4 ;
547+ list->keys [0 ] = key;
548+ zval value;
549+ ZVAL_PTR (&value, list);
550+ if (zend_weakrefs_hash_add (&pt_memo_results, obj, &value) == NULL ) {
551+ efree (list); /* unreachable: the find above showed no entry */
552+ }
553+ }
554+
555+ /* Purge every key list without touching the memo slots (the caller resets
556+ * those wholesale). On 8.4 the unregister loop is spelled out, as in
557+ * pt_weakrefs_hash_destroy. */
558+ static void memoResultsClean ()
559+ {
560+ pt_invalidate_active = false ;
561+ #if PHP_VERSION_ID < 80500
562+ zend_ulong objKey;
563+ ZEND_HASH_MAP_FOREACH_NUM_KEY (&pt_memo_results, objKey) {
564+ zend_weakrefs_hash_del (&pt_memo_results, zend_weakref_key_to_object (objKey));
565+ } ZEND_HASH_FOREACH_END ();
566+ #else
567+ zend_weakrefs_hash_clean (&pt_memo_results);
568+ #endif
569+ pt_invalidate_active = true ;
570+ }
571+
572+ /* }}} */
573+
438574/* Mirrors PHPStan\Type\TypeCombinatorCache. */
439575class TypeCombinatorCache
440576{
@@ -467,8 +603,8 @@ class TypeCombinatorCache
467603 }
468604
469605 if (memoizable) {
470- MemoSlot *slot = memoFind (key);
471- if (slot-> result != NULL ) {
606+ MemoSlot *slot = memoLookup (key);
607+ if (slot != NULL ) {
472608 GC_ADDREF (slot->result );
473609 RETVAL_OBJ (slot->result );
474610 return ;
@@ -487,14 +623,17 @@ class TypeCombinatorCache
487623 if (memoizable && pt_memo_count < MEMO_ENTRIES_LIMIT ) {
488624 /* Fresh lookup: the callback re-enters these operations for nested
489625 * types, which may have inserted this very key or grown the table. */
490- MemoSlot *slot = memoFind (key);
491- if (slot->result == NULL ) {
626+ MemoSlot *slot = memoInsertPos (key);
627+ if (slot->result == NULL || slot->result == MEMO_TOMBSTONE ) {
628+ if (slot->result == MEMO_TOMBSTONE ) {
629+ pt_memo_tombstones--;
630+ }
492631 slot->key = key;
493632 slot->result = Z_OBJ_P (return_value);
494- GC_ADDREF (slot->result );
495633 pt_memo_count++;
634+ memoTrackResult (slot->result , key);
496635
497- if ((uint64_t ) pt_memo_count * 4 > (uint64_t ) (pt_memo_mask + 1 ) * 3 ) {
636+ if ((uint64_t ) ( pt_memo_count + pt_memo_tombstones) * 4 > (uint64_t ) (pt_memo_mask + 1 ) * 3 ) {
498637 memoGrow ();
499638 }
500639 }
@@ -506,11 +645,7 @@ class TypeCombinatorCache
506645 if (!pt_cache_inited) {
507646 return ;
508647 }
509- for (uint32_t i = 0 ; i <= pt_memo_mask; i++) {
510- if (pt_memo_slots[i].result != NULL ) {
511- OBJ_RELEASE (pt_memo_slots[i].result );
512- }
513- }
648+ memoResultsClean ();
514649 if (pt_memo_mask + 1 > MEMO_INITIAL_CAPACITY_LIMIT ) {
515650 efree (pt_memo_slots);
516651 pt_memo_slots = (MemoSlot *) ecalloc (MEMO_INITIAL_CAPACITY_LIMIT , sizeof (MemoSlot));
@@ -519,6 +654,7 @@ class TypeCombinatorCache
519654 memset (pt_memo_slots, 0 , (size_t ) (pt_memo_mask + 1 ) * sizeof (MemoSlot));
520655 }
521656 pt_memo_count = 0 ;
657+ pt_memo_tombstones = 0 ;
522658 }
523659};
524660
@@ -533,6 +669,7 @@ using phpstanturbo::pt_fn_do_union;
533669using phpstanturbo::pt_memo_slots;
534670using phpstanturbo::pt_memo_mask;
535671using phpstanturbo::pt_memo_count;
672+ using phpstanturbo::pt_memo_results;
536673using phpstanturbo::pt_obj_serials;
537674using phpstanturbo::pt_next_serial;
538675using phpstanturbo::pt_guard_ce;
@@ -556,13 +693,16 @@ void pt_type_combinator_cache_rinit()
556693 zend_hash_init (&pt_type_hashes, 4096 , NULL , typeHashDtor, 0 );
557694 zend_hash_init (&pt_ce_kinds, 128 , NULL , NULL , 0 );
558695 zend_hash_init (&pt_obj_serials, 1024 , NULL , NULL , 0 );
696+ zend_hash_init (&pt_memo_results, 4096 , NULL , phpstanturbo::memoResultDtor, 0 );
559697 pt_memo_slots = (phpstanturbo::MemoSlot *) ecalloc (MEMO_INITIAL_CAPACITY_LIMIT , sizeof (phpstanturbo::MemoSlot));
560698 pt_memo_mask = MEMO_INITIAL_CAPACITY_LIMIT - 1 ;
561699 pt_memo_count = 0 ;
700+ phpstanturbo::pt_memo_tombstones = 0 ;
562701 pt_next_serial = 1 ;
563702 pt_guard_ce = NULL ;
564703 pt_guard_resolved = false ;
565704 pt_guard_unavailable = false ;
705+ phpstanturbo::pt_invalidate_active = true ;
566706 pt_cache_inited = true ;
567707}
568708
@@ -572,10 +712,13 @@ void pt_type_combinator_cache_rshutdown()
572712 return ;
573713 }
574714 TypeCombinatorCache::clear ();
715+ phpstanturbo::pt_invalidate_active = false ;
716+ pt_weakrefs_hash_destroy (&pt_memo_results);
575717 efree (pt_memo_slots);
576718 pt_memo_slots = NULL ;
577719 pt_memo_mask = 0 ;
578720 pt_memo_count = 0 ;
721+ phpstanturbo::pt_memo_tombstones = 0 ;
579722 pt_weakrefs_hash_destroy (&pt_type_hashes);
580723 pt_weakrefs_hash_destroy (&pt_obj_serials);
581724 zend_hash_destroy (&pt_ce_kinds);
0 commit comments