summaryrefslogtreecommitdiff
path: root/chapter33/src/main/java/com/seaofnodes
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-11-21 22:00:10 -0800
committerCliff Click <cliffc@acm.org>2026-11-21 22:00:10 -0800
commit96f150b05516bc254c4035821c0119db1ecce301 (patch)
tree0058ada01b43b8b42c3c999068c3adf1d2c3e92a /chapter33/src/main/java/com/seaofnodes
parentc201515eeb2e99cb6f0e820459662affc047c2ce (diff)
downloadSimple-96f150b05516bc254c4035821c0119db1ecce301.tar.gz
Simple-96f150b05516bc254c4035821c0119db1ecce301.zip
Simple loops, loop escapes and loop scratch
Move LoopTree finding earlier. KeepAlive to force raw ptr->int to keep bytes handed to native code alive. (not sure this is worth it, alternative is to just pass the ptr)
Diffstat (limited to 'chapter33/src/main/java/com/seaofnodes')
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java661
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java28
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java7
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java1
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java48
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java102
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/Node.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java96
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java1
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Conversions.java16
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java5
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/type/Type.java7
14 files changed, 851 insertions, 131 deletions
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java
index 0c4feeee..ee83d3a4 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java
@@ -13,23 +13,34 @@ import java.util.*;
*/
public final class Allocation {
private final Summary[] _summaries;
+ private final Summary _entrySummary;
private final ArrayList<Summary> _postorder = new ArrayList<>();
- // Destination bits: result, static storage, then Call/Parm input indices.
+ // Destination bits: result, static storage, Call/Parm input indices, then
+ // borrowed field paths. A child's storage need not share its holder's owner.
private static final int RESULT=0, STATIC=1;
/** One abstract storage object. Imported allocations are distinct per call
* site; a parameter denotes borrowed storage, not an allocation to move. */
public static final class Site {
- public final NewNode _allocation; // null for a formal or static storage
- public final int _arg; // >=2: Parm index, -1: static, 0: fresh
+ public final NewNode _allocation; // null for borrowed or static storage
+ public final int _arg; // >=2: Parm index, -1: static, 0: fresh/path
public final String _name;
public final long _bytes; // snapshot before later IR rewrites
public final BitSet _owners = new BitSet();
public final HashMap<String,HashSet<Site>> _fields = new HashMap<>();
+ public Summary _frame; // activation creating this object
+ public Summary _scope; // scratch frame, null for an external destination
+ private CFGNode _birth; // allocation control, or importing call
+ private final ArrayList<String> _destinations;
+ private final HashMap<String,Site> _loads = new HashMap<>();
+ private Site _base; // borrowed field origin, e.g. arg3.c
+ private String _field;
+ private int _depth;
- private Site(NewNode allocation, int arg, String name) {
+ private Site(Summary sum, NewNode allocation, int arg, String name) {
_allocation=allocation; _arg=arg; _name=name;
+ _destinations=sum._destinations;
_bytes=allocation!=null && allocation.size()._type instanceof TypeInteger size && size.isConstant()
? size.value() : -1;
if( arg>=2 ) _owners.set(arg);
@@ -37,23 +48,43 @@ public final class Allocation {
}
public String destination() {
- if( _owners.isEmpty() ) return "frame";
+ if( _owners.isEmpty() ) return _scope==null || _scope._loop==null ? "frame" : _scope.name()+" iteration";
SB sb = new SB();
- for( int i=_owners.nextSetBit(0); i>=0; i=_owners.nextSetBit(i+1) )
- sb.p(i==RESULT ? "result" : i==STATIC ? "static" : "arg"+i).p(" & ");
+ if( _owners.get(RESULT) ) sb.p("result & ");
+ if( _owners.get(STATIC) ) sb.p("static & ");
+ ArrayList<String> names = new ArrayList<>();
+ for( int i=_owners.nextSetBit(2); i>=0; i=_owners.nextSetBit(i+1) )
+ names.add(_destinations.get(i));
+ Collections.sort(names); // Paths are discovered in arbitrary order.
+ for( String name : names ) sb.p(name).p(" & ");
return sb.unchar(3).toString();
}
}
/** Symbolic summary, with separate destinations for separate arguments.
* Object fields are weak updates: all stored references remain possible.
- * The first cut rejects pointer loads rather than guessing their origin. */
+ * Borrowed field paths describe incoming contents separately from stores. */
- // Per-function summary; allocation sites; failure reasons
+ // An activation summary: a function or one loop iteration. Loops share their
+ // enclosing function's SSA/Site vocabulary, so composition needs no cloning
+ // or argument substitution. Calls substitute that vocabulary in compose().
public static final class Summary {
- public final FunNode _fun;
+ public final FunNode _fun; // owning function, also for loop frames
+ public final LoopNode _loop; // null for a function activation
+ public Summary _parent;
+ public final ArrayList<Summary> _frames = new ArrayList<>();
public final ArrayList<Site> _sites = new ArrayList<>();
+ // Ports map formal/output identity to its value. Loop Phis are entry
+ // and continuation ports; captured SSA values name themselves. Memory
+ // ports are included; their retention effects are summarized below.
+ public final IdentityHashMap<Node,Node> _entry = new IdentityHashMap<>();
+ public final IdentityHashMap<Node,Node> _exit = new IdentityHashMap<>();
+ public final IdentityHashMap<Node,Node> _next = new IdentityHashMap<>();
public final HashSet<Site> _returns = new HashSet<>();
+ public final HashSet<Site> _retained = new HashSet<>();
+ public final HashSet<Site> _continues = new HashSet<>();
+ public final HashSet<Site> _scratch = new HashSet<>();
+ private final HashSet<Site> _escapes = new HashSet<>();
public String _reject;
private byte _state; // 0 pre/unseen, 1 mid/active DFS, 2 post/complete
// All allocation-interesting Nodes; Calls, Stores, News, Ptr ops
@@ -61,18 +92,38 @@ public final class Allocation {
// Just the Calls
private final ArrayList<CallNode> _calls = new ArrayList<>();
// Pointer expression -> possible storage objects, in this function's vocabulary.
- private final IdentityHashMap< Node,HashSet<Site>> _values = new IdentityHashMap<>();
- // Call -> returned storage after substituting actuals and importing effects once.
- private final IdentityHashMap<CallNode,HashSet<Site>> _results = new IdentityHashMap<>();
- private final BitSet _resolving = new BitSet();
- private final Site _static = new Site(null,-1,"static");
+ private final IdentityHashMap< Node,HashSet<Site>> _values;
+ // Call -> returned storage after substituting actuals and closing effects.
+ private final IdentityHashMap<CallNode,HashSet<Site>> _results;
+ private final BitSet _resolved;
+ private final BitSet _raw; // Scalar expressions feeding lexical lifetime endpoints
+ private final IdentityHashMap<LoopNode,Summary> _loops = new IdentityHashMap<>();
+ private final ArrayList<String> _destinations;
+ private final Site _static;
+ private int _pathLimit; // own reads plus the path depths imported at calls
+ private boolean _changed;
- private Summary(FunNode fun) { _fun=fun; }
+ private Summary(FunNode fun) {
+ _fun=fun; _loop=null;
+ _values=new IdentityHashMap<>();
+ _results=new IdentityHashMap<>();
+ _resolved=new BitSet();
+ _raw=new BitSet();
+ _destinations=new ArrayList<>(List.of("result","static"));
+ _static=new Site(this,null,-1,"static");
+ }
+ private Summary(Summary fun, LoopNode loop) {
+ _fun=fun._fun; _loop=loop;
+ _values=fun._values; _results=fun._results; _resolved=fun._resolved;
+ _raw=fun._raw;
+ _destinations=fun._destinations; _static=fun._static;
+ }
+ public String name() { return _loop==null ? _fun.label() : "loop#"+_loop._nid; }
// Hit the end of summary findings with no errors.
public boolean supported() { return _state==2 && _reject==null; }
// Throw or return valid summary
public Summary requireSupported() {
- if( !supported() ) throw new IllegalStateException("Allocation "+_fun.label()+": "+_reject);
+ if( !supported() ) throw new IllegalStateException("Allocation "+name()+": "+_reject);
return this;
}
// Collect first rejection
@@ -81,9 +132,14 @@ public final class Allocation {
public Allocation(CodeGen code) {
_summaries = new Summary[code._linker._len];
+ Summary entry=null;
for( FunNode fun : code._linker )
- if( fun!=null && !fun.isDead() && !fun._type.isHigh() )
- _summaries[fun.sig().fidx()] = new Summary(fun);
+ if( fun!=null && !fun.isDead() && !fun._type.isHigh() ) {
+ Summary sum=new Summary(fun);
+ _summaries[fun.sig().fidx()] = sum;
+ if( code.entryClinitName().equals(fun._name) ) entry=sum;
+ }
+ _entrySummary=entry;
for( Summary sum : _summaries )
if( sum!=null )
visit(sum);
@@ -116,6 +172,14 @@ public final class Allocation {
// Collection interesting function body and call sites
collect(sum);
for( CallNode call : sum._calls ) {
+ if( nativeCall(call) ) {
+ // Native code borrows its arguments for this call only.
+ // Returned storage still needs an explicit origin contract.
+ Type ret=call.tfp().ret();
+ if( !(ret instanceof TypeInteger || ret instanceof TypeFloat) )
+ sum.reject("native result storage has no allocation contract at call #"+call._nid);
+ continue;
+ }
Summary callee = target(call);
if( callee==null ) sum.reject("opaque or indirect call #"+call._nid);
else {
@@ -140,6 +204,15 @@ public final class Allocation {
return idx>=0 && idx<_summaries.length ? _summaries[idx] : null;
}
+ // Unlike external(), this excludes unknown targets and mixed Simple/native
+ // target sets. Every possible target must obey the native borrowing rule.
+ private static boolean nativeCall(CallNode call) {
+ if( !(call.fptr()._type instanceof TypeFunPtr fp) || XInt.isHigh(fp.fidxs()) || fp.nfcns()==0 ) return false;
+ for( int idx=XInt.next(fp.fidxs(),-1); idx>=0; idx=XInt.next(fp.fidxs(),idx) )
+ if( CodeGen.CODE.externFunc(idx)==null ) return false;
+ return true;
+ }
+
// Follow control, memory, and references, not arithmetic/offset expressions.
// Find allocations at control anchors too: their only remaining use might
// be a scalar load or a raw address buried under arithmetic. Don't walk into
@@ -147,8 +220,9 @@ public final class Allocation {
private void collect(Summary sum) {
BitSet seen = new BitSet();
ArrayDeque<Node> work = new ArrayDeque<>();
- // Start from the return
+ // Start at both ends: zero-exit loops cannot be reached from Return.
work.push(sum._fun.ret());
+ work.push(sum._fun);
// Repeat until entire function is walked
while( !work.isEmpty() ) {
Node n = work.pop();
@@ -156,6 +230,10 @@ public final class Allocation {
seen.set(n._nid);
// Add to function body
sum._nodes.add(n);
+ if( n instanceof CFGNode cfg && !(cfg instanceof ReturnNode) &&
+ (cfg==sum._fun || !cfg.isFunLeaf()) )
+ for( Node use : cfg._outputs )
+ if( use instanceof CFGNode next && !cfg.skip(next) ) work.push(next);
if( n instanceof CFGNode )
for( Node use : n._outputs )
if( use instanceof NewNode alloc && alloc.ctrl()==n ||
@@ -170,10 +248,7 @@ public final class Allocation {
work.push(use);
if( n.isFunLeaf() ) continue;
if( n instanceof CallNode call ) sum._calls.add(call);
- // Iteration/winner destinations go here. Until then reject loops,
- // even when a flow-insensitive union would appear to fit a frame.
- if( n instanceof LoopNode ) sum.reject("loop destinations not implemented");
- if( n instanceof PtrToIntNode ) sum.reject("raw address escapes lifetime tracking #"+n._nid);
+ if( n instanceof LoopNode loop ) sum._loops.put(loop,new Summary(sum,loop));
// CLInit accesses static state, not caller parameters. Its body is
// analyzed separately; stores publishing local objects to static
@@ -188,35 +263,92 @@ public final class Allocation {
in._type instanceof TypeMem || pointer(in) || in instanceof NewNode) )
work.push(in);
}
+ keepOrigins(sum,seen);
}
+ // Follow the scope endpoint backwards, not all uses of an integer address.
+ // Memory round trips and wrapper calls need no provenance: the original
+ // conversion is kept here until its own lexical scope ends.
+ private static void keepOrigins(Summary sum, BitSet seen) {
+ ArrayDeque<Node> work=new ArrayDeque<>();
+ for( Node n : sum._nodes ) if( n instanceof KeepAliveNode ) work.push(n.in(1));
+ while( !work.isEmpty() ) {
+ Node n=work.pop();
+ if( pointer(n) || n instanceof ConstantNode || n instanceof CFGNode ||
+ n instanceof LoadNode || n.isFunLeaf() ||
+ n instanceof ProjNode || sum._raw.get(n._nid) ) continue;
+ sum._raw.set(n._nid);
+ if( !seen.get(n._nid) ) { seen.set(n._nid); sum._nodes.add(n); }
+ for( Node in : n._inputs ) if( in!=null ) work.push(in);
+ }
+ }
// Post-order work during the Call Graph visit
private void build(Summary sum) {
+ loopFrames(sum);
for( Node n : sum._nodes ) {
// Gather allocation sites
if( n instanceof NewNode alloc ) {
if( !(alloc.size()._type instanceof TypeInteger size) || !size.isConstant() )
sum.reject("variable-size allocation #"+alloc._nid);
- Site site = new Site(alloc,0,"new#"+alloc._nid+":"+alloc._ts._name);
+ Site site = new Site(sum,alloc,0,"new#"+alloc._nid+":"+alloc._ts._name);
+ site._birth=(CFGNode)alloc.ctrl();
if( TypeStruct.startsClzPrefix(alloc._ts._name) ) site._owners.set(STATIC);
sum._sites.add(site);
sum._values.put(alloc,set(site));
}
if( n instanceof ParmNode parm && pointer(parm) ) {
if( parm.fun()!=sum._fun ) sum.reject("foreign parameter #"+parm._nid);
- Site site = new Site(null,parm._idx,"arg"+parm._idx+":"+parm.label());
+ while( sum._destinations.size()<=parm._idx )
+ sum._destinations.add("arg"+sum._destinations.size());
+ Site site = new Site(sum,null,parm._idx,"arg"+parm._idx+":"+parm.label());
sum._sites.add(site);
sum._values.put(parm,set(site));
}
+ if( n instanceof LoadNode && pointer(n) ) sum._pathLimit++;
}
- for( CallNode call : sum._calls ) compose(sum,call);
- for( Node n : sum._nodes ) {
- if( n instanceof StoreNode store && pointer(store.val()) ) {
- Set<Site> dst = refs(sum,store.ptr()), src=refs(sum,store.val());
- edge(dst, store._name, src);
+ // Import fresh storage once per call, even though its reference edges
+ // may need several local rounds. No repeated walk of a callee's IR.
+ IdentityHashMap<CallNode,IdentityHashMap<Site,HashSet<Site>>> imports=new IdentityHashMap<>();
+ for( CallNode call : sum._calls ) {
+ if( nativeCall(call) ) continue;
+ Summary callee=target(call);
+ IdentityHashMap<Site,HashSet<Site>> map=new IdentityHashMap<>();
+ imports.put(call,map);
+ sum._results.put(call,new HashSet<>());
+ map.put(callee._static,set(sum._static));
+ int depth=0;
+ for( Site site : callee._sites ) {
+ depth=Math.max(depth,site._depth);
+ if( site==callee._static ) continue;
+ HashSet<Site> values=new HashSet<>();
+ if( site._allocation!=null && !site._owners.isEmpty() ) {
+ Site copy=new Site(sum,site._allocation,0,"call#"+call._nid+"/"+site._name);
+ copy._birth=call;
+ if( site._owners.get(STATIC) ) copy._owners.set(STATIC);
+ sum._sites.add(copy);
+ values.add(copy);
+ }
+ map.put(site,values);
}
+ sum._pathLimit+=depth;
}
- sum._returns.addAll(refs(sum,sum._fun.ret().expr()));
+
+ // Loads, stores, and call effects depend on each other. Solve their weak
+ // unions before assigning owners: caching an early empty load would lose
+ // a later-discovered store. Targets, fields, and call results grow
+ // monotonically, including cyclic loop Phis. Each expression is visited
+ // once per round; a cycle uses the targets discovered so far.
+ do {
+ sum._changed=false;
+ sum._resolved.clear();
+ for( CallNode call : sum._calls ) if( !nativeCall(call) ) compose(sum,call,imports.get(call));
+ for( Node n : sum._nodes ) {
+ if( pointer(n) || sum._raw.get(n._nid) ) refs(sum,n);
+ if( n instanceof StoreNode store && pointer(store.val()) )
+ if( edge(refs(sum,store.ptr()),store._name,refs(sum,store.val())) ) sum._changed=true;
+ }
+ if( pointer(sum._fun.ret().expr()) && sum._returns.addAll(refs(sum,sum._fun.ret().expr())) ) sum._changed=true;
+ } while( sum._changed && sum._reject==null );
for( Site site : sum._returns ) site._owners.set(RESULT);
if( !sum._static._fields.isEmpty() ) sum._sites.add(sum._static);
@@ -232,6 +364,11 @@ public final class Allocation {
if( dst._owners.cardinality() != before ) work.push(dst);
}
}
+ if( sum._reject==null ) {
+ frameBoundaries(sum);
+ summarizeFrame(sum,sum,imports);
+ if( sum._reject==null ) placeFrames(sum);
+ }
// Bin packing goes here: fixed destinations become caller landing zones.
// Free-list work goes here: only after checking remaining usable aliases.
// Parallel growing tips go here: one owner may need several storage areas.
@@ -242,46 +379,301 @@ public final class Allocation {
return n!=null && (n._type instanceof TypeMemPtr || n._type instanceof TypePtr);
}
+ // LoopTree already establishes reducible nesting and each CFG's tightest
+ // containing loop. Allocation only supplies the corresponding frame summaries.
+ private static void loopFrames(Summary sum) {
+ for( Summary frame : sum._loops.values() ) {
+ CFGNode.LoopTree tree=frame._loop._ltree;
+ assert tree!=null && tree._head==frame._loop && tree._par!=null;
+ frame._parent=tree._par._head instanceof StartNode ? sum : sum._loops.get(tree._par._head);
+ assert frame._parent!=null : "Missing enclosing loop summary";
+ frame._parent._frames.add(frame);
+ }
+ }
+
+ // Everything reachable through stored references. Used both for backedge
+ // safety and for retaining a winner's entire object graph on loop exit.
+ private static HashSet<Site> reachable(HashSet<Site> roots) {
+ HashSet<Site> seen=new HashSet<>(roots);
+ ArrayDeque<Site> work=new ArrayDeque<>(roots);
+ while( !work.isEmpty() )
+ for( HashSet<Site> children : work.pop()._fields.values() )
+ for( Site child : children )
+ if( seen.add(child) ) work.push(child);
+ return seen;
+ }
+
+ // A store to storage not born in this iteration can carry its value into
+ // the next iteration. Stores within an iteration's private graph are fine;
+ // a surviving root will bring that entire graph into reachable() instead.
+ private static void retained(HashSet<Site> dst, HashSet<Site> src,
+ HashSet<Site> born, HashSet<Site> carried) {
+ for( Site base : dst )
+ if( !born.contains(base) ) { carried.addAll(src); return; }
+ }
+
+ // Memory reaching the backedge exposes stores that a pointer-Phi check alone
+ // misses, e.g. an array allocated before the loop collecting each candidate.
+ // Stop at this header: entry memory and exit-only stores do not execute on
+ // the repeated path. Weak updates deliberately do not kill earlier stores.
+ private static ArrayList<Node> backMemory(LoopNode loop) {
+ ArrayList<Node> nodes=new ArrayList<>();
+ BitSet seen=new BitSet();
+ ArrayDeque<Node> work=new ArrayDeque<>();
+ for( Node use : loop._outputs )
+ if( use instanceof PhiNode phi && phi.region()==loop && phi._type instanceof TypeMem )
+ work.push(phi.in(2));
+ while( !work.isEmpty() ) {
+ Node n=work.pop();
+ if( seen.get(n._nid) ) continue;
+ seen.set(n._nid);
+ if( n instanceof PhiNode phi && phi.region()==loop ) continue;
+ if( n instanceof ParmNode || n.isFunLeaf() ) continue;
+ nodes.add(n);
+ if( n instanceof ProjNode proj ) work.push(proj.in(0));
+ else if( n instanceof CallEndNode end ) work.push(end.call());
+ else for( Node in : n._inputs )
+ if( in!=null && in._type instanceof TypeMem ) work.push(in);
+ }
+ return nodes;
+ }
+
+ private static Summary enclosing(Summary sum, CFGNode ctrl) {
+ if( ctrl==null || ctrl._type.isHigh() ) return sum;
+ assert ctrl._ltree!=null : "Missing LoopTree for CFG #"+ctrl._nid;
+ if( ctrl._ltree._head instanceof StartNode ) return sum;
+ Summary frame=sum._loops.get(ctrl._ltree._head);
+ assert frame!=null : "Missing loop summary for CFG #"+ctrl._nid;
+ return frame;
+ }
+
+ // Earliest control for a boundary value/use, without scheduling or changing
+ // the IR. New's pointer AND private-memory projections inherit its control.
+ // Floating scalar calculations can finish before returning from a frame;
+ // only their scalar result then crosses the boundary.
+ private static CFGNode control(Node n, IdentityHashMap<Node,CFGNode> cache, BitSet active) {
+ if( n instanceof CFGNode cfg ) return cfg;
+ if( n instanceof PhiNode phi ) return phi.region();
+ if( n.isFunLeaf() ) return null;
+ if( cache.containsKey(n) ) return cache.get(n);
+ if( active.get(n._nid) ) return CFGNode.safeCFG(n);
+ active.set(n._nid);
+ CFGNode ctrl=null;
+ for( Node in : n._inputs )
+ if( in!=null ) ctrl=CFGNode.deepest(ctrl,control(in,cache,active));
+ active.clear(n._nid);
+ cache.put(n,ctrl);
+ return ctrl;
+ }
+
+ // Export a value from its producing activation to the common ancestor,
+ // then capture it down to the consuming activation. These explicit ports,
+ // not a later placement scan of uses, define what must survive cleanup.
+ private static void crossing(Node value, Summary from, Summary to) {
+ Summary common=from;
+ while( true ) {
+ Summary up=to;
+ while( up!=null && up!=common ) up=up._parent;
+ if( up!=null ) break;
+ common=common._parent;
+ }
+ for( Summary frame=from; frame!=common; frame=frame._parent ) frame._exit.put(value,value);
+ for( Summary frame=to; frame!=common; frame=frame._parent ) frame._entry.put(value,value);
+ }
+
+ // Build the function/iteration interfaces in the existing SSA vocabulary.
+ // A loop's backedge is a return into its next activation, with Phi inputs
+ // supplying the arguments. Breaks/fallout export through the normal interface.
+ private void frameBoundaries(Summary sum) {
+ IdentityHashMap<Node,CFGNode> controls=new IdentityHashMap<>();
+ BitSet active=new BitSet();
+ for( Site site : sum._sites ) if( site._birth!=null ) {
+ site._frame=enclosing(sum,site._birth);
+ for( Summary frame=site._frame; frame!=sum; frame=frame._parent ) frame._sites.add(site);
+ }
+ for( Summary frame : sum._loops.values() )
+ for( Node use : frame._loop._outputs )
+ if( use instanceof PhiNode phi && phi.region()==frame._loop ) {
+ frame._entry.put(phi,phi.in(1));
+ frame._next.put(phi,phi.in(2));
+ }
+ sum._exit.put(sum._fun.ret(),sum._fun.ret().expr());
+ sum._exit.put(sum._fun.ret().mem(),sum._fun.ret().mem());
+ for( Node n : sum._nodes ) if( n instanceof ParmNode ) sum._entry.put(n,n);
+ if( sum._loops.isEmpty() ) return;
+ for( Node n : sum._nodes ) {
+ boundaryInputs(sum,n,controls,active);
+ // collect() skips scalar arithmetic. Merge Phis still define exit
+ // ports, including scalar results loaded from reclaimed scratch.
+ if( n instanceof CFGNode )
+ for( Node use : n._outputs )
+ if( use instanceof PhiNode phi && phi.region()==n ) boundaryInputs(sum,phi,controls,active);
+ }
+ // Scalar users were deliberately omitted by collect(). Their pointer
+ // operands still need boundary ports (e.g. a load after an outside call).
+ for( var value : sum._values.entrySet() ) {
+ Node n=value.getKey();
+ if( !pointer(n) || n instanceof ConstantNode ) continue;
+ Summary producer=enclosing(sum,control(n,controls,active));
+ for( Node use : n._outputs ) {
+ if( use.isFunLeaf() || use instanceof PhiNode phi && phi.region() instanceof LoopNode ) continue;
+ crossing(n,producer,enclosing(sum,control(use,controls,active)));
+ }
+ }
+ }
+
+ private static void boundaryInputs(Summary sum, Node n, IdentityHashMap<Node,CFGNode> controls, BitSet active) {
+ if( n.isFunLeaf() || n instanceof PhiNode phi && phi.region() instanceof LoopNode ) return;
+ Summary consumer=enclosing(sum,control(n,controls,active));
+ for( Node in : n._inputs ) {
+ if( in==null || in instanceof ConstantNode || in instanceof CFGNode ) continue;
+ // Ordinary integer users do not extend the borrowing scope. Only
+ // the endpoint and its expression carry raw-address obligations.
+ if( sum._raw.get(in._nid) &&
+ !(n instanceof KeepAliveNode) && !sum._raw.get(n._nid) ) continue;
+ crossing(in,enclosing(sum,control(in,controls,active)),consumer);
+ }
+ }
+
+ // The same summary closure for function returns and loop exits. Effects on
+ // incoming storage escape the frame even without a returned pointer. Loops
+ // additionally describe the continuation's values and memory effects.
+ private void summarizeFrame(Summary sum, Summary frame,
+ IdentityHashMap<CallNode,IdentityHashMap<Site,HashSet<Site>>> imports) {
+ frame._state=1;
+ for( Summary child : frame._frames ) {
+ summarizeFrame(sum,child,imports);
+ if( child._reject!=null ) frame.reject(child._reject);
+ }
+ HashSet<Site> born=new HashSet<>();
+ for( Site site : frame._sites ) if( site._allocation!=null ) born.add(site);
+ for( Node value : frame._exit.values() )
+ if( frame._loop!=null || pointer(value) ) frame._returns.addAll(refs(sum,value));
+ for( Site site : sum._sites )
+ if( !born.contains(site) )
+ for( HashSet<Site> children : site._fields.values() ) frame._retained.addAll(children);
+ frame._escapes.addAll(frame._returns);
+ frame._escapes.addAll(frame._retained);
+ // Static allocations retain their absolute lifetime across substitution.
+ for( Site site : born ) if( site._owners.get(STATIC) ) frame._escapes.add(site);
+ frame._escapes.addAll(reachable(frame._escapes));
+ if( frame._loop!=null ) {
+ for( var port : frame._next.entrySet() )
+ if( pointer(port.getKey()) || sum._raw.get(port.getKey()._nid) )
+ frame._continues.addAll(refs(sum,port.getValue()));
+ for( Node n : backMemory(frame._loop) ) {
+ if( n instanceof StoreNode store && pointer(store.val()) )
+ retained(refs(sum,store.ptr()),refs(sum,store.val()),born,frame._continues);
+ if( n instanceof CallNode call && !nativeCall(call) ) {
+ var map=imports.get(call);
+ for( Site site : target(call)._sites )
+ for( HashSet<Site> children : site._fields.values() )
+ for( Site child : children ) retained(map.get(site),map.get(child),born,frame._continues);
+ }
+ }
+ frame._continues.addAll(reachable(frame._continues));
+ for( Site site : frame._continues )
+ if( born.contains(site) ) {
+ frame.reject(frame.name()+" carries "+site._name+" across its backedge; collection/overlap destinations not implemented");
+ break;
+ }
+ }
+ frame._state=2;
+ }
+
+ // Function and iteration cleanup use the same rule. Promote escaped storage
+ // to the enclosing frame until its interface no longer exports that storage.
+ // A function's external results already have symbolic owner requirements.
+ // No RSP adjustment or actual reclamation is emitted by this planning pass.
+ private static void placeFrames(Summary sum) {
+ for( Site site : sum._sites ) if( site._frame!=null ) {
+ Summary scope=site._frame;
+ while( scope!=null && scope._escapes.contains(site) ) scope=scope._parent;
+ site._scope=scope;
+ if( scope!=null ) scope._scratch.add(site);
+ }
+ }
+
// One element Set of Site
private static HashSet<Site> set(Site site) {
HashSet<Site> set = new HashSet<>(); set.add(site); return set;
}
- private static void edge(Set<Site> dst, String field, Set<Site> src) {
- if( src.isEmpty() ) return;
+ private static boolean edge(HashSet<Site> dst, String field, HashSet<Site> src) {
+ if( src.isEmpty() ) return false;
+ boolean changed=false;
for( Site site : dst )
- site._fields.computeIfAbsent(field,k -> new HashSet<>()).addAll(src);
+ changed |= site._fields.computeIfAbsent(field,k -> new HashSet<>()).addAll(src);
+ return changed;
}
+ // Select a field's possible values, not its containing object's storage.
+ // Fresh objects have only the stores we see. Borrowed objects also have an
+ // incoming value, named by a path. That path is a separate borrowed Site,
+ // substituted against the actual object's fields at each call.
+ private HashSet<Site> field(Summary sum, HashSet<Site> bases, String name) {
+ HashSet<Site> values=new HashSet<>();
+ for( Site base : bases ) {
+ if( base._allocation==null ) {
+ Site child=base._loads.get(name);
+ if( child==null ) {
+ // Weak updates can invent an unbounded path even in straight
+ // line code: p.next=p.next.next. Stop at the body's finite
+ // read count rather than silently truncate possible origins.
+ // Memory-ordered field updates go here.
+ if( base._depth>=sum._pathLimit ) {
+ sum.reject("cyclic field-path expansion at "+base._name+"."+name);
+ continue;
+ }
+ String path=(base._arg>=2 ? "arg"+base._arg : base._name)+"."+name;
+ child=new Site(sum,null,0,path);
+ child._base=base; child._field=name; child._depth=base._depth+1;
+ if( base==sum._static || base._owners.get(STATIC) ) child._owners.set(STATIC);
+ else {
+ child._owners.set(sum._destinations.size());
+ sum._destinations.add(path);
+ }
+ base._loads.put(name,child);
+ sum._sites.add(child);
+ sum._changed=true;
+ }
+ values.add(child);
+ }
+ Set<Site> stored=base._fields.get(name);
+ if( stored!=null ) values.addAll(stored);
+ }
+ return values;
+ }
// Which storage objects can this pointer expression denote? This resolves
// pointer VALUE flow, not the fields reachable through the pointer. A Phi
// unions possible targets; casts/views preserve targets; a call result uses
- // compose's caller-side targets. New/Parm targets were seeded by build.
+ // compose's caller-side targets; a load selects one field's targets.
+ // New/Parm targets were seeded by build.
// Example: refs(cond ? a : b) = {site(a), site(b)}.
// build() uses these sets to add Store edges, then propagates owner requirements
- // through that separate object graph. Object cycles are handled there;
- // _resolving rejects cyclic SSA values (loop Phi support is future work).
+ // through that separate object graph. Cyclic SSA values use the prior known
+ // targets; the next local round propagates any newly discovered ones.
private HashSet<Site> refs(Summary sum, Node n) {
- if( !pointer(n) ) return new HashSet<>();
- HashSet<Site> old = sum._values.get(n);
- if( old!=null ) return old;
+ if( n==null || !(pointer(n) || sum._raw.get(n._nid)) ) return new HashSet<>();
+ HashSet<Site> old = sum._values.computeIfAbsent(n,k -> new HashSet<>());
+ if( n instanceof ParmNode || sum._resolved.get(n._nid) ) return old;
+ sum._resolved.set(n._nid);
HashSet<Site> values = new HashSet<>();
- if( sum._resolving.get(n._nid) ) {
- sum.reject("cyclic reference value #"+n._nid);
- return values;
- }
- sum._resolving.set(n._nid);
if( n instanceof ConstantNode ) {
// Zero/null carries no storage obligation. Other constant objects
- // have static backing; references loaded from them are not guessed.
+ // have static backing; field() handles their incoming contents.
if( n._type!=Type.NIL && n._type!=TypeInteger.ZERO ) values.add(sum._static);
} else if( n instanceof ProjNode proj && proj.in(0) instanceof NewNode alloc && proj._idx==0 ) {
Set<Site> sites = sum._values.get(alloc);
if( sites==null ) sum.reject("foreign allocation #"+alloc._nid);
else values.addAll(sites);
} else if( n instanceof ProjNode proj && proj.in(0) instanceof CallEndNode end && proj._idx==2 ) {
- values.addAll(compose(sum,end.call()));
+ Set<Site> result=sum._results.get(end.call());
+ if( result==null ) sum.reject("foreign call #"+end.call()._nid);
+ else values.addAll(result);
+ } else if( n instanceof LoadNode load ) {
+ values.addAll(field(sum,refs(sum,load.ptr()),load._name));
} else if( n instanceof PhiNode phi && !(phi instanceof ParmNode) ) {
for( int i=1; i<n.nIns(); i++ )
if( !phi.region().in(i)._type.isHigh() ) values.addAll(refs(sum,n.in(i)));
@@ -290,108 +682,165 @@ public final class Allocation {
values.addAll(refs(sum,n.in(1)));
} else if( n instanceof ArrayInitNode ) {
values.addAll(refs(sum,n.in(2)));
+ } else if( sum._raw.get(n._nid) ) {
+ for( Node in : n._inputs ) values.addAll(refs(sum,in));
} else {
- // Field-path/array-element origins go here. A parameter's child may
- // have a different owner; never silently substitute the base owner.
sum.reject("reference origin "+n.getClass().getSimpleName()+" #"+n._nid);
}
- sum._resolving.clear(n._nid);
- sum._values.put(n,values);
- return values;
+ if( old.addAll(values) ) sum._changed=true;
+ return old;
}
// Apply an already-built callee summary to this particular call. Translate
// callee Sites into caller Sites: formal -> refs(actual), static -> static,
- // escaping allocation -> fresh Site tagged with this call. This copies
- // analysis objects, not runtime objects or IR. Private callee scratch stays
- // in the callee. A second call gets distinct Sites for its fresh allocations.
+ // borrowed field -> actual field targets. Fresh Sites were imported once by
+ // build, tagged with this call. Private callee scratch stays in the callee.
+ // A second call gets distinct Sites for its fresh allocations.
// Then translate field edges and returned targets through the same map.
// For helper(h) { h.c = new Thing; }, calling helper(a) adds a.c -> call/new.
// The map values are SETS because an actual may select several objects.
// Callee result/argument owner bits are relative to its signature; do not
// copy them into the caller. build's closure derives the caller's owners
// from the translated edges and uses of the result. Only static is absolute.
- private HashSet<Site> compose(Summary sum, CallNode call) {
- HashSet<Site> result=sum._results.get(call);
- if( result!=null ) return result;
- result=new HashSet<>();
- sum._results.put(call,result);
+ private void compose(Summary sum, CallNode call, IdentityHashMap<Site,HashSet<Site>> map) {
Summary callee=target(call);
- if( callee==null || !callee.supported() ) {
- sum.reject("unavailable allocation summary at call #"+call._nid);
- return result;
- }
- IdentityHashMap<Site,HashSet<Site>> map=new IdentityHashMap<>();
- map.put(callee._static,set(sum._static));
- // Establish all substitutions first, so forward/cyclic field edges can
- // be copied without depending on Site visitation order.
+ // Grow substitutions before transferring edges. A later local round
+ // resolves forward references and aliasing actuals. For example, after
+ // f(a,b) { a.c=new Thing; return b.c; }, f(h,h) returns that new Thing too.
for( Site site : callee._sites ) {
if( site._arg>=2 ) {
- if( site._arg>=call.nIns()-1 ) {
+ if( site._arg>=call.nIns()-1 )
sum.reject("missing argument at call #"+call._nid);
- map.put(site,new HashSet<>());
- } else map.put(site,refs(sum,call.arg(site._arg)));
- } else if( site._allocation!=null && !site._owners.isEmpty() ) {
- Site copy=new Site(site._allocation,0,"call#"+call._nid+"/"+site._name);
- // Return/argument owners are substituted by edges in this caller.
- if( site._owners.get(STATIC) ) copy._owners.set(STATIC);
- sum._sites.add(copy);
- map.put(site,set(copy));
- }
+ else if( map.get(site).addAll(refs(sum,call.arg(site._arg))) ) sum._changed=true;
+ } else if( site._base!=null )
+ if( map.get(site).addAll(field(sum,map.get(site._base),site._field)) ) sum._changed=true;
}
// Retention effects exist even when the function returns a scalar.
for( Site site : callee._sites ) {
- Set<Site> dst=map.get(site);
- if( dst==null ) continue;
+ HashSet<Site> dst=map.get(site);
+ if( dst.isEmpty() ) continue;
for( var field : site._fields.entrySet() ) for( Site child : field.getValue() ) {
- Set<Site> src=map.get(child);
+ HashSet<Site> src=map.get(child);
if( src==null ) sum.reject("unmapped retained storage at call #"+call._nid);
- else edge(dst,field.getKey(),src);
+ else sum._changed |= edge(dst,field.getKey(),src);
}
}
for( Site site : callee._returns ) {
Set<Site> returned=map.get(site);
if( returned==null ) sum.reject("unmapped returned storage at call #"+call._nid);
- else result.addAll(returned);
+ else sum._changed |= sum._results.get(call).addAll(returned);
}
- return result;
+ }
+
+ // Printing has its own rooted traversal: reversing the analysis's entire
+ // forest would put disconnected bodies (e.g. inlined constructors) first.
+ private void printPostorder(Summary sum, BitSet seen, ArrayList<Summary> post) {
+ if( sum==null || seen.get(sum._fun._nid) ) return;
+ seen.set(sum._fun._nid);
+ ArrayList<CallNode> calls=new ArrayList<>(sum._calls);
+ calls.sort(Comparator.comparingInt(n -> n._nid));
+ for( CallNode call : calls ) printPostorder(target(call),seen,post);
+ post.add(sum);
}
@Override public String toString() {
StringBuilder out = new StringBuilder("Allocation destinations (analysis only; no stack lowering)\n");
- for( Summary sum : _postorder ) {
+ BitSet seen=new BitSet();
+ ArrayList<Summary> order=new ArrayList<>();
+ printPostorder(_entrySummary,seen,order);
+ Collections.reverse(order);
+ int reachable=order.size();
+ ArrayList<Summary> other=new ArrayList<>();
+ for( Summary sum : _summaries ) printPostorder(sum,seen,other);
+ Collections.reverse(other);
+ order.addAll(other);
+ for( int i=0; i<order.size(); i++ ) {
+ if( i==reachable && _entrySummary!=null )
+ out.append("\nOther retained functions (not reachable by direct calls from entry):\n");
+ Summary sum=order.get(i);
out.append("\n+-- ").append(sum._fun.label()).append("\n");
ArrayList<CallNode> calls=new ArrayList<>(sum._calls);
calls.sort(Comparator.comparingInt(n -> n._nid));
for( CallNode call : calls ) {
Summary callee=target(call);
out.append("| call#").append(call._nid).append(" -> ")
- .append(callee==null ? "?" : callee._fun.label()).append("\n");
+ .append(callee==null ? nativeCall(call) ? "native (borrow; no retain)" : "?" : callee._fun.label()).append("\n");
}
if( !sum.supported() ) {
out.append("`-- REJECT: ").append(sum._reject).append("\n");
continue; // Do not display a partial plan as a safe placement.
}
- ArrayList<Site> sites=new ArrayList<>(sum._sites);
- sites.sort(Comparator.comparing(s -> s._name));
- for( Site site : sites ) {
- out.append("| [").append(site.destination()).append("] ").append(site._name);
- if( site._allocation!=null ) out.append(" (").append(site._bytes).append(" bytes)");
- out.append("\n");
- // Stable debugging order belongs here, not in the analysis maps.
- ArrayList<String> edges=new ArrayList<>();
- for( var field : site._fields.entrySet() ) for( Site child : field.getValue() )
- edges.add("| ."+field.getKey()+" --> "+child._name+"\n");
- Collections.sort(edges);
- for( String edge : edges ) out.append(edge);
- }
- out.append("`-- return");
- ArrayList<String> returns=new ArrayList<>();
- for( Site site : sum._returns ) returns.add(site._name);
- Collections.sort(returns);
- for( String name : returns ) out.append(" -> ").append(name);
- out.append("\n");
+ printFrames(out,sum,"| ");
+ printStorage(out,sum,"| ");
+ printSites(out,"| cleanup on return -> ",sum._scratch);
+ printSites(out,"`-- return -> ",sum._returns," | ");
}
return out.toString();
}
+
+ // Show storage in its owning frame, which may enclose its allocation site.
+ // Borrowed/external destinations remain at function level.
+ private static void printStorage(StringBuilder out, Summary frame, String indent) {
+ ArrayList<Site> sites=new ArrayList<>();
+ for( Site site : frame._sites )
+ if( site._scope==frame || (frame._loop==null && site._scope==null) ) sites.add(site);
+ sites.sort(Comparator.comparing(s -> s._name));
+ for( Site site : sites ) {
+ out.append(indent).append('[').append(site.destination()).append("] ").append(site._name);
+ if( site._allocation!=null ) out.append(" (").append(site._bytes).append(" bytes)");
+ if( site._frame!=null && site._frame._loop!=null && site._scope!=site._frame )
+ out.append("; ").append(site._frame.name()).append(" winner");
+ out.append('\n');
+ ArrayList<String> edges=new ArrayList<>();
+ for( var field : site._fields.entrySet() ) for( Site child : field.getValue() )
+ edges.add(indent+" ."+field.getKey()+" --> "+child._name+"\n");
+ Collections.sort(edges);
+ for( String edge : edges ) out.append(edge);
+ }
+ }
+
+ private static void printSites(StringBuilder out, String label, HashSet<Site> sites) {
+ printSites(out,label,sites,", ");
+ }
+ private static void printSites(StringBuilder out, String label, HashSet<Site> sites, String separator) {
+ out.append(label).append('{');
+ ArrayList<String> names=new ArrayList<>();
+ for( Site site : sites ) names.add(site._name);
+ Collections.sort(names);
+ for( int i=0; i<names.size(); i++ ) {
+ if( i>0 ) out.append(separator);
+ out.append(names.get(i));
+ }
+ out.append("}\n");
+ }
+
+ private static void printPorts(StringBuilder out, String label, IdentityHashMap<Node,Node> ports) {
+ out.append(label).append('{');
+ ArrayList<Node> keys=new ArrayList<>(ports.keySet());
+ keys.sort(Comparator.comparingInt(n -> n._nid));
+ for( int i=0; i<keys.size(); i++ ) {
+ Node port=keys.get(i), value=ports.get(port);
+ if( i>0 ) out.append(", ");
+ out.append(port.label()).append('#').append(port._nid);
+ if( port!=value ) out.append(" <- ").append(value.label()).append('#').append(value._nid);
+ }
+ out.append("}\n");
+ }
+
+ private static void printFrames(StringBuilder out, Summary parent, String indent) {
+ ArrayList<Summary> frames=new ArrayList<>(parent._frames);
+ frames.sort(Comparator.comparingInt(s -> s._loop._nid));
+ for( Summary frame : frames ) {
+ out.append(indent).append("+-- ").append(frame.name()).append(" frame; parent ").append(parent.name()).append('\n');
+ printPorts(out,indent+"| entry -> ",frame._entry);
+ printPorts(out,indent+"| continue values -> ",frame._next);
+ printSites(out,indent+"| continue refs -> ",frame._continues);
+ printPorts(out,indent+"| exit values -> ",frame._exit);
+ printSites(out,indent+"| return refs -> ",frame._returns);
+ printSites(out,indent+"| retain -> ",frame._retained);
+ printStorage(out,frame,indent+"| ");
+ printFrames(out,frame,indent+"| ");
+ printSites(out,indent+"`-- cleanup on continue and return -> ",frame._scratch);
+ }
+ }
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
index f38305b2..3db16f8b 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
@@ -16,6 +16,7 @@ public class CodeGen {
// Last created CodeGen as a global; used all over to avoid passing about a "context".
public static CodeGen CODE;
+ private final long _typeGeneration;
// Location of built-in CPU ports
public static final String PORTS = "com.seaofnodes.simple.node.cpus";
@@ -27,11 +28,11 @@ public class CodeGen {
Opto, // SCCP, numeric modes, seed the peephole worklist
IterPostOpto, // Peepholes and inlining using SCCP results
FinalizeIR, // Field layout, offset cleanup, function/CU roots
+ LoopTree, // Containing loops for allocation analysis
Allocation, // Symbolic allocation destinations; analysis only
TypeCheck, // Last check for bad programs
Serialize, // Save ideal IR, including opaque class initialization
Lower, // Expand checked class initialization to ordinary IR
- LoopTree, // Build a loop tree; break infinite loops
Unlink, // Unlink call sites before machine code generation
Select, // Convert to target hardware nodes
Schedule, // Global schedule (code motion) nodes
@@ -136,6 +137,7 @@ public class CodeGen {
// of places. Probably becomes a TLS at some point.
CODE = this;
if( resetTypes ) Type.reset(); // Reset to recover from failed test
+ _typeGeneration = Type.resetGeneration();
_cwd = System.getProperty("user.dir")+"/";
_modDir = modDir == null ? _cwd : modDir;
@@ -197,6 +199,7 @@ public class CodeGen {
step(target, Phase.IterPostOpto, this::iterPostOpto, dump);
// Field layouts; field symbols become constant offsets
step(target, Phase.FinalizeIR, this::finalizeIR, dump);
+ step(target, Phase.LoopTree, this::loopTree, dump);
step(target, Phase.Allocation, this::allocation, dump);
// Final error check - bad programs fail here
step(target, Phase.TypeCheck, this::typeCheck, dump);
@@ -205,9 +208,6 @@ public class CodeGen {
// Eval2 executes ideal operations, including CLInit, directly. Only
// machine compilation expands them before scheduling.
step(target, Phase.Lower, () -> { if( cpu!=null ) lower(); }, dump);
- // Compute the loop-tree, used for approximating exec frequencies for
- // scheduling and register allocation
- step(target, Phase.LoopTree, this::loopTree, dump);
// Detach call-graph edges; ideal execution retains unloaded summaries
// as dispatch targets and schedules their bodies on first use.
step(target, Phase.Unlink, () -> unlink(cpu!=null), dump);
@@ -522,14 +522,15 @@ public class CodeGen {
// Last check for bad programs
public Allocation _allocation;
public CodeGen allocation() {
- return phase(Phase.Allocation, _phase==Phase.FinalizeIR, () -> {
+ if( _phase==Phase.FinalizeIR ) loopTree();
+ return phase(Phase.Allocation, _phase==Phase.LoopTree, () -> {
_allocation = new Allocation(this);
if( Boolean.getBoolean("simple.alloc.dump") ) System.out.print(_allocation);
if( Boolean.getBoolean("simple.alloc.check") ) _allocation.requireSupported();
});
}
public CodeGen typeCheck() {
- if( _phase==Phase.FinalizeIR ) allocation();
+ if( _phase==Phase.FinalizeIR || _phase==Phase.LoopTree ) allocation();
return phase(Phase.TypeCheck, _phase==Phase.Allocation, () -> TypeCheck.run(this));
}
@@ -540,10 +541,11 @@ public class CodeGen {
}
// ---------------------------
- // Build the loop tree; break never-exit loops
+ // Build containing loops without changing control flow before TypeCheck
+ // and serialization. Scheduling adds exits to zero-exit loops later.
public CodeGen loopTree() {
- return phase(Phase.LoopTree, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize),
- () -> _start.buildLoopTree(_linker,_stop));
+ return phase(Phase.LoopTree, _phase==Phase.FinalizeIR,
+ () -> _start.buildLoopTree(_linker,_stop,false));
}
// ---------------------------
@@ -584,7 +586,11 @@ public class CodeGen {
unlink(true);
}
private void unlink(boolean removeImports) {
- phase(Phase.Unlink, _phase==Phase.LoopTree, () -> {
+ phase(Phase.Unlink, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize), () -> {
+ KeepAliveNode.erase(_start);
+ // Lower can change CFG membership. Rebuild for scheduling, now
+ // including synthetic exits for loops with no exits at all.
+ _start.rebuildLoopTree(_linker,_stop);
_start.setDef(2,null); // Releases the compiler-only escape analysis.
if( removeImports ) Unlink.run(this,true);
else Unlink.forEval(this,_start,_stop);
@@ -815,6 +821,8 @@ public class CodeGen {
// Debugging helper
@Override public String toString() {
+ if( _typeGeneration != Type.resetGeneration() )
+ return "IR unavailable: shared types were reset after this compilation.";
if( _stop == null )
return "No StopNode";
return IRPrinter.prettyPrint(this);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
index 9c43e029..0e61e434 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
@@ -106,7 +106,8 @@ public class Serialize {
// A - Print the C0DE header; last byte is the version number.
// Format 2: gradual packed ints, UTF-8 strings, sparse MemMerge edges,
// and wider singleton function IDs. Reject old cached objects clearly.
- baos.write('C').write('0').write('D').write('2');
+ // Format 3 retains lexical raw-address lifetime endpoints in bodies.
+ baos.write('C').write('0').write('D').write('3');
// Count unique Types
var types = new HashMap<Type,Integer>();
@@ -335,7 +336,7 @@ public class Serialize {
Type.TAGOFFS();
// A - Read a header
- if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='2' )
+ if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='3' )
throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file");
// B - Packed read of #strings, then strings
@@ -368,7 +369,7 @@ public class Serialize {
String[] strs = elf._strs;
if( strs == null ) {
// A - Read a header
- if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != '2' )
+ if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != '3' )
throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" );
// B - Packed read of #strings, then strings
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java
index bb9a6196..bd876a01 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java
@@ -9,6 +9,7 @@ abstract class Unlink {
// Disconnect compiler-only interprocedural edges before scheduling. Keep
// signatures in the linker; runtime calls resolve FIDXs, not graph edges.
static Ary<FunNode> forEval(CodeGen code, StartNode start, StopNode stop) {
+ KeepAliveNode.erase(start);
Ary<Node> nodes = new Ary<>(Node.class);
start.walk(n -> { nodes.add(n); return null; });
Ary<FunNode> funs = new Ary<>(FunNode.class);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java
index ba744dc3..7cbf3f9b 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java
@@ -200,7 +200,34 @@ public abstract class CFGNode extends Node {
// Tag all CFG Nodes with their containing LoopNode; LoopNodes themselves
// also refer to *their* containing LoopNode, as well as have their depth.
// Start contains the function bodies at depth 0; real loops add depth.
+ public void rebuildLoopTree(Ary<FunNode> funs, StopNode stop) {
+ // Reset just these function bodies, not other graphs that Eval2 might
+ // already be executing. Call/Return links are not intraprocedural CFG.
+ BitSet seen=new BitSet();
+ Ary<CFGNode> work=new Ary<>(CFGNode.class);
+ for( FunNode fun : funs )
+ if( fun!=null && !fun.isDead() && !fun._type.isHigh() && fun.summary()==null ) {
+ work.push(fun);
+ if( fun.in(1) instanceof StartCUNode start ) start._pre=0;
+ }
+ while( !work.isEmpty() ) {
+ CFGNode cfg=work.pop();
+ if( seen.get(cfg._nid) ) continue;
+ seen.set(cfg._nid);
+ cfg._pre=0;
+ cfg._ltree=null;
+ if( cfg instanceof ReturnNode ) continue;
+ for( Node use : cfg._outputs )
+ if( use instanceof CFGNode next && !cfg.skip(next) ) work.push(next);
+ }
+ buildLoopTree(funs,stop);
+ }
+
public void buildLoopTree( Ary<FunNode> funs, StopNode stop) {
+ buildLoopTree(funs,stop,true);
+ }
+
+ public void buildLoopTree( Ary<FunNode> funs, StopNode stop, boolean forceExits) {
_ltree = stop._ltree = CodeGen.CODE.XCTRL._ltree = new LoopTree((StartNode)this);
Ary<FunNode> work = new Ary<>(FunNode.class);
@@ -221,17 +248,21 @@ public abstract class CFGNode extends Node {
}
for( int i=0; i<work._len; i++ )
- pre = work.at(i)._bltWalk(pre,work.at(i),stop, post, work);
+ pre = work.at(i)._bltWalk(pre,work.at(i),stop, post, work,forceExits);
post.clear();
}
- int _bltWalk( int pre, FunNode fun, StopNode stop, BitSet post, Ary<FunNode> work ) {
+ int _bltWalk( int pre, FunNode fun, StopNode stop, BitSet post, Ary<FunNode> work, boolean forceExits ) {
// Pre-walked?
if( _pre!=0 ) return pre;
_pre = pre++;
// Seed the function's outer tree before walking its body. Synthetic
// exits can be added before the post-order walk reaches the entry.
- if( this instanceof FunNode ) _ltree = stop._ltree;
+ if( this instanceof FunNode ) {
+ _ltree = stop._ltree;
+ // A zero-exit function's Return is not reachable through control.
+ fun.ret()._ltree = _ltree;
+ }
if( this instanceof ReturnNode ) {
_ltree = fun._ltree;
post.set(_nid);
@@ -243,7 +274,7 @@ public abstract class CFGNode extends Node {
if( skip( usecfg ) ) {
if( usecfg._pre==0 && usecfg instanceof FunNode fun2 && fun2.summary()==null ) work.add( fun2 );
} else
- pre = usecfg._bltWalk( pre, use instanceof FunNode fuse ? fuse : fun, stop, post, work );
+ pre = usecfg._bltWalk( pre, use instanceof FunNode fuse ? fuse : fun, stop, post, work,forceExits );
}
// Post-order work: find innermost loop
@@ -257,16 +288,21 @@ public abstract class CFGNode extends Node {
// Child visited but not post-visited?
if( !post.get(usecfg._nid) ) {
// Must be a backedge to a LoopNode then
+ assert usecfg instanceof LoopNode : "Simple CFGs must be reducible";
ltree = usecfg._ltree = new LoopTree((LoopNode)usecfg);
} else {
// Take child's loop choice, which must exist
ltree = usecfg._ltree;
// If falling into a loop, use the target loop's parent instead
if( ltree._head == usecfg ) {
- if( ltree._par == null )
+ if( ltree._par == null ) {
// This loop never had an If test choose to take its
// exit, i.e. it is a no-exit infinite loop.
- ltree._par = ltree._head.forceExit(fun,stop)._ltree;
+ // Analysis needs its nesting, but a synthetic exit
+ // must not change nonreturning summaries in .simple.
+ if( forceExits ) ltree._head.forceExit(fun,stop);
+ ltree._par = fun._ltree;
+ }
ltree = ltree._par;
}
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java
new file mode 100644
index 00000000..7db31fe3
--- /dev/null
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java
@@ -0,0 +1,102 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.Ary;
+import java.util.BitSet;
+import java.util.ArrayDeque;
+
+/** A lexical lifetime endpoint. This is a control use, not a machine operand.
+ * Kept values may be raw addresses; Allocation follows them back to storage.
+ * Retained in .simple and through inlining; erased before scheduling. */
+public class KeepAliveNode extends CFGNode {
+ public KeepAliveNode(Node ctrl, Node value) { super(ctrl,value); }
+ @Override public Tag serialTag() { return Tag.KeepAlive; }
+ @Override public Type compute() { return in(0)._type; }
+ @Override public Node idealize() {
+ Node value=in(1);
+ if( value._type==TypeInteger.ZERO || value._type==Type.NIL || in(0)._type==Type.XCONTROL ) return in(0);
+ if( in(0) instanceof KeepAliveNode prior && prior.in(1)==value && addDep(prior).nOuts()==1 ) return prior;
+ // Pending parser edges count as uses too. Drop an expression only when
+ // none of its parts has a use outside the fences.
+ if( unused(value) ) return in(0);
+ return null;
+ }
+
+ private boolean unused(Node value) {
+ BitSet seen=new BitSet();
+ Ary<Node> nodes=new Ary<>(Node.class);
+ ArrayDeque<Node> work=new ArrayDeque<>();
+ work.push(value);
+ while( !work.isEmpty() ) {
+ Node n=work.pop();
+ if( n==null || n instanceof ConstantNode || n instanceof CFGNode || seen.get(n._nid) ) continue;
+ seen.set(n._nid);
+ nodes.add(n);
+ // Only inspect the address expression, not the object's fields or
+ // the allocation's memory. The pointer is the endpoint of tracing.
+ if( n instanceof PtrToIntNode ) continue;
+ if( n._type instanceof TypeMemPtr || n.isFunLeaf() ) return false;
+ for( Node in : n._inputs ) if( in!=null ) work.push(in);
+ }
+ for( Node n : nodes ) for( Node use : addDep(n)._outputs )
+ if( use==null || !(use instanceof KeepAliveNode) && !seen.get(use._nid) ) return false;
+ return true;
+ }
+
+ /** Parser-only accumulation of lifetime obligations. A scalar token lets
+ * ordinary Phis merge branches and loops; it is never evaluated as a number.
+ * Both inputs survive: replacing a variable must not forget its old object. */
+ public static class Values extends Node {
+ public Values(Node prior, Node value) { super(null,prior,value); }
+ @Override public Tag serialTag() { return Tag.KeepValues; }
+ @Override public Type compute() { return TypeInteger.BOT; }
+ @Override public Node idealize() {
+ if( in(1)._type==TypeInteger.ZERO ) return in(2);
+ if( in(2)._type==TypeInteger.ZERO || in(1)==in(2) ) return in(1);
+ return null;
+ }
+ }
+
+ public static void erase(StartNode start) {
+ Ary<Node> nodes=new Ary<>(Node.class);
+ BitSet candidates=new BitSet();
+ start.walk(n -> {
+ if( n instanceof KeepAliveNode || n instanceof Values ||
+ n instanceof PhiNode && !(n instanceof ParmNode) ) {
+ nodes.add(n);
+ candidates.set(n._nid);
+ }
+ return null;
+ });
+ boolean hasFence=false;
+ for( Node n : nodes ) if( n instanceof KeepAliveNode || n instanceof Values ) { hasFence=true; break; }
+ if( !hasFence ) return;
+ // GVN can share a pending Phi with an ordinary program Phi. Names do
+ // not distinguish them. Preserve every Phi with a real use, and its
+ // inputs; discard only the subgraph used exclusively by lifetime fences.
+ BitSet live=new BitSet();
+ ArrayDeque<Node> work=new ArrayDeque<>();
+ for( Node n : nodes ) if( !(n instanceof KeepAliveNode) )
+ for( Node use : n._outputs ) if( use==null || !candidates.get(use._nid) ) {
+ work.push(n);
+ break;
+ }
+ while( !work.isEmpty() ) {
+ Node n=work.pop();
+ if( live.get(n._nid) ) continue;
+ live.set(n._nid);
+ assert !(n instanceof Values) : "Lifetime token used as a program value";
+ for( int i=1; i<n.nIns(); i++ )
+ if( n.in(i)!=null && candidates.get(n.in(i)._nid) ) work.push(n.in(i));
+ }
+ // Loaded Eval2 bodies must not GVN into a different executing graph.
+ ConstantNode zero=ConstantNode.raw(TypeInteger.ZERO);
+ zero.setDef(0,start);
+ zero.keep();
+ for( Node n : nodes ) if( !n.isDead() && !live.get(n._nid) )
+ n.subsume(n instanceof KeepAliveNode ? n.in(0) : zero);
+ zero.unkill();
+ CodeGen.CODE.invalidateIDepthCaches();
+ }
+}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java b/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java
index 3688d6ea..6862b25c 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java
@@ -77,7 +77,7 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
New,Never,Not,Or,Parm,Phi,Proj,PtrToInt,
ReadOnly,Return,Region,RoundF32,
Sar,Shl,Shr,Start,StartCU,StopCU,Stop,Store,Sub,
- ToInteger,ToFloat,XCtrl,Xor,F64Bits,F64FromBits,Mod;
+ ToInteger,ToFloat,XCtrl,Xor,F64Bits,F64FromBits,Mod,KeepAlive,KeepValues;
public static final Tag[] VALS = values();
public Node make( BAOS bais, String[] strs, Type[] types, GlobalBits fileAliases, GlobalBits aliases ) {
return switch(this) {
@@ -85,6 +85,8 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
case And -> { int mode=bais.packed1(); assert mode==1; yield new AndNode(null,null,null); }
case Div -> new DivNode(null,null,(byte)bais.packed1());
case Guard -> GuardNode.make(bais);
+ case KeepAlive -> new KeepAliveNode(null,null);
+ case KeepValues -> new KeepAliveNode.Values(null,null);
case If -> new IfNode(null,null);
case Loop -> new LoopNode(null,null,null);
case Minus -> new MinusNode(null,(byte)bais.packed1());
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
index 80d2aa0a..2fa551fb 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
@@ -18,6 +18,14 @@ import java.util.*;
*/
public class ScopeNode extends MemMergeNode {
+ // Parser root for pending lifetime uses. Real edges let Phi replacement
+ // update the pending values, just like the ordinary variable bindings.
+ private static class Pending extends Node {
+ @Override public Type compute() { return Type.BOTTOM; }
+ @Override public Node idealize() { return null; }
+ @Override public boolean eq(Node n) { return this==n; }
+ }
+
/**
* The control is a name that binds to the currently active control
* node in the graph
@@ -52,6 +60,7 @@ public class ScopeNode extends MemMergeNode {
}
public int _lexSize; // Number of Vars in this scope
+ public int _keepSize; // Lifetime scopes outside this lexical scope
}
public final Ary<Kind> _kinds;
// Lexical scope nesting depth
@@ -60,6 +69,8 @@ public class ScopeNode extends MemMergeNode {
// Extra guards; tested predicates and cast results
private final Ary<Node> _guards;
+ private Pending _keeps; // Materialized only when a scope has a real address use
+ private final Ary<Node> _emptyKeeps = new Ary<>(Node.class); // Zeroes and lazy loop sentinels
// A new ScopeNode
public ScopeNode() {
@@ -114,8 +125,66 @@ public class ScopeNode extends MemMergeNode {
public void push( Kind kind ) {
kind._lexSize = _vars.size();
+ kind._keepSize = keepDepth();
_kinds.push(kind);
+ pushKeep();
+ }
+
+ public int keepDepth() { return _keeps==null ? _emptyKeeps.size() : _keeps.nIns(); }
+ private Node keepAt(int i) { return _keeps==null ? _emptyKeeps.at(i) : _keeps.in(i); }
+ private void materializeKeeps(Node value) {
+ if( _keeps!=null || value==CodeGen.CODE.ZERO || value instanceof ScopeNode ) return;
+ _keeps=new Pending().keep();
+ for( Node n : _emptyKeeps ) _keeps.addDef(n);
+ _emptyKeeps.clear();
+ }
+ private void addKeep(Node value) {
+ materializeKeeps(value);
+ if( _keeps==null ) _emptyKeeps.add(value); else _keeps.addDef(value);
+ }
+ public void pushKeep() { addKeep(CodeGen.CODE.ZERO); }
+ private Node setKeep(int i, Node n) {
+ Node old=keepAt(i);
+ if( old!=n ) {
+ materializeKeeps(n);
+ if( _keeps==null ) _emptyKeeps.set(i,n); else _keeps.setDef(i,n);
+ }
+ return n;
+ }
+ private Node getKeep(int i) { return getKeep(i,false); }
+ private Node getKeep(int i, boolean writing) {
+ Node old=keepAt(i);
+ if( old instanceof ScopeNode loop ) {
+ Node def=loop.getKeep(i,writing);
+ // Reading an empty obligation needs no loop Phi. A conversion
+ // must create one before adding its address to this iteration.
+ if( def==CodeGen.CODE.ZERO && !writing ) return def;
+ old=def instanceof PhiNode phi && loop.ctrl()==phi.region() ? def :
+ loop.setKeep(i,new PhiNode("$keep",loop.ctrl(),def,null).init());
+ setKeep(i,old);
+ }
+ return old;
+ }
+ public void keepValue(Node value) {
+ int i=keepDepth()-1;
+ setKeep(i,new KeepAliveNode.Values(getKeep(i,true),value).peephole());
+ }
+ // Flush just the scopes being exited; outer obligations remain pending.
+ public void endKeeps(int first) {
+ for( int i=keepDepth()-1; i>=first; i-- ) {
+ if( ctrl()._type!=Type.XCONTROL ) {
+ Node value=getKeep(i);
+ if( value._type!=TypeInteger.ZERO )
+ ctrl(new KeepAliveNode(ctrl(),value).peephole());
+ }
+ setKeep(i,CodeGen.CODE.ZERO);
+ }
}
+ public void popKeepsTo(int size) {
+ endKeeps(size);
+ if( _keeps==null ) _emptyKeeps.setLen(size); else _keeps.popUntil(size);
+ }
+ public void popKeep() { popKeepsTo(keepDepth()-1); }
// Pop a lexical scope
public void pop() {
@@ -124,7 +193,9 @@ public class ScopeNode extends MemMergeNode {
}
// Pop a scope, no promote FRefs
public void _pop() {
- int n = _kinds.pop()._lexSize;
+ Kind kind=_kinds.pop();
+ popKeepsTo(kind._keepSize);
+ int n = kind._lexSize;
popUntil(n); // Pop off inputs going out of scope
_vars.setLen(n); // Pop off variables going out of scope
}
@@ -352,6 +423,7 @@ public class ScopeNode extends MemMergeNode {
dup._vars .addAll(_vars );
dup._kinds .addAll(_kinds );
dup._guards .addAll(_guards );
+ for( int i=0; i<keepDepth(); i++ ) dup.addKeep(loop ? this : keepAt(i));
// The dup'd guards all need dup'd keepers, to keep proper accounting
// when later removing all guards
for( Node n : _guards )
@@ -391,6 +463,11 @@ public class ScopeNode extends MemMergeNode {
_merge(that,r,nIns());
}
public void _merge(ScopeNode that, RegionNode r, int max ) {
+ for( int i=0; i<keepDepth(); i++ ) {
+ if( keepAt(i)==that.keepAt(i) ) continue;
+ Node lhs=getKeep(i), rhs=that.getKeep(i);
+ if( lhs!=rhs ) setKeep(i,new PhiNode("$keep",r,lhs,rhs).peephole());
+ }
for( int i = 1; i < max; i++)
if( in(i) != that.in(i) ) { // No need for redundant Phis
// If we are in lazy phi mode we need to a lookup
@@ -446,10 +523,23 @@ public class ScopeNode extends MemMergeNode {
back.kill(); // Loop backedge is dead
// Now one-time do a useless-phi removal
this._useless();
+ for( int i=0; i<keepDepth(); i++ )
+ if( keepAt(i) instanceof PhiNode phi ) {
+ Node n=phi.peephole();
+ if( n!=phi ) phi.subsume(n);
+ }
}
// Fill in the backedge of any inserted Phis
void _endLoop( ScopeNode scope, Node back, Node exit ) {
+ ScopeNode bscope=(ScopeNode)back, escope=(ScopeNode)exit;
+ for( int i=0; i<keepDepth(); i++ ) {
+ Node n=keepAt(i);
+ if( n instanceof PhiNode phi && phi.region()==scope.ctrl() && phi.in(2)==null ) {
+ phi.setDef(2,bscope.getKeep(i));
+ }
+ if( escope.keepAt(i)==scope ) escope.setKeep(i,n);
+ }
for( int i=1; i<nIns(); i++ ) {
if( !loopVar(var(i)) ) continue;
Node n = in(i);
@@ -654,8 +744,10 @@ public class ScopeNode extends MemMergeNode {
n.unkill();
_guards.clear();
// Can have lazy uses remaining
- if( isUnused() )
+ if( isUnused() ) {
+ if( _keeps!=null ) _keeps.unkill();
super.kill();
+ }
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
index 079853cd..9f0b63f5 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
@@ -168,6 +168,7 @@ final class ArrayInitializers {
// Saved paths share Var records with the active scope. Drop locals
// without promoting them, then copy forward references explicitly.
while( cur.depth()>_frame._depth ) cur._pop();
+ cur.popKeepsTo(_frame._kind._keepSize+1);
cur.balanceLoopFRefs(P._scope);
cur.update(_frame._value,value.unkeep());
if( _frame._returns==null ) _frame._returns=cur;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java
index 6c626669..95ae3168 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java
@@ -32,6 +32,7 @@ final class ControlFlow {
P.ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection
P._scope.addGuards(ifT,pred,false); // Up-cast predicate
// Parse true-side flavor
+ if( fside.equals("else") ) P._scope.pushKeep();
Node lhs = switch( fside ) {
case "else" -> P.statements.parseStatement(); // if( pred ) stmts;
case ":" -> P.expressions.parseAssignment(); // pred ? asgn;
@@ -40,6 +41,7 @@ final class ControlFlow {
default -> throw TODO();
};
lhs.keep();
+ if( fside.equals("else") ) P._scope.popKeep();
P._scope.removeGuards(ifT);
// See if a one-sided def was made: "if(pred) int x = 1;" and throw.
@@ -57,6 +59,7 @@ final class ControlFlow {
P._scope.addGuards(ifF,pred,true);
// Parse false-side flavor
boolean doRHS = false; // RHS is optional for if/else and trinary
+ if( fside.equals("else") ) P._scope.pushKeep();
Node rhs = switch( fside ) {
case "else" -> (doRHS = P.match(fside)) ? P.statements.parseStatement() : P.con(lhs._type.makeZero());
case ":" -> (doRHS = P.match(fside)) ? P.expressions.parseAssignment() : P.con(lhs._type.makeZero());
@@ -65,6 +68,7 @@ final class ControlFlow {
default -> throw TODO();
};
rhs.keep();
+ if( fside.equals("else") ) P._scope.popKeep();
P._scope.removeGuards(ifF);
// The RHS of `||` is parsed on the false side, so retain its updated
// control, memory and locals just as an explicit else arm does.
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Conversions.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Conversions.java
index 72247ca6..cdba0c0f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Conversions.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Conversions.java
@@ -21,10 +21,20 @@ final class Conversions {
if( expr instanceof FunPtrNode && t instanceof TypeFunPtr )
return expr;
// Auto-widen array to i64 (cast ptr to raw int bits)
- if( t == TypeInteger.BOT && expr._type instanceof TypeMemPtr tmp && tmp._obj.isAry() )
- return P.peep(new AddNode(P.peep(new PtrToIntNode(expr)),ConFldOffNode.make(tmp._obj,"[]")));
+ if( t == TypeInteger.BOT && expr._type instanceof TypeMemPtr tmp && tmp._obj.isAry() ) {
+ Node raw=P.peep(new AddNode(P.peep(new PtrToIntNode(expr)),ConFldOffNode.make(tmp._obj,"[]")));
+ P._scope.keepValue(raw);
+ return raw;
+ }
// Widen ints to floats, narrow wide types
- return P.peep(new ConvertNode(t,expr));
+ Type src=expr._type;
+ boolean possibleArray=!(expr instanceof ArithNode) && (src==Type.BOTTOM || src==TypeScalar.BOT);
+ Node converted=P.peep(new ConvertNode(t,expr));
+ // A forward call can acquire its array result type after parsing.
+ // ConvertNode will then introduce PtrToInt; save its endpoint now.
+ if( t==TypeInteger.BOT && possibleArray )
+ P._scope.keepValue(converted);
+ return converted;
}
// Inferred `var` declarations describe writable slots, not the exact
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java
index a7726521..5064c479 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -389,6 +389,7 @@ final class Functions {
// travel in expr's private memory; only their scope layout is retained.
int lexN = P._scope.enclosingFuncOrDecl();
Kind.Func k = (Kind.Func)P._scope._kinds.at(lexN);
+ P._scope.endKeeps(k._keepSize);
if( FunNode.isInit(k._name) ) {
int nestedLexSize = lexN+1 < P._scope.depth() ? P._scope._kinds.at(lexN+1)._lexSize : P._scope.nIns();
if( k._name.endsWith(".<clinit>") )
@@ -412,6 +413,7 @@ final class Functions {
_returnScope = P._scope.dup();
while( lexN+1 < _returnScope.depth() )
_returnScope._pop(); // Pop a nested block scope until we hit the function scope
+ _returnScope.popKeepsTo(k._keepSize+1);
_returnScope.define("$expr", Conversions.inferredReturnType(expr._type), true, expr, null);
} else {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java
index 0c2a25f7..b27a5032 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java
@@ -193,7 +193,9 @@ final class Statements {
// Our current scope is the body Scope
P.ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection
P._scope.addGuards(ifT,pred.unkeep(),false); // Up-cast predicate
+ P._scope.pushKeep(); // An unbraced body also has an iteration lifetime.
parseStatement().isKill(); // Parse loop body
+ P._scope.popKeep();
P._scope.removeGuards(ifT);
// Merge the loop bottom into other continue statements
@@ -206,8 +208,10 @@ final class Statements {
// Now append the next code onto the body code
if( doFor ) {
int old = P.pos(nextPos);
+ P._scope.pushKeep();
if( !P.peek(')') )
P.expressions.parseAssignment().isKill();
+ P._scope.popKeep();
if( P.pos() != nextEnd )
throw P.errorSyntax( "Unexpected code after expression" );
P.pos(old);
@@ -264,6 +268,7 @@ final class Statements {
// copy forward references into the jump scope with their own indices.
while( cur.depth() > _breakScope.depth() )
cur._pop();
+ cur.popKeepsTo(_breakScope.keepDepth());
cur.balanceLoopFRefs(P._scope);
// If this is a continue then first time the target is null
// So we just use the pruned current scope as the base for the
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java b/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java
index 221de04c..41fe039f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/type/Type.java
@@ -235,8 +235,15 @@ public class Type /*implements Cloneable*/ {
public int nkids() { return 0; } // Number of kids
+ // Reset recycles Type objects still referenced by old compilation graphs.
+ // Debuggers must not inspect those types, even if they have been reused and
+ // look valid again. The generation lets a CodeGen detect that situation.
+ private static long RESET_GENERATION;
+ public static long resetGeneration() { return RESET_GENERATION; }
+
// Clear and re-insert the basic Type INTERN table
public static void reset() {
+ RESET_GENERATION++;
VISIT.clear();
FREES.clear();
if( INTERN0.isEmpty() ) {