summaryrefslogtreecommitdiff
path: root/chapter33/docs/memory-management.md
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-11-30 10:43:11 -0800
committerCliff Click <cliffc@acm.org>2026-11-30 10:43:11 -0800
commitd9a46e588fe09ed58e160778b0d8dcee62d4d0e4 (patch)
tree80fdd9e8294636c0e666fa52db7cac4a9b8c8d01 /chapter33/docs/memory-management.md
parentc37676fc0c04997f51f4659848570619f68ac10d (diff)
downloadSimple-d9a46e588fe09ed58e160778b0d8dcee62d4d0e4.tar.gz
Simple-d9a46e588fe09ed58e160778b0d8dcee62d4d0e4.zip
Checkpoint Allocation2 before separate-compilation redesignch33
Replace the legacy allocation planner, deletion proof engine, and independent FunctionEffects pass with Allocation2 as the sole allocation-analysis phase. Keep one Site per optimized allocation/static object, per-site weak field facts, dependency-driven escape propagation, incoming-edge counts, and points-to dumps. Move the shared node WorkList into util. Normalize Never exits before allocation analysis and TypeCheck while preserving semantic nonreturning summaries. Keep internal class-init call dependencies out of global escapes, sharpen hidden private-memory defaults, refresh singleton constant escape sets after type closure, and publish field-local escape facts. Detach unloaded summary wrappers from scheduling roots. Retain declaration metadata and optimized return states in C0DA objects without legacy contracts. Keep qualified forward type names separate from expression member access, allow peepholes to return dead self, and retain the supporting regressions. Use integer types for symbolic field offsets and Opto-high uninitialized fields. Make Breakout's debounce helper private. Remove disabled escape implementations, obsolete null assertions, duplicate graphics compilation, survey runners/results, investigation transcripts, and source archives. Consolidate the selected ownership, lifetime, storage, deletion, and growing-array designs with their rationale/examples and academic references. Replace the obsolete Chapter33 handoff in the AI notes with current guidance. This is an unfinished analysis checkpoint. Imported pointer identities, transitive escapes, intrinsic calls, construction checks, and cofinite-summary universe rebasing still need work. Import loading order is unchanged. Validation: main/test compilation and git diff --check pass. Before/after make -k -j8 tests_nographics both report 825 executions and 78 failures, with unchanged extracted failure names; all lattice shards pass. Chapter33 retains its three failing deletion/imported-identity/transitive-escape regressions.
Diffstat (limited to 'chapter33/docs/memory-management.md')
-rw-r--r--chapter33/docs/memory-management.md368
1 files changed, 368 insertions, 0 deletions
diff --git a/chapter33/docs/memory-management.md b/chapter33/docs/memory-management.md
new file mode 100644
index 00000000..29461b99
--- /dev/null
+++ b/chapter33/docs/memory-management.md
@@ -0,0 +1,368 @@
+# Points-to, ownership, and storage
+
+## Scope and architecture
+
+Allocation2 computes allocation-site points-to facts after Opto, FinalizeIR, and
+LoopTree, before TypeCheck. It is the only allocation-analysis phase. It does
+not prove ownership, select storage, insert deletion, or implement recycling.
+Separate-compilation analysis is incomplete; its results must not authorize
+reclamation yet.
+
+The design separates three jobs:
+
+1. Analyze references, ownership/borrows, lifetime boundaries, multiplicity,
+ object sizes, and interference.
+2. Choose storage with a heuristic. Every outcome is a concrete plan or an
+ explicit unsupported diagnostic.
+3. Lower the plan into frame slots, allocations, resets, and reclamation.
+
+This separation keeps policy changes independent of the safety facts they use.
+A may-points-to set records possible aliases; it cannot by itself prove that an
+overwrite removed the last usable reference. Temporal proofs need memory order
+and reference liveness. Ownership additionally needs relationships between
+concrete objects represented by the same allocation site.
+
+## (1) Points-to analysis
+
+### Object abstraction and precision
+
+Each optimized NewNode denotes one abstract Site, potentially representing many
+runtime objects. Static constant objects have separate Sites. Distinct NewNodes
+of the same class stay distinct. TypeStruct supplies the layout; each Site owns
+its reference-field facts, indexed in TypeStruct field order and looked up by
+field alias. Array indices share the `[]` field.
+
+The analysis is interprocedural and context-insensitive over the remaining IR.
+Parameters merge live actuals and calls share their callee's result facts.
+Earlier inlining supplies context precision by cloning code. There are no
+per-call analysis copies. A shared factory therefore has one abstract allocation
+even when two calls produce different concrete objects.
+
+This gives a small finite abstraction with ordinary monotone constraints. The
+cost is loss of call-site correlation, array-index precision, and temporal field
+contents. A set containing one Site is not proof of one concrete object.
+Bounded repetition belongs to earlier optimization: unrolling four allocations
+gives four NewNodes; this pass does not add exact-count analysis.
+
+Recursion is deferred for lifetime placement. Cyclic points-to constraints have
+a finite domain, but convergence does not prove a recursive storage policy.
+The intended later model treats a recursive call SCC as a loop-like unit.
+[Recency abstraction][recency], distinguishing the newest object from older
+summary objects, is an optional future precision improvement.
+
+### Facts and worklist
+
+```text
+P(pointer SSA node) -> set of Sites, plus an outside-storage flag
+H(Site, reference field) -> set of Sites, plus an outside-storage flag
+Escapes -> local Sites accessible outside, plus outside storage
+```
+
+Points stores a HashSet of Sites. Null adds no Site; nullability belongs to the
+type analysis. The `_unknown` flag denotes storage outside the local collection;
+compatible local escapees are separate explicit Sites. An empty local set is
+therefore different from an unknown external reference.
+
+| Operation | Constraint |
+|---|---|
+| New and its pointer projection | Seed the allocation Site |
+| Static object constant | Seed its static Site |
+| Pointer Phi / formal parameter | Union live input facts |
+| Guard, readonly, construction/init view | Forward pointer facts |
+| `p.f = q` | Union P(q) into each possible base Site's field |
+| `q = p.f` | Union the corresponding fields of possible base Sites |
+| Known loaded call | Actual-to-Parm links; Return-to-call-result links |
+| External argument or result | Relate outside storage and compatible escapees; incomplete |
+
+Stores are weak updates: a Site can represent many concrete objects. Conversely,
+multiple aliases to a proven concrete singleton would not prevent a strong
+update, because all those aliases observe the same cell. Set cardinality,
+number of pointer names, and concrete multiplicity are distinct facts.
+
+Reading a Points registers the consuming Node. Growing a fact requeues its
+readers on util.WorkList; loads and stores discover field dependencies as their
+bases grow. Node-keyed tables use identity rather than Node.hashCode, which
+participates in GVN locking. The solver uses graph walks for initialization and
+dependency-driven propagation thereafter. `verify()` explicitly re-evaluates
+constraints and is called by assertions/tests; it is not a second production
+analysis pass. Convergence checking is not a soundness proof.
+
+After solving, reverse field-edge counts identify candidate owning fields.
+These counts exclude local SSA aliases and do not prove concrete ownership.
+`simple.alloc2.dump` prints Sites, fields, escapes, and pointer facts.
+
+This is an inclusion-based, field-sensitive analysis with flow-insensitive field
+facts. Its finite monotone domain supports worklist solving; broad sets and field
+cross-products can still be expensive. Cornell's [alias-analysis lesson][cornell]
+provides the standard terminology.
+
+### Separate compilation and escapes
+
+FunctionSummary is metadata for an unloaded SummaryNode: signature, optimized
+return state, name, size, and class-initialization dependencies. Serialized format
+10 (`C0DA`) contains no allocation destinations, consume contracts, or separate
+function-write analysis. A body loads when needed for inlining or evaluation.
+
+An internal call does not publish its callee's FIDX. Class-init dependency edges
+serve cycle checking and must not grant unknown callers access. Hidden private
+construction memory defaults to unknown contents with empty escape sets; actual
+calls still carry initialized field values under the broad declared signature.
+Publication of one field uses that field's value, rather than unrelated escapes
+from the entire private object. Final singleton-memory constants refresh their
+escape sets after recursive type closure has completed.
+
+Boundary handling still needs work: imported pointer results must include
+returned local arguments; escape closure must observe later field growth;
+outside writes, raw addresses, and intrinsic calls need explicit treatment.
+The current implementation and regression tests expose these gaps. Neither an
+unknown result nor a low incoming-edge count permits a lifetime decision.
+
+Cofinite imported escape sets also need a defined receiving universe. Renaming
+only their finite exclusions admits caller-private FIDXs into the infinite tail.
+Preserve membership of known remote identities while excluding local identities
+from the anonymous remote remainder. Actual local escapes enter through the
+caller's escape flow. Today type-table loading occurs during parsing, before all
+local identities exist, although SummaryNodes are installed after parsing.
+Import ordering and universe rebasing are pending work; ordinary universal type
+bounds must retain their meaning.
+
+### Normalized exits
+
+LoopTree inserts Never exits before Allocation2 and TypeCheck. FunNode preserves
+the semantic return state before adding synthetic control flow, so diagnostics
+and serialized summaries do not claim a nonreturning function returns. Rebuilding
+the loop tree for scheduling retains existing synthetic exits. Unloaded summary
+wrappers remain dispatch metadata and are detached from scheduling roots.
+
+## (2) Ownership: candidates first, per-instance proofs next
+
+Reverse field-edge counts fall directly out of points-to. If only abstract
+`A.buf` points to B, record the single source as an ownership candidate. Counts
+exclude local SSA aliases and must not silently ignore unknown external edges
+when someone eventually consumes them as evidence.
+
+The tempting inference "one reverse edge, therefore A owns B" is unsound for
+summary objects. Both heaps below have `A.buf -> {B}`:
+
+```text
+a1.buf = b1; a2.buf = b2; // separate pairings
+a1.buf = b1; a2.buf = b1; // shared child
+```
+
+The missing fact is relational: for every concrete a, a.buf belongs to that a,
+and distinct As do not retain the same owned B. Establish this at construction,
+then show every write
+to the owning field restores it. Temporary aliases are borrows whose usable
+lifetimes end before reclamation. Copying the owner pointer is fine; both copies
+name the same owning field. Copying the child creates a separate borrow to track.
+
+For hand-over-hand replacement:
+
+| Step | Old B | New B |
+|---|---|---|
+| Entry | retained by v.buf | absent |
+| `old = v.buf` | v.buf and old | absent |
+| Allocate next, copy | v.buf and old | next |
+| `v.buf = next` | old | v.buf and next |
+| Last use of next | old | v.buf |
+| Last usable reference to old ends | reclaimable | v.buf |
+
+The straight-line case is deliberately modest. Every reachable mutation,
+constructor/helper, and call must preserve the invariant or invalidate the
+candidate. A no-growth path can retain the incoming B. A new summary/version
+name must not assert a physically new object on that path. Outstanding aliases
+such as `saved = v.buf` across grow block old-buffer reclamation; loading v.buf
+after grow refers to the current child instead.
+
+This does not require runtime reference counting. [Alias burying][burying]
+explains why temporary aliases need not prevent later uniqueness. Preconditions,
+postconditions, and frame reasoning from [separation logic][seplogic] are useful
+without adopting a general theorem prover.
+
+### From one-step ownership to aggregates
+
+Prove immediate owner edges first. If A owns B and B owns C, ownership composes;
+an owner tree plus ancestry queries suffices, without enumerating every pair.
+This is not ordinary reachability:
+
+```text
+A.b -> B; A.c -> C; B.c -> C
+```
+
+A may own B and C, but B does not own C because A.c bypasses B. Detaching B does
+not authorize reclaiming C. [Owners-as-dominators][ownership] concerns the
+object graph, not the control-flow dominator tree or frame containment tree.
+
+The next generalization permits internal sharing/cycles within a representation
+while controlling access crossing its boundary, as in [external uniqueness][external].
+The ownership hierarchy may be a tree even though heap pointers form a graph.
+Whole-aggregate lifetime resembles [region reference counting][regions-rc], but
+we are not committing to runtime counts or one arena per owner.
+
+Examples: v owns its current buffer; Canvas owns its current pixel array; Game
+can own its bricks. Breakout's Game and Canvas are separate roots in main; a
+drawing helper borrowing Canvas does not transfer ownership. Keeping every
+historical buffer in the owner's arena defeats prompt reclamation, so an owned
+child must be detachable after its boundary borrows end.
+
+Pros: a uniform rule for wrappers, canvases, and nested representations, with
+cheap transitive composition. Cons: proving the first edge requires temporal
+and relational information absent from raw may-points-to sets. Internal sharing
+requires a wider boundary proof. Start with paired fields; do not solve general
+heap shape merely to handle a resize.
+
+## (3) Lifetime boundaries and reclamation proofs
+
+The proposed "frame idom" is a containing allocation-frame relation: function
+activation, loop iteration, or suitable single-entry/single-exit region. For
+`main: p=make(); use(p);`, make and use are siblings under main; the object can
+be allocated in main's frame. Ordinary immediate CFG dominance alone does not
+give that lifetime. Calling this a frame LCA avoids conflating the structures.
+
+Find a common enclosing frame for the allocation and all usable accesses,
+including indirect access through fields, returns, and retained aliases. Model
+cleanup boundaries, including loop continuation and exits. A call-DAG walk can
+propagate these requirements; do not expand the dynamic activation tree.
+Interprocedural paths must respect matched calls/returns, not connect a shared
+callee return to arbitrary callers. [Realizable-path analysis][realizable]
+explains that distinction. Context-insensitive may results may conservatively
+include infeasible paths; lifetime reasoning must preserve call/return meaning.
+
+Multiplicity is relative to the selected frame. A site may need one slot per
+iteration yet accumulate many retained objects in the enclosing function:
+
+```text
+head = null;
+while (...) head = new Cell(head);
+use(head);
+```
+
+The tiny graph `head -> A; A.next -> A` represents a potentially large list.
+The common frame is outside the loop, requiring growth. A known object size
+does not prove bounded total demand. "Many/unknown" is conservative, not a proof
+that demand is mathematically unbounded. A repeatedly executed site may still
+reuse one slot when each previous object's lifetime ends before the next.
+
+Memory-SSA walks can establish borrow ends through overwrites, calls, and
+loop backedges. Propagate checked contracts on the call DAG. Automatic deletion
+also needs a selected endpoint; conservative checkpoints suffice initially.
+These proofs are not implemented in Allocation2.
+
+"No usable future reference" is the reclamation condition. It is weaker than
+"no pointer bits anywhere": an unused local or a field overwritten before its
+next read need not keep storage alive. Mere lexical scope exit is insufficient
+if a stored/returned alias remains usable.
+
+Pros: use memory-SSA reasoning and keep lifetime separate from alias
+possibility. Cons: still must connect per-instance ownership and temporal facts
+without rebuilding the old parallel reference machinery. The frame tree and
+its SESE/cleanup representation remain to be implemented in Allocation2.
+
+## (4) Storage selection is a separate heuristic
+
+There need not be a safety theorem saying "stack allocation has become
+impossible." Retaining everything in a growing outermost region can often be
+safe but wasteful. Lifetime safety and useful bounded-space behavior differ.
+Ownership transfer exposes earlier reclamation opportunities; policy decides
+whether to exploit them. [Region inference][regions] supplies a lifetime model,
+without deciding every allocator tradeoff for us.
+
+Use an explicit decision tree, initially conservative:
+
+| Candidate decision | Required facts / tradeoff |
+|---|---|
+| Fixed slot in the LCA frame | Known size, singleton relative to that frame, sufficient lifetime; simple and cheap |
+| Grow at an available open tip | Dynamic size or overlapping instances; allocate at definition, reclaim at owning-frame end; may retain dead intermediates |
+| Another growth stack | Competing live growth obstructs one tip; extra stack/metadata cost; fixed-size repetitions are useful candidates, not a hard restriction |
+| Free-list/buddy allocation | Hand-over-hand or other proven reuse endpoints; unordered deaths/variable sizes; allocator overhead |
+| Unsupported, request rewrite | No plan justified by available facts and policy |
+
+The policy can improve later. It needs neither an optimal answer nor elaborate
+theory up front. All leaves report a decision and reason. Analysis supplies
+lifetime bounds, size, multiplicity, ownership/borrow facts, safe reuse points,
+and interference. Open-tip availability also depends on prior layout choices,
+so the heuristic combines these facts with its current plan. It must never
+manufacture a missing lifetime or deletion proof.
+
+Lowering subsequently reserves slots, passes region destinations where needed,
+inserts allocation/reset/drop operations, and handles every exit. Separating it
+from analysis makes policy changes and debugging easier.
+
+## (5) Deletion semantics: zero first, optimize later
+
+The selected design changes deletion to clear ALL fields, references and
+scalars, including final fields. References stored in deletable objects must
+admit null. Final means immutable during the live-object protocol; reset of dead
+storage is permitted. Bulk zeroing is a natural initial implementation.
+Removing redundant clearing is a later optimization with an observability proof.
+
+Between deletion and reuse, a stale non-array reference sees zeroed fields;
+after reuse its backing slot must still have a type-compatible representation. Zeroing eliminates
+references discoverable by rereading the deleted object, but cannot revoke
+references copied out before deletion. Those retain their own lifetime duties.
+
+StoreNode's existing `_init` permission bypasses final/readonly store checks,
+which is relevant to reset lowering. It is not by itself a complete solution:
+load folding, field type bounds, final-field assumptions, and memory ordering
+must agree that dead/reset memory can contain zeros. Consider an explicit raw
+storage/reset meaning for that permission. Numeric nonzero bounds and array
+headers need the same care as reference nullability.
+
+Non-array stale aliases remain type-safe and readable, so deletion does not by
+itself end the backing slot's lifetime. Reusing a readable field as an arbitrary
+allocator link is not justified. Arrays instead require proof of no usable
+stale access before physical recycling; then the allocator may reuse the old
+header, including the length field, as metadata. Auto-inserted deletion likewise
+needs the no-remaining-usable-reference proof, not just a one-edge candidate.
+
+Pros: predictable reset semantics; stale object paths no longer expose the whole
+former representation; initially simple bulk clearing. Cons: observable writes,
+final/type optimizer changes, and restrictions on reuse with stale aliases.
+Keep the chain "prove alias death -> permit header reuse -> buddy allocation"
+visible and revisit alternatives if expensive. These semantic and runtime
+changes are not implemented by the points-to slice.
+
+## Remaining implementation
+
+Complete and review separate-compilation points-to constraints before using
+them for lifetime proofs. Then implement paired ownership and borrow endpoints,
+containing-frame lifetime and multiplicity facts, the storage decision heuristic,
+and reset/reclamation lowering. Native-effect precision and consuming recursion
+are separate follow-ups, not prerequisites for choosing this analysis structure.
+
+Use small semantic assertions as well as fixed-point checks. In particular,
+exercise shared factories, weak field stores, loops, pointer arrays, imported
+identity functions, escaping object graphs, and callbacks. Keep failing semantic
+regressions visible until the corresponding behavior is implemented.
+
+The [growing-array design](growing-arrays.md) gives scope, return-destination,
+and direct-I/O examples for the later storage stage.
+
+## References
+
+- [Cornell, Alias Analysis][cornell]: constraints, heap abstraction, sensitivity.
+ Also the original [pointer-analysis notes][notes].
+- [Tofte and Talpin, Region-Based Memory Management][regions]: lifetime/regions.
+- [Balakrishnan and Reps, Recency-Abstraction for Heap-Allocated Storage][recency]:
+ most-recent versus summary objects; optional precision.
+- [Reynolds, Separation Logic][seplogic]: local heap reasoning and contracts.
+- [Boyland, Alias Burying][burying]: uniqueness after temporary aliases.
+- [Clarke and Wrigstad, External Uniqueness Is Unique Enough][external]:
+ aggregate boundaries despite internal sharing.
+- [Gay and Aiken, Memory Management with Explicit Regions][regions-rc]:
+ region reference counting; motivation, not a selected runtime scheme.
+- [Clarke et al., Ownership Types: A Survey][ownership]: owners-as-dominators
+ and ownership variants/inference.
+- [Reps, Horwitz, and Sagiv, Precise Interprocedural Dataflow Analysis via Graph
+ Reachability][realizable]: valid call/return paths.
+
+[cornell]: https://www.cs.cornell.edu/courses/cs6120/2023fa/lesson/10/
+[notes]: https://www.cs.cornell.edu/courses/cs4120/2026sp/notes.html?id=pointer
+[regions]: https://ropas.snu.ac.kr/lib/dock/ToTa1997.pdf
+[recency]: https://research.cs.wisc.edu/wpis/papers/sas06-recency.pdf
+[seplogic]: https://www.cs.cmu.edu/~jcr/seplogic.pdf
+[burying]: https://onlinelibrary.wiley.com/doi/abs/10.1002/spe.370
+[external]: https://ics-archive.science.uu.nl/research/techreps/repo/CS-2002/2002-048.pdf
+[regions-rc]: https://theory.stanford.edu/~aiken/publications/papers/pldi98a.pdf
+[ownership]: https://ilyasergey.net/papers/ownership-survey.pdf
+[realizable]: https://www.cs.tufts.edu/comp/150CMP/papers/reps95reachability.pdf