summaryrefslogtreecommitdiff
path: root/chapter33/src
diff options
context:
space:
mode:
Diffstat (limited to 'chapter33/src')
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java1147
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java538
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java53
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java131
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java5
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java29
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java35
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java13
-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/CLInitNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java3
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/FunPtrNode.java1
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/Intrinsic.java13
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java102
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java70
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java11
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/Node.java9
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java96
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/StartNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/StopCUNode.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java17
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java15
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java5
-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/References.java16
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java5
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/type/Type.java7
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java76
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/BrainFuckTest.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java11
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java2121
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Eval2.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java12
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java19
43 files changed, 4569 insertions, 88 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
new file mode 100644
index 00000000..2c0d4664
--- /dev/null
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java
@@ -0,0 +1,1147 @@
+package com.seaofnodes.simple.codegen;
+
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.SB;
+import com.seaofnodes.simple.util.BAOS;
+import com.seaofnodes.simple.parser.Parser;
+import java.util.*;
+
+/** First allocation-lifetime experiment. Builds plans, not machine allocations.
+ * One DFS of the call DAG: discover callees on entry, compose their symbolic
+ * summaries on exit. No call-tree expansion, caller rewalk, or IR mutation.
+ * Within a summary, reference edges propagate destination requirements with a
+ * small worklist. A rejected summary is never a usable allocation plan.
+ */
+public final class Allocation {
+ private final Summary[] _summaries;
+ private final Summary _entrySummary;
+ private final ArrayList<Summary> _postorder = new ArrayList<>();
+ public final ArrayList<ArrayDelete> _deletes = new ArrayList<>();
+
+ // 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 borrowed/static storage or unloaded allocations
+ 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 boolean _fresh; // also true for allocations in unloaded bodies
+ private final boolean _buddy;
+ 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<>();
+ Site _base; // borrowed field origin, e.g. arg3.c
+ String _field;
+ private int _depth;
+
+ private Site(Summary sum, NewNode allocation, int arg, String name) {
+ this(sum,allocation,arg,name,
+ allocation!=null && allocation.size()._type instanceof TypeInteger size && size.isConstant() ? size.value() : -1,
+ allocation!=null,allocation!=null && allocation._deletable);
+ }
+ private Site(Summary sum, NewNode allocation, int arg, String name, long bytes, boolean fresh, boolean buddy) {
+ _allocation=allocation; _arg=arg; _name=name;
+ _destinations=sum._destinations;
+ _bytes=bytes; _fresh=fresh; _buddy=buddy;
+ if( arg>=2 ) _owners.set(arg);
+ if( arg==-1 ) _owners.set(STATIC);
+ }
+
+ public String destination() {
+ if( buddy() ) return "buddy";
+ if( _owners.isEmpty() ) return _scope==null || _scope._loop==null ? "frame" : _scope.name()+" iteration";
+ SB sb = new SB();
+ 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();
+ }
+
+ public boolean buddy() { return _buddy; }
+ }
+
+ /** Symbolic summary, with separate destinations for separate arguments.
+ * Object fields are weak updates: all stored references remain possible.
+ * Borrowed field paths describe incoming contents separately from stores. */
+
+ // 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; // 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<>();
+ public final ArrayList<ArrayDelete.Consume> _consumes = new ArrayList<>();
+ boolean _opaqueEffects; // raw/native effects absent from the field graph
+ private final HashSet<Site> _escapes = new HashSet<>();
+ public String _reject;
+ private byte _state; // 0 pre/unseen, 1 mid/active DFS, 2 post/complete
+ private byte _ownershipState;
+ private boolean _ownershipCycle;
+ // All allocation-interesting Nodes; Calls, Stores, News, Ptr ops
+ private final ArrayList<Node> _nodes = new ArrayList<>();
+ // 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;
+ // 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 Site _static;
+ private int _pathLimit; // own reads plus the path depths imported at calls
+ private boolean _changed;
+
+ 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 ? "loop#"+_loop._nid : _fun==null ? "saved contract" : _fun.label(); }
+ // 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 "+name()+": "+_reject);
+ return this;
+ }
+ // Collect first rejection
+ private void reject(String why) { if( _reject==null ) _reject=why; }
+ }
+
+ 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() ) {
+ 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);
+ // Callees precede callers. Discharged requirements disappear; incoming
+ // ones become the caller's own contract. This is separate from placement.
+ for( Summary sum : _postorder ) ownership(sum);
+ }
+
+ private void ownership(Summary sum) {
+ if( sum._ownershipState==2 ) return;
+ if( sum._ownershipState==1 ) { sum._ownershipCycle=true; return; }
+ sum._ownershipState=1;
+ for( CallNode call : sum._calls ) {
+ if( call.fptr()._type instanceof TypeFunPtr fp && !XInt.isHigh(fp.fidxs()) )
+ for( int fidx=XInt.next(fp.fidxs(),0); fidx>=0; fidx=XInt.next(fp.fidxs(),fidx) ) {
+ Summary callee=fidx<_summaries.length ? _summaries[fidx] : null;
+ if( callee!=null ) { ownership(callee); sum._ownershipCycle |= callee._ownershipCycle; }
+ }
+ }
+ for( CallNode call : sum._calls ) {
+ if( Intrinsic.arrayDelete(call) && Intrinsic.arrayDeleteType(call.tfp()) && call.nargs()==1 )
+ consume(sum,new ArrayDelete(this,sum._nodes,call,2));
+ else if( call.fptr()._type instanceof TypeFunPtr fp && !XInt.isHigh(fp.fidxs()) )
+ for( int fidx=XInt.next(fp.fidxs(),0); fidx>=0; fidx=XInt.next(fp.fidxs(),fidx) ) {
+ Summary callee=fidx<_summaries.length ? _summaries[fidx] : null;
+ if( callee!=null )
+ for( ArrayDelete.Consume requirement : new ArrayList<>(callee._consumes) )
+ consume(sum,new ArrayDelete(this,sum._nodes,call,requirement));
+ }
+ }
+ sum._ownershipState=2;
+ }
+
+ private void consume(Summary sum, ArrayDelete check) {
+ // Recursive SCC heads need the same entry/outgoing ownership boundary
+ // as loop heads. Their allocation graphs are not built yet; do not
+ // assume a consuming requirement also proves a unique outgoing field.
+ if( sum._ownershipCycle ) check._reject="recursive consuming contracts are not supported";
+ _deletes.add(check);
+ if( check._reject==null && check._requirement!=null && !sum._consumes.contains(check._requirement) )
+ sum._consumes.add(check._requirement);
+ }
+
+ void checkOwnership() {
+ // A first-class callback type does not yet carry consuming paths.
+ // Do not let it erase a requirement established on a concrete function.
+ for( Summary sum : _postorder ) for( CallNode call : sum._calls ) {
+ TypeFunPtr target=call.fptr()._type instanceof TypeFunPtr fp ? fp : null;
+ int first=target!=null && target.nargs()>0 && target.arg(0)==TypePtr.PTR ? 3 : 2;
+ for( int i=first; i<call.nIns()-1; i++ ) {
+ Type arg=call.arg(i)._type;
+ int[] callbacks=arg instanceof TypeFunPtr fp ? fp.fidxs() :
+ nativeCall(call) && arg instanceof TypeMemPtr ? TypeMem.START.escapesFrom(arg)._escFs : XInt.EMPTY;
+ if( callbacks!=XInt.EMPTY ) for( Summary callee : _summaries )
+ if( callee!=null && !callee._consumes.isEmpty() && XInt.bit(callbacks,callee._fun.sig().fidx()) )
+ throw Parser.error("Consuming callback requires an explicit ownership contract",call._loc);
+ if( (target==null || XInt.isHigh(target.fidxs())) && deletableStorage(arg,new HashSet<>()) )
+ throw Parser.error("Unknown call cannot verify ownership of deletable storage",call._loc);
+ }
+ }
+ }
+
+ private static boolean deletableStorage(Type t, HashSet<Type> seen) {
+ if( !seen.add(t) || !(t instanceof TypeMemPtr ptr) ) return false;
+ if( ptr._del ) return true;
+ if( ptr._obj._fields!=null )
+ for( Field field : ptr._obj._fields ) if( deletableStorage(field._t,seen) ) return true;
+ return false;
+ }
+
+ public Summary summary(String name) {
+ for( Summary sum : _summaries )
+ if( sum!=null && name.equals(sum._fun._name) ) return sum;
+ throw new IllegalArgumentException("No allocation summary for "+name);
+ }
+
+ Summary summary(FunNode fun) { return _summaries[fun.sig().fidx()]; }
+
+ // Boundary contracts contain symbolic storage, never graph node IDs or
+ // implementation frames. Site zero is static storage. Local scratch is
+ // omitted; only external destinations and their reference graph survive.
+ static void write(BAOS out, Summary sum) {
+ assert sum._state==2;
+ out.packed4(sum._consumes.size());
+ for( ArrayDelete.Consume consume : sum._consumes ) {
+ out.packed4(consume.arg()); out.packed4(consume.path().size());
+ for( String field : consume.path() ) out.packedS(field);
+ }
+ out.packed1(sum._opaqueEffects ? 1 : 0);
+ out.packedS(sum._reject==null ? "" : sum._reject);
+ if( !sum.supported() ) return;
+ out.packed4(sum._destinations.size());
+ for( String name : sum._destinations ) out.packedS(name);
+ ArrayList<Site> sites=new ArrayList<>();
+ HashMap<Site,Integer> ids=new HashMap<>();
+ ids.put(sum._static,0);
+ sites.add(sum._static);
+ for( Site site : sum._sites )
+ if( site!=sum._static && !site._owners.isEmpty() ) {
+ ids.put(site,sites.size()); sites.add(site);
+ }
+ // Include field/path dependencies even when they have no destination
+ // of their own. Assign IDs before writing so cycles need no recursion.
+ for( int i=0; i<sites.size(); i++ ) {
+ Site site=sites.get(i);
+ if( site._base!=null && !ids.containsKey(site._base) ) {
+ ids.put(site._base,sites.size()); sites.add(site._base);
+ }
+ for( HashSet<Site> values : site._fields.values() )
+ for( Site child : values ) if( !ids.containsKey(child) ) {
+ ids.put(child,sites.size()); sites.add(child);
+ }
+ }
+ out.packed4(sites.size());
+ for( Site site : sites ) {
+ out.packed4(site._arg); out.packedS(site._name);
+ out.packed8(site._bytes);
+ out.packed1((site._fresh ? 1 : 0) | (site.buddy() ? 2 : 0));
+ out.packed4(site._owners.cardinality());
+ for( int bit=site._owners.nextSetBit(0); bit>=0; bit=site._owners.nextSetBit(bit+1) ) out.packed4(bit);
+ }
+ for( Site site : sites ) {
+ out.packed4(site._base==null ? -1 : ids.get(site._base));
+ if( site._base!=null ) out.packedS(site._field);
+ out.packed4(site._depth);
+ out.packed4(site._fields.size());
+ for( var field : site._fields.entrySet() ) {
+ out.packedS(field.getKey()); out.packed4(field.getValue().size());
+ for( Site child : field.getValue() ) out.packed4(ids.get(child));
+ }
+ }
+ out.packed4(sum._returns.size());
+ for( Site site : sum._returns ) out.packed4(ids.get(site));
+ }
+
+ static Summary read(BAOS in) {
+ Summary sum=new Summary((FunNode)null);
+ sum._state=2;
+ int consumes=in.packed4();
+ for( int i=0; i<consumes; i++ ) {
+ int arg=in.packed4(), count=in.packed4();
+ ArrayList<String> path=new ArrayList<>();
+ for( int j=0; j<count; j++ ) path.add(in.packedS());
+ sum._consumes.add(new ArrayDelete.Consume(arg,path));
+ }
+ sum._opaqueEffects=in.packed1()!=0;
+ String reject=in.packedS();
+ if( !reject.isEmpty() ) { sum.reject(reject); return sum; }
+ sum._destinations.clear();
+ int names=in.packed4();
+ for( int i=0; i<names; i++ ) sum._destinations.add(in.packedS());
+ int count=in.packed4();
+ for( int i=0; i<count; i++ ) {
+ int arg=in.packed4(); String name=in.packedS();
+ long bytes=in.packed8(); int flags=in.packed1();
+ Site site=new Site(sum,null,arg,name,bytes,(flags&1)!=0,(flags&2)!=0);
+ site._owners.clear();
+ int owners=in.packed4();
+ for( int j=0; j<owners; j++ ) site._owners.set(in.packed4());
+ sum._sites.add(site);
+ }
+ sum._static=sum._sites.get(0);
+ for( Site site : sum._sites ) {
+ int base=in.packed4();
+ if( base>=0 ) {
+ site._base=sum._sites.get(base); site._field=in.packedS();
+ site._base._loads.put(site._field,site);
+ }
+ site._depth=in.packed4();
+ int fields=in.packed4();
+ for( int j=0; j<fields; j++ ) {
+ String field=in.packedS(); int size=in.packed4();
+ HashSet<Site> values=new HashSet<>();
+ for( int k=0; k<size; k++ ) values.add(sum._sites.get(in.packed4()));
+ site._fields.put(field,values);
+ }
+ }
+ int returns=in.packed4();
+ for( int i=0; i<returns; i++ ) sum._returns.add(sum._sites.get(in.packed4()));
+ // Retention is represented by stores through incoming/static sites.
+ for( Site site : sum._sites ) if( !site._fresh )
+ for( HashSet<Site> children : site._fields.values() ) sum._retained.addAll(children);
+ return sum;
+ }
+
+ public void requireSupported() {
+ for( Summary sum : _postorder )
+ sum.requireSupported();
+ }
+
+ /** Analysis-only deletion checkpoint. No storage is freed. A proof about
+ * incoming storage also reports the unique-entry contract still required. */
+ public ArrayDelete checkArrayDelete(CallNode call, int arg) {
+ for( Summary sum : _postorder )
+ if( sum._calls.contains(call) ) return new ArrayDelete(this,sum._nodes,call,arg);
+ throw new IllegalArgumentException("Deletion checkpoint is not in an analyzed body");
+ }
+
+ // A deliberately narrow helper contract: pointer fields are not changed,
+ // and the result is scalar or forwards known arguments. Scalar element
+ // copies, including loops, qualify. Scalar results need only effects;
+ // reference results also require an allocation contract for their origins.
+ boolean arrayBorrow(CallNode call) {
+ // A nonreturning call contributes no retained references to its caller.
+ if( call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP ) return true;
+ if( nativeCall(call) ) return false; // No pointer-memory effect contract yet.
+ Summary sum=target(call);
+ if( sum==null || sum._fun._extern ) return false;
+ Type ret=sum._fun.ret().expr()._type;
+ if( !(ret instanceof TypeInteger || ret instanceof TypeFloat) && arrayResult(call)==null ) return false;
+ return noReferenceEffects(sum._fun);
+ }
+
+ // Direct argument forwarding is enough for copy/identity helpers. Field
+ // paths and fresh return storage are serialized too, but their deletion
+ // proofs need richer memory-origin queries before allowing these borrows.
+ ArrayList<Node> arrayResult(CallNode call) {
+ Summary sum=target(call);
+ if( sum==null || !sum.supported() ) return null;
+ ArrayList<Node> args=new ArrayList<>();
+ for( Site site : sum._returns ) {
+ if( site._arg<2 || site._arg>=call.nIns()-1 ) return null;
+ args.add(call.arg(site._arg));
+ }
+ return args;
+ }
+
+ // Repeated consumption also needs an exclusive outgoing slot. Consuming
+ // the entry value alone does not promise that: a helper could publish its
+ // replacement into a second field before returning. The existing boundary
+ // graph (including imported graphs) suffices for this narrow proof.
+ boolean arrayOwned(CallNode call, ArrayDelete.Consume consume) {
+ return arrayOwned(target(call),consume);
+ }
+
+ private static boolean arrayOwned(Summary sum, ArrayDelete.Consume consume) {
+ if( sum==null || !sum.supported() || sum._opaqueEffects || consume.path().isEmpty() ) return false;
+ Site owner=null;
+ for( Site site : sum._sites ) if( site._arg==consume.arg() ) owner=site;
+ if( owner==null ) return false;
+ for( int i=0; i<consume.path().size()-1; i++ ) {
+ String field=consume.path().get(i);
+ Set<Site> stored=owner._fields.get(field);
+ Site incoming=owner._loads.get(field);
+ if( stored!=null && !stored.isEmpty() ) {
+ if( stored.size()!=1 || incoming!=null && !stored.contains(incoming) ) return false;
+ owner=stored.iterator().next();
+ } else owner=incoming;
+ if( owner==null ) return false;
+ }
+ String field=consume.path().getLast();
+ HashSet<Site> values=new HashSet<>();
+ Set<Site> stored=owner._fields.get(field);
+ if( stored!=null ) values.addAll(stored);
+ Site incoming=owner._loads.get(field);
+ if( incoming!=null ) values.add(incoming);
+ for( Site value : values ) {
+ if( value!=incoming && !value._fresh || sum._returns.contains(value) ) return false;
+ for( Site site : sum._sites ) for( var edge : site._fields.entrySet() )
+ if( edge.getValue().contains(value) && (site!=owner || !edge.getKey().equals(field)) ) return false;
+ }
+ return true;
+ }
+
+ boolean arrayBorrow(CLInitNode init) {
+ return init.bypass() || noReferenceEffects(CodeGen.CODE.link(init.cu()));
+ }
+
+ private static boolean noReferenceEffects(FunNode fun) {
+ FunctionEffects effects=CodeGen.CODE._effects.get(fun);
+ return effects!=null && !effects._referenceWrites;
+ }
+
+ private void visit(Summary sum) {
+ if( sum._state==2 ) return; // Post-order, done
+ // Mid-visit, so found a Call Graph cycle, i.e. recursion
+ if( sum._state==1 ) {
+ // Recursive SCC/mega-call work goes here; do not expand a call tree.
+ sum.reject("recursive call component");
+ return;
+ }
+ // Was pre-order, now mid-order
+ sum._state=1;
+ if( sum._fun.summary()!=null && sum._fun.summary()._allocation!=null ) {
+ Summary contract=sum._fun.summary()._allocation;
+ sum._reject=contract._reject;
+ sum._destinations.clear(); sum._destinations.addAll(contract._destinations);
+ sum._static=contract._static;
+ sum._sites.addAll(contract._sites);
+ sum._returns.addAll(contract._returns);
+ sum._retained.addAll(contract._retained);
+ sum._consumes.addAll(contract._consumes);
+ sum._opaqueEffects=contract._opaqueEffects;
+ } else if( sum._fun._extern || sum._fun.summary()!=null ) {
+ sum.reject("opaque body: allocation contract unavailable");
+ } else {
+ // Collection interesting function body and call sites
+ collect(sum);
+ for( Node n : sum._nodes )
+ if( n instanceof PtrToIntNode || n instanceof CLInitNode init && !arrayBorrow(init) ) sum._opaqueEffects=true;
+ for( CallNode call : sum._calls ) {
+ if( nativeCall(call) ) {
+ if( !Intrinsic.pure(call) && !Intrinsic.arrayDelete(call) &&
+ !(call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP) ) sum._opaqueEffects=true;
+ // 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 {
+ // Recursive walk Call Graph DAG
+ visit(callee);
+ sum._opaqueEffects |= callee._opaqueEffects;
+ // If some callee is rejected, so is this caller
+ if( callee._reject!=null )
+ sum.reject("call #"+call._nid+" -> "+callee._fun.label()+": "+callee._reject);
+ }
+ }
+ if( sum._reject==null )
+ build(sum);
+ }
+ // Postder
+ sum._state=2;
+ _postorder.add(sum);
+ }
+
+ Summary target(CallNode call) {
+ if( !(call.fptr()._type instanceof TypeFunPtr fp) || !fp.isConstant() ) return null;
+ int idx=fp.fidx();
+ 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
+ // other functions, so no following linked Calls or Parms.
+ private void collect(Summary sum) {
+ BitSet seen = new BitSet();
+ ArrayDeque<Node> work = new ArrayDeque<>();
+ // 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();
+ if( seen.get(n._nid) ) continue; // Been there, done that
+ 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 ||
+ use instanceof ParmNode parm && parm.fun()==sum._fun )
+ work.push(use);
+ // Reference uses stay within this function; Parm call links and
+ // constant/global anchors are boundaries. In particular, find raw
+ // conversions without following their scalar arithmetic users.
+ if( !n.isFunLeaf() || n instanceof ParmNode )
+ for( Node use : n._outputs )
+ if( use instanceof PtrToIntNode || pointer(use) && !use.isFunLeaf() )
+ work.push(use);
+ if( n.isFunLeaf() ) continue;
+ if( n instanceof CallNode call ) sum._calls.add(call);
+ 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
+ // state already give those objects the static destination. Do not
+ // mistake an own-class initialization guard for recursive calling.
+ if( n instanceof CallEndNode cend ) { work.push(cend.call()); continue; }
+
+ // Walk selected edges. We can skip pure-data ops, but need to
+ // walk both control and memory at least.
+ for( Node in : n._inputs )
+ if( in!=null && (in instanceof CFGNode || in.isMem() ||
+ 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._deletable && (!(alloc.size()._type instanceof TypeInteger size) || !size.isConstant()) )
+ sum.reject("variable-size allocation #"+alloc._nid);
+ 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);
+ 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++;
+ }
+ // 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._fresh && !site._owners.isEmpty() ) {
+ Site copy=new Site(sum,site._allocation,0,"call#"+call._nid+"/"+site._name,site._bytes,true,site.buddy());
+ 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;
+ }
+
+ // 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);
+
+ // Local closure only: an object retained in a destination retains its
+ // referenced objects there too. Cyclic object graphs need no DAG rewalk.
+ ArrayDeque<Site> work=new ArrayDeque<>(sum._sites);
+ while( !work.isEmpty() ) {
+ Site src = work.pop();
+ for( Set<Site> values : src._fields.values() )
+ for( Site dst : values ) {
+ int before = dst._owners.cardinality();
+ dst._owners.or(src._owners); // Union owners set
+ 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.
+ }
+
+ // n has pointer type
+ private static boolean pointer(Node n) {
+ 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.
+ 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._fresh ) 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) && !site.buddy() ) {
+ 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 ) {
+ // Buddy blocks are independent allocations, released by .del().
+ // Keep tracking their references, but never put them in stack cleanup.
+ if( site.buddy() ) { site._scope=site._frame; continue; }
+ 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 boolean edge(HashSet<Site> dst, String field, HashSet<Site> src) {
+ if( src.isEmpty() ) return false;
+ boolean changed=false;
+ for( Site site : dst )
+ 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._fresh ) {
+ 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; 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. 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( 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( n instanceof ConstantNode ) {
+ // Zero/null carries no storage obligation. Other constant objects
+ // 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 ) {
+ 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)));
+ } else if( n instanceof ReadOnlyNode || n instanceof GuardNode ||
+ n instanceof ConstructNode || n instanceof InitViewNode || n instanceof ConvertNode ) {
+ 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 {
+ sum.reject("reference origin "+n.getClass().getSimpleName()+" #"+n._nid);
+ }
+ 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,
+ // 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 void compose(Summary sum, CallNode call, IdentityHashMap<Site,HashSet<Site>> map) {
+ Summary callee=target(call);
+ // 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 )
+ sum.reject("missing argument at call #"+call._nid);
+ 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 ) {
+ HashSet<Site> dst=map.get(site);
+ if( dst.isEmpty() ) continue;
+ for( var field : site._fields.entrySet() ) for( Site child : field.getValue() ) {
+ HashSet<Site> src=map.get(child);
+ if( src==null ) sum.reject("unmapped retained storage at call #"+call._nid);
+ 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 sum._changed |= sum._results.get(call).addAll(returned);
+ }
+ }
+
+ // 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");
+ 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");
+ for( ArrayDelete.Consume consume : sum._consumes ) {
+ out.append("| may consume entry(").append(consume).append("); requires unique access");
+ if( arrayOwned(sum,consume) ) out.append("; returns unique ").append(consume);
+ out.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 ? 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.
+ }
+ 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._fresh ) {
+ out.append(" (");
+ if( site._bytes<0 ) out.append("dynamic size");
+ else out.append(site._bytes).append(" bytes");
+ out.append(')');
+ }
+ 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/ArrayDelete.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java
new file mode 100644
index 00000000..1d22a3b6
--- /dev/null
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java
@@ -0,0 +1,538 @@
+package com.seaofnodes.simple.codegen;
+
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.SB;
+import java.util.*;
+
+/** Demand-driven ownership at a deletion checkpoint. Field queries follow
+ * memory SSA. Call summaries supply may-stores, returned origins, and exclusive
+ * outgoing fields at that call's memory output, never at all calls at once.
+ * Runtime recycling remains separate from these proofs. */
+public final class ArrayDelete {
+ public record Consume(int arg, List<String> path) {
+ public Consume { path=List.copyOf(path); }
+ @Override public String toString() {
+ SB sb=new SB().p("arg").p(arg);
+ for( String field : path ) sb.p('.').p(field);
+ return sb.toString();
+ }
+ }
+
+ // An origin is a local Node, an incoming base.field, a callee allocation,
+ // or a call's exclusive outgoing base.field. Interned inside this check.
+ // Node equality/hashing must be identity: Node.hashCode participates in GVN.
+ private record Ref(Node node, Ref base, String field, Allocation.Site site) {
+ @Override public int hashCode() {
+ return System.identityHashCode(node)+31*System.identityHashCode(base)+
+ 17*System.identityHashCode(site)+Objects.hashCode(field);
+ }
+ @Override public boolean equals(Object o) {
+ return o instanceof Ref r && node==r.node && base==r.base && site==r.site && Objects.equals(field,r.field);
+ }
+ boolean fresh() { return node instanceof NewNode || node instanceof CallNode || node instanceof LoopNode && base!=null; }
+ }
+ private static final class Effects {
+ final IdentityHashMap<Allocation.Site,HashSet<Ref>> values=new IdentityHashMap<>();
+ final HashMap<Ref,HashMap<String,HashSet<Ref>>> stores=new HashMap<>();
+ final HashSet<Ref> returns=new HashSet<>();
+ boolean building=true;
+ }
+
+ public final CallNode _call;
+ public String _reject;
+ public Node _unique;
+ public Consume _requirement;
+ private Ref _owner;
+ private String _field;
+ private int _alias;
+ private final Allocation _allocation;
+ private final HashMap<Ref,Ref> _origins=new HashMap<>();
+ private final IdentityHashMap<Node,HashSet<Ref>> _refs=new IdentityHashMap<>();
+ private final IdentityHashMap<CallNode,Effects> _effects=new IdentityHashMap<>();
+ private final IdentityHashMap<CallNode,HashSet<Ref>> _owned=new IdentityHashMap<>();
+ private final HashMap<Ref,HashSet<Ref>> _loopEntries=new HashMap<>();
+ private final IdentityHashMap<Node,Boolean> _borrows=new IdentityHashMap<>();
+ private final BitSet _active=new BitSet(), _after=new BitSet();
+ private final ArrayList<LoopNode> _backedges=new ArrayList<>();
+ private HashSet<Ref> _old;
+ private HashSet<Ref> _next;
+ private String _arrayType;
+ private boolean _deletable;
+
+ ArrayDelete(Allocation allocation, List<Node> nodes, CallNode call, int arg) {
+ this(allocation,nodes,call,new Consume(arg,List.of()),false);
+ }
+ ArrayDelete(Allocation allocation, List<Node> nodes, CallNode call, Consume consume) {
+ this(allocation,nodes,call,consume,true);
+ }
+ private ArrayDelete(Allocation allocation, List<Node> nodes, CallNode call, Consume consume, boolean atCaller) {
+ _allocation=allocation; _call=call;
+ if( consume.arg()<2 || consume.arg()>=call.nIns()-1 ) throw new IllegalArgumentException("Not a call argument");
+ Node value=call.arg(consume.arg());
+ Type type=value._type;
+ HashSet<Ref> roots=refs(value);
+ for( String name : consume.path() ) {
+ if( roots.size()!=1 || !(type instanceof TypeMemPtr ptr) ) {
+ reject("ambiguous consuming owner for "+consume); return;
+ }
+ Field field=ptr._obj.field(name);
+ if( field==null ) { reject("missing consuming field ."+name); return; }
+ _owner=roots.iterator().next(); _field=name; _alias=field._alias;
+ roots=contents(call.in(1),_owner,name,_alias);
+ // This checkpoint's next ownership version belongs to the next
+ // iteration; the entry and other preceding versions are checked here.
+ roots.remove(ref(call,_owner,name,null));
+ type=field._t;
+ }
+ if( !(type instanceof TypeMemPtr ptr) || !ptr._obj.isAry() || ptr.nullable() ) {
+ reject("requires a non-null array"); return;
+ }
+ _arrayType=ptr._obj._name;
+ _deletable=ptr._del;
+ if( _reject!=null ) return;
+ if( roots.isEmpty() ) { reject("array has no known origin"); return; }
+ _old=new HashSet<>(roots);
+ ArrayDeque<Ref> entries=new ArrayDeque<>(roots);
+ while( !entries.isEmpty() ) {
+ HashSet<Ref> entry=_loopEntries.get(entries.pop());
+ if( entry!=null ) for( Ref r : entry ) if( _old.add(r) ) entries.push(r);
+ }
+ for( Ref root : _old ) if( !root.fresh() ) {
+ Consume incoming=entryPath(root);
+ if( incoming==null ) { reject("cannot express incoming ownership as an argument field path"); return; }
+ if( _requirement!=null && !_requirement.equals(incoming) ) {
+ reject("array has multiple incoming ownership paths"); return;
+ }
+ _requirement=incoming; _unique=value;
+ }
+ after(call);
+ // Merges reached after this checkpoint exclude paths that bypassed it.
+ _refs.clear(); _effects.clear(); _owned.clear();
+
+ // A unique-entry requirement excludes aliases in the other arguments.
+ // Callees may rely on this; check the actuals at each consuming caller.
+ if( atCaller ) for( int i=2; i<call.nIns()-1; i++ )
+ if( i!=consume.arg() && pointer(call.arg(i)) && contains(call.arg(i)) )
+ reject("argument #"+(i-2)+" aliases the array at deletion");
+
+ // Check explicit stores and substituted callee stores by the same rule:
+ // any alias must be killed at the checkpoint's incoming memory version.
+ for( Ref root : roots ) if( root.node==null && root.base!=null ) slot(root.base,root.field);
+ for( Node n : nodes ) {
+ if( _reject!=null ) return;
+ if( n instanceof StoreNode st && pointer(st.val()) && contains(st.val()) ) {
+ if( later(st) ) reject("store #"+st._nid+" uses the array after deletion");
+ else for( Ref base : refs(st.ptr()) ) slot(base,st._name);
+ }
+ if( n instanceof CallNode other && other!=call && !borrow(other) && !unborn(other) ) {
+ Effects effect=effects(other);
+ if( effect==null ) { reject("call #"+other._nid+" ("+target(other)+") has unknown reference effects before deletion"); continue; }
+ for( var base : effect.stores.entrySet() ) for( var field : base.getValue().entrySet() )
+ if( contains(field.getValue()) ) {
+ if( later(other) ) reject("call #"+other._nid+" stores the array after deletion");
+ else slot(base.getKey(),field.getKey());
+ }
+ }
+ if( n instanceof CLInitNode init && !_allocation.arrayBorrow(init) && !later(init) && !unborn(init) )
+ reject("class initialization #"+init._nid+" has unknown reference effects before deletion");
+ }
+ for( Node n : nodes ) {
+ if( _reject!=null ) return;
+ if( pointer(n) && contains(n) ) for( Node use : n._outputs ) {
+ if( _reject!=null ) return;
+ use(n,use);
+ }
+ }
+ if( _reject==null && !_backedges.isEmpty() ) {
+ if( atCaller && !consume.path().isEmpty() && !_allocation.arrayOwned(call,consume) )
+ reject("callee does not preserve unique field ownership across deletion backedge");
+ else backedges(nodes);
+ }
+ }
+
+ public boolean proven() { return _reject==null && _unique==null; }
+ private void reject(String why) { if( _reject==null ) _reject=why; }
+ private Ref ref(Node n, Ref base, String field, Allocation.Site site) {
+ Ref r=new Ref(n,base,field,site);
+ Ref old=_origins.putIfAbsent(r,r);
+ return old==null ? r : old;
+ }
+ private Ref ref(Node n) { return ref(n,null,null,null); }
+ private static HashSet<Ref> set(Ref r) { HashSet<Ref> s=new HashSet<>(); s.add(r); return s; }
+ private static boolean pointer(Node n) { return n!=null && (n._type instanceof TypeMemPtr || n._type instanceof TypePtr); }
+ private Type type(Ref r) {
+ if( r.base!=null && type(r.base) instanceof TypeMemPtr p ) {
+ Field field=p._obj.field(r.field);
+ if( field!=null ) return field._t;
+ }
+ Type t=r.site!=null && r.site._allocation!=null ? r.site._allocation._type : r.node==null ? TypePtr.PTR : r.node._type;
+ return t instanceof TypeTuple tt && (r.node instanceof NewNode || r.site!=null && r.site._allocation!=null) ? tt.at(0) : t;
+ }
+ private int alias(Ref base, String name) {
+ if( type(base) instanceof TypeMemPtr p ) {
+ Field field=p._obj.field(name);
+ if( field!=null ) return field._alias;
+ }
+ return 1; // Unknown base: query the whole-memory slice conservatively.
+ }
+ private static Consume entryPath(Ref r) {
+ if( r.node instanceof ParmNode parm ) return new Consume(parm._idx,List.of());
+ if( r.node!=null || r.base==null ) return null;
+ Consume parent=entryPath(r.base);
+ if( parent==null ) return null;
+ ArrayList<String> path=new ArrayList<>(parent.path()); path.add(r.field);
+ return new Consume(parent.arg(),path);
+ }
+ private boolean contains(Node n) {
+ if( n._type instanceof TypeMemPtr p && p._obj!=TypeStruct.BOT && !p._obj._name.equals(_arrayType) ) return false;
+ return contains(refs(n));
+ }
+ private boolean contains(HashSet<Ref> refs) {
+ for( Ref old : _old ) if( mayAlias(refs,old) ) return true;
+ return false;
+ }
+ private boolean updated(HashSet<Ref> refs) {
+ if( _next!=null ) for( Ref r : _next ) if( mayAlias(refs,r) ) return true;
+ return false;
+ }
+ private boolean mayAlias(HashSet<Ref> refs, Ref base) {
+ for( Ref r : refs ) {
+ if( r==base ) return true;
+ if( r.fresh() || base.fresh() ) continue;
+ // Literal/static arrays cannot inhabit a deletable array slot.
+ if( _deletable && r.node instanceof ConstantNode && type(r) instanceof TypeMemPtr p &&
+ p._obj.isAry() && !p._del ) continue;
+ // A separate array parameter is disjoint under the propagated
+ // unique-entry requirement, checked against actuals at callers.
+ // Do not infer that different owner paths are disjoint: two
+ // wrapper parameters might denote the same wrapper.
+ if( _requirement!=null && _old!=null && _old.contains(base) &&
+ entryPath(base)!=null && r.node instanceof ParmNode ) continue;
+ if( type(r) instanceof TypeMemPtr x && type(base) instanceof TypeMemPtr y &&
+ x._obj!=TypeStruct.BOT && y._obj!=TypeStruct.BOT && !x._obj._name.equals(y._obj._name) ) continue;
+ return true;
+ }
+ return false;
+ }
+ private boolean unborn(CFGNode effect) {
+ for( Ref root : _old ) {
+ CFGNode birth=root.node instanceof NewNode alloc ? (CFGNode)alloc.ctrl() :
+ root.node instanceof CallNode call ? call : null;
+ if( birth==null || effect==birth || !effect.dominates(birth,null) ) return false;
+ }
+ return true;
+ }
+ private HashSet<Ref> refs(Node n) {
+ HashSet<Ref> known=_refs.get(n);
+ if( known!=null ) return known;
+ HashSet<Ref> result=new HashSet<>();
+ if( _reject!=null ) return result;
+ if( _active.get(n._nid) ) { reject("cyclic reference at #"+n._nid); return result; }
+ _active.set(n._nid);
+ if( n._type==Type.NIL || n._type.isHigh() ) {
+ } else if( n instanceof NewNode || n instanceof ParmNode || n instanceof ConstantNode ) result.add(ref(n));
+ else if( n instanceof ProjNode proj && proj._idx==0 && proj.in(0) instanceof NewNode ) result.add(ref(proj.in(0)));
+ else if( n instanceof GuardNode || n instanceof ReadOnlyNode || n instanceof ConstructNode || n instanceof InitViewNode )
+ result.addAll(refs(n.in(1)));
+ else if( n instanceof ArrayInitNode ) result.addAll(refs(n.in(2)));
+ else if( n instanceof PhiNode phi ) {
+ for( int i=1; i<phi.nIns(); i++ ) if( liveInput(phi,i) ) result.addAll(refs(phi.in(i)));
+ } else if( n instanceof LoadNode load ) {
+ HashSet<Ref> bases=refs(load.ptr());
+ if( bases.size()!=1 ) reject("ambiguous owner of field ."+load._name+" at #"+load._nid);
+ else result.addAll(contents(load.mem(),bases.iterator().next(),load._name,load._alias));
+ } else if( n instanceof ProjNode proj && proj._idx==2 && proj.in(0) instanceof CallEndNode end ) {
+ // Forwarded arguments need no field substitution, including calls
+ // which also update memory. Their stores are checked separately.
+ ArrayList<Node> args=_allocation.arrayResult(end.call());
+ if( args!=null ) for( Node arg : args ) result.addAll(refs(arg));
+ else {
+ Effects effect=effects(end.call());
+ if( effect==null ) reject("untracked returned reference at call #"+end.call()._nid);
+ else result.addAll(effect.returns);
+ }
+ } else reject("untracked reference #"+n._nid+" ("+n.label()+")");
+ _active.clear(n._nid); _refs.put(n,result);
+ return result;
+ }
+
+ // Unique entry -> unique exit is a strong ownership transfer, even when
+ // the implementation takes its no-growth path. May-stores remain weak.
+ private HashSet<Ref> owned(CallNode call) {
+ HashSet<Ref> slots=_owned.get(call);
+ if( slots!=null ) return slots;
+ slots=new HashSet<>(); _owned.put(call,slots);
+ Allocation.Summary sum=_allocation.target(call);
+ if( sum!=null ) for( Consume consume : sum._consumes )
+ if( _allocation.arrayOwned(call,consume) ) {
+ HashSet<Ref> bases=refs(call.arg(consume.arg()));
+ for( int i=0; i<consume.path().size()-1; i++ ) {
+ String field=consume.path().get(i);
+ HashSet<Ref> next=new HashSet<>();
+ for( Ref base : bases ) next.addAll(contents(call.in(1),base,field,alias(base,field)));
+ bases=next;
+ }
+ if( bases.size()==1 ) slots.add(ref(null,bases.iterator().next(),consume.path().getLast(),null));
+ }
+ return slots;
+ }
+
+ private HashSet<Ref> substitute(CallNode call, Allocation.Site site, Effects effect) {
+ HashSet<Ref> known=effect.values.get(site);
+ if( known!=null ) return known;
+ HashSet<Ref> values=new HashSet<>(); effect.values.put(site,values);
+ if( site._arg>=2 ) values.addAll(refs(call.arg(site._arg)));
+ else if( site._arg==-1 ) values.add(ref(CodeGen.CODE._start));
+ else if( site._fresh ) values.add(ref(call,null,null,site));
+ else if( site._base!=null )
+ for( Ref base : substitute(call,site._base,effect) )
+ values.addAll(contents(call.in(1),base,site._field,alias(base,site._field)));
+ else reject("unmapped call storage at #"+call._nid);
+ return values;
+ }
+
+ private Effects effects(CallNode call) {
+ Effects known=_effects.get(call);
+ if( known!=null ) {
+ if( known.building ) { reject("cyclic call-field effects at #"+call._nid); return null; }
+ return known;
+ }
+ Allocation.Summary sum=_allocation.target(call);
+ if( sum==null || !sum.supported() || sum._opaqueEffects || sum._fun._extern ) return null;
+ Effects effect=new Effects(); _effects.put(call,effect);
+ HashSet<Ref> owned=owned(call);
+ for( Allocation.Site site : sum._sites ) if( !site._fields.isEmpty() )
+ for( Ref base : substitute(call,site,effect) ) for( var field : site._fields.entrySet() ) {
+ HashSet<Ref> values=effect.stores.computeIfAbsent(base,k -> new HashMap<>())
+ .computeIfAbsent(field.getKey(),k -> new HashSet<>());
+ if( owned.contains(ref(null,base,field.getKey(),null)) ) values.add(ref(call,base,field.getKey(),null));
+ else for( Allocation.Site value : field.getValue() ) values.addAll(substitute(call,value,effect));
+ }
+ for( Allocation.Site site : sum._returns ) effect.returns.addAll(substitute(call,site,effect));
+ effect.building=false;
+ return effect;
+ }
+
+ private HashSet<Ref> contents(Node mem, Ref base, String field, int alias) {
+ return contents(mem,base,field,alias,new BitSet());
+ }
+ private HashSet<Ref> contents(Node mem, Ref base, String field, int alias, BitSet seen) {
+ HashSet<Ref> result=new HashSet<>();
+ if( _reject!=null || mem._type.isHigh() || seen.get(mem._nid) ) return result;
+ // A field query is reachability through memory definitions, with strong
+ // stores cutting edges. A loop revisit adds no new reachable definition.
+ seen.set(mem._nid);
+ if( mem instanceof MemMergeNode merge ) {
+ if( alias==1 ) {
+ for( Node slice : merge._inputs ) if( slice!=null ) result.addAll(contents(slice,base,field,alias,seen));
+ } else {
+ Node slice=merge.explicitAlias(alias);
+ result.addAll(contents(slice==null ? merge.in(1) : slice,base,field,alias,seen));
+ }
+ } else if( mem instanceof StoreNode st ) {
+ HashSet<Ref> bases=refs(st.ptr());
+ boolean same=(st._alias==alias || st._alias==1 || alias==1) && st._name.equals(field);
+ boolean exact=same && bases.size()==1 && bases.contains(base);
+ if( same && mayAlias(bases,base) ) {
+ if( "[]".equals(field) ) reject("array-element ownership needs an index proof");
+ else result.addAll(refs(st.val()));
+ }
+ if( !exact ) result.addAll(contents(st.mem(),base,field,alias,seen));
+ } else if( mem instanceof EscapeNode esc ) {
+ HashSet<Ref> bases=refs(esc.self());
+ boolean same=esc.fld()._alias==alias || alias==1;
+ if( same && mayAlias(bases,base) ) result.addAll(contents(esc.priv(),base,field,alias,seen));
+ if( !same || bases.size()!=1 || !bases.contains(base) ) result.addAll(contents(esc.pub(),base,field,alias,seen));
+ } else if( mem instanceof PhiNode phi && !(mem instanceof ParmNode) ) {
+ if( phi.region() instanceof LoopNode loop && inside(_call,loop) && base==_owner &&
+ field.equals(_field) && alias==_alias && type(ref(null,base,field,null)) instanceof TypeMemPtr p && p._obj.isAry() ) {
+ // A loop header is an ownership boundary, just like a call.
+ // Keep its entry version distinct from calls on the backedge.
+ Ref entry=ref(loop,base,field,null);
+ if( !_loopEntries.containsKey(entry) ) {
+ _loopEntries.put(entry,new HashSet<>());
+ _loopEntries.get(entry).addAll(contents(phi.in(1),base,field,alias,seen));
+ }
+ result.add(entry);
+ } else for( int i=1; i<phi.nIns(); i++ ) if( liveInput(phi,i) ) result.addAll(contents(phi.in(i),base,field,alias,seen));
+ } else if( mem instanceof ProjNode proj && proj.in(0) instanceof CallEndNode end ) {
+ CallNode call=end.call();
+ if( call==_call && base==_owner && field.equals(_field) && alias==_alias ||
+ owned(call).contains(ref(null,base,field,null)) ) result.add(ref(call,base,field,null));
+ else if( call==_call || Intrinsic.arrayDelete(call) || borrow(call) )
+ result.addAll(contents(call.in(1),base,field,alias,seen));
+ else {
+ Effects effect=effects(call);
+ if( effect==null ) reject("unknown reference effects at call #"+call._nid+" ("+target(call)+")");
+ else {
+ for( var store : effect.stores.entrySet() ) if( mayAlias(set(store.getKey()),base) ) {
+ Set<Ref> values=store.getValue().get(field);
+ if( values!=null ) result.addAll(values);
+ }
+ result.addAll(contents(call.in(1),base,field,alias,seen));
+ }
+ }
+ } else if( mem instanceof ProjNode proj && proj.in(0) instanceof NewNode ) {
+ } else if( mem instanceof ProjNode proj && proj.in(0) instanceof CLInitNode init && _allocation.arrayBorrow(init) ) {
+ result.addAll(contents(init.mem(),base,field,alias,seen));
+ } else if( mem instanceof ParmNode || mem instanceof ConstantNode || mem instanceof ProjNode proj && proj.in(0) instanceof StartNode ) {
+ if( !base.fresh() ) result.add(ref(null,base,field,null));
+ } else reject("unknown memory #"+mem._nid+" ("+mem.getClass().getSimpleName()+") for ."+field);
+ return result;
+ }
+
+ private boolean liveInput(PhiNode phi, int i) {
+ Node ctrl=phi.region().in(i);
+ return !ctrl._type.isHigh() && (!_after.get(phi.region()._nid) || _after.get(ctrl._nid));
+ }
+ private void slot(Ref base, String field) {
+ if( base==_owner && field.equals(_field) ) return;
+ if( contains(contents(_call.in(1),base,field,alias(base,field))) )
+ reject("field ."+field+" still holds the array at deletion");
+ }
+ private boolean borrow(CallNode call) {
+ Boolean known=_borrows.get(call);
+ if( known!=null ) return known;
+ boolean result=Intrinsic.arrayDelete(call) || _allocation.arrayBorrow(call);
+ _borrows.put(call,result); return result;
+ }
+ private static String target(CallNode call) {
+ return call.fptr()._type instanceof TypeFunPtr fp && fp.isConstant() ? CodeGen.CODE.funcName(fp.fidx()) : "indirect";
+ }
+ private void use(Node value, Node use) {
+ if( use==null ) { reject("unclassified kept reference #"+value._nid); return; }
+ if( use==_call ) return;
+ if( use instanceof PtrToIntNode ) { reject("raw-address borrow of the array at #"+use._nid); return; }
+ if( use instanceof CallNode call ) {
+ if( later(call) ) reject("call #"+call._nid+" uses the array after deletion");
+ else if( !borrow(call) && effects(call)==null ) reject("call #"+call._nid+" has no borrowing-only contract");
+ return;
+ }
+ if( use instanceof StoreNode store && store.val()==value ) return;
+ if( use instanceof EscapeNode || use instanceof NewNode || use instanceof ArrayInitNode ) return;
+ if( pointer(use) && (use instanceof PhiNode || use instanceof GuardNode || use instanceof ReadOnlyNode ||
+ use instanceof ConstructNode || use instanceof InitViewNode) ) return;
+ if( use.isFunLeaf() && !(use instanceof ReturnNode) ) return;
+ if( later(use) ) reject("use #"+use._nid+" ("+use.label()+") survives deletion");
+ }
+
+ private void after(CallNode call) {
+ if( call.cend()==null ) { reject("checkpoint has no continuation"); return; }
+ ArrayDeque<CFGNode> work=new ArrayDeque<>();
+ work.push(call.cend());
+ while( !work.isEmpty() ) {
+ CFGNode n=work.pop();
+ if( _after.get(n._nid) || n._type.isHigh() ) continue;
+ _after.set(n._nid);
+ if( n instanceof ReturnNode ) continue;
+ for( Node use : n._outputs )
+ if( use instanceof CFGNode next && !n.skip(next) ) {
+ if( next instanceof LoopNode loop && n==loop.back() && inside(call,loop) ) {
+ if( !_backedges.contains(loop) ) _backedges.add(loop);
+ } else work.push(next);
+ }
+ }
+ assert !_after.get(call._nid);
+ }
+
+ private static boolean inside(CFGNode ctrl, LoopNode loop) {
+ for( CFGNode.LoopTree tree=ctrl._ltree; tree!=null; tree=tree._par )
+ if( tree._head==loop ) return true;
+ return false;
+ }
+
+ // The backedge is a call to the next iteration. The wrapper passes its
+ // current field, not a saved copy of its old field. Check explicit Phi
+ // arguments and invariant references used again, as well as stored copies
+ // of the replacement. This last check is deliberately conservative: a
+ // later iteration might kill a stored alias before growing, but we do not
+ // yet infer that ordering as part of an iteration's entry contract.
+ private void backedges(List<Node> nodes) {
+ IdentityHashMap<Node,CFGNode> controls=new IdentityHashMap<>();
+ BitSet active=new BitSet();
+ for( LoopNode loop : _backedges ) {
+ _next=new HashSet<>();
+ if( _owner!=null ) for( Node use : loop._outputs )
+ if( use instanceof PhiNode phi && phi.region()==loop && phi._type instanceof TypeMem mem &&
+ (mem._alias==_alias || mem._alias==1) )
+ _next.addAll(contents(phi.in(2),_owner,_field,_alias));
+ // Include eventual exits as well as the next body. An invariant
+ // saved pointer returned after the loop also crosses this boundary.
+ BitSet next=new BitSet();
+ ArrayDeque<CFGNode> work=new ArrayDeque<>();
+ work.push(loop);
+ while( !work.isEmpty() ) {
+ CFGNode ctrl=work.pop();
+ if( next.get(ctrl._nid) || ctrl._type.isHigh() ) continue;
+ next.set(ctrl._nid);
+ if( ctrl instanceof ReturnNode ) continue;
+ for( Node use : ctrl._outputs )
+ if( use instanceof CFGNode cfg && !ctrl.skip(cfg) ) work.push(cfg);
+ }
+ for( Node n : nodes ) {
+ if( _reject!=null ) return;
+ // A helper after grow can retain the replacement through the
+ // wrapper. That effect precedes the NEXT grow, even though it
+ // does not precede this iteration's checkpoint.
+ if( n instanceof CallNode call && call!=_call && later(call) && inside(call,loop) && !borrow(call) ) {
+ Effects effect=effects(call);
+ if( effect==null ) reject("call #"+call._nid+" has unknown reference effects across deletion backedge");
+ else for( var base : effect.stores.entrySet() ) for( var field : base.getValue().entrySet() )
+ if( updated(field.getValue()) && !(base.getKey()==_owner && field.getKey().equals(_field)) )
+ reject("replacement array alias stored across deletion backedge at call #"+call._nid);
+ }
+ if( n instanceof PhiNode phi && phi.region()==loop && pointer(phi) ) {
+ HashSet<Ref> carried=refs(phi.in(2));
+ if( contains(phi.in(2)) || updated(carried) )
+ reject("array reference crosses deletion backedge at Phi #"+phi._nid);
+ }
+ if( n instanceof StoreNode st && pointer(st.val()) && updated(refs(st.val())) ) {
+ CFGNode ctrl=Allocation.control(st,controls,active);
+ if( ctrl!=null && inside(ctrl,loop) &&
+ !(refs(st.ptr()).equals(set(_owner)) && st._name.equals(_field)) )
+ reject("replacement array alias stored across deletion backedge at #"+st._nid);
+ }
+ if( !pointer(n) || !contains(n) ) continue;
+ CFGNode birth=Allocation.control(n,controls,active);
+ if( birth!=null && next.get(birth._nid) ) continue;
+ for( Node use : n._outputs ) {
+ if( use==null || use.isFunLeaf() ) continue;
+ CFGNode ctrl=Allocation.control(use,controls,active);
+ if( ctrl!=null && next.get(ctrl._nid) )
+ reject("array reference reused across deletion backedge at #"+use._nid);
+ }
+ }
+ }
+ _next=null;
+ }
+
+ // Follow data/memory definitions to their controls. A floating load on
+ // pre-delete memory may run before delete; a pointer returned afterwards
+ // is itself a post-delete use. No scheduling or graph mutation is needed.
+ private boolean later(Node node) {
+ BitSet seen=new BitSet();
+ ArrayDeque<Node> work=new ArrayDeque<>();
+ work.push(node);
+ while( !work.isEmpty() ) {
+ Node n=work.pop();
+ if( seen.get(n._nid) ) continue;
+ seen.set(n._nid);
+ if( n instanceof CFGNode ) {
+ if( _after.get(n._nid) ) return true;
+ continue;
+ }
+ if( n instanceof PhiNode phi ) { work.push(phi.region()); continue; }
+ if( n.isFunLeaf() ) continue;
+ for( Node in : n._inputs ) if( in!=null ) work.push(in);
+ }
+ return false;
+ }
+
+ @Override public String toString() {
+ SB sb=new SB().p("delete at call #").p(_call._nid).p(": ");
+ if( _reject!=null ) return sb.p("REJECT: ").p(_reject).toString();
+ if( _unique!=null ) sb.p("requires unique entry ").p(_requirement.toString()).p("; ");
+ return sb.p("no surviving array access").toString();
+ }
+}
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 51a6a197..302f1491 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,10 +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
@@ -135,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;
@@ -196,6 +199,8 @@ 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);
// Save reloadable ideal IR for a later seperate compilation
@@ -203,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);
@@ -429,13 +431,21 @@ public class CodeGen {
// SCCP and numeric-mode resolution; leave cleanup work queued for Iter.
public CodeGen opto() { return phase(Phase.Opto, _phase==Phase.Iter, () -> Opto.opto(this)); }
- public CodeGen iterPostOpto() { return phase(Phase.IterPostOpto, _phase==Phase.Opto, () -> _iter.iterate(this)); }
+ public CodeGen iterPostOpto() { return phase(Phase.IterPostOpto, _phase==Phase.Opto, () -> {
+ // The call graph is settled. Peepholes can now ask which aliases a
+ // call preserves; later inlining only removes possible effects.
+ _effects=FunctionEffects.analyze(this);
+ _iter.iterate(this);
+ }); }
// Materialize an inline candidate at an empty worklist. Loading queues
// the new body and affected callers before CallEnd considers inlining.
+ public boolean _loadingBody;
public void loadForInline(CompUnit cu) {
assert _phase==Phase.IterPostOpto && _iter._work.isEmpty();
- ParseAll.loadCompUnit(this,cu);
+ _loadingBody=true;
+ try { ParseAll.loadCompUnit(this,cu); }
+ finally { _loadingBody=false; }
}
// TypeCheck saves its successful analysis for Serialize. Loading bodies
@@ -518,7 +528,21 @@ public class CodeGen {
// ---------------------------
// Last check for bad programs
- public CodeGen typeCheck() { return phase(Phase.TypeCheck, _phase==Phase.FinalizeIR, () -> TypeCheck.run(this)); }
+ public Allocation _allocation;
+ public IdentityHashMap<FunNode,FunctionEffects> _effects;
+ public CodeGen allocation() {
+ if( _phase==Phase.FinalizeIR ) loopTree();
+ return phase(Phase.Allocation, _phase==Phase.LoopTree, () -> {
+ _effects = FunctionEffects.analyze(this);
+ _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 || _phase==Phase.LoopTree ) allocation();
+ return phase(Phase.TypeCheck, _phase==Phase.Allocation, () -> TypeCheck.run(this));
+ }
// ---------------------------
// TypeCheck queued surviving CLInits during its existing error walk.
@@ -527,10 +551,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));
}
// ---------------------------
@@ -571,7 +596,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);
@@ -802,6 +831,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/FunctionEffects.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java
new file mode 100644
index 00000000..9094f635
--- /dev/null
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java
@@ -0,0 +1,131 @@
+package com.seaofnodes.simple.codegen;
+
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import java.util.*;
+
+/** Effects introduced by a function, independent of its incoming memory.
+ * Scan each body once, then union effects along call edges to a fixed point.
+ * This includes recursion and paths which never reach Return. */
+public final class FunctionEffects {
+ public int[] _writes;
+ public boolean _referenceWrites;
+ public TypeMem _escapes;
+ private final ArrayList<FunNode> _callees = new ArrayList<>();
+
+ public FunctionEffects(int[] writes, boolean referenceWrites, TypeMem escapes) {
+ _writes=writes; _referenceWrites=referenceWrites; _escapes=escapes;
+ }
+ private FunctionEffects() { this(XInt.EMPTY,false,TypeMem.START); }
+
+ public static IdentityHashMap<FunNode,FunctionEffects> analyze(CodeGen code) {
+ IdentityHashMap<FunNode,FunctionEffects> effects=new IdentityHashMap<>();
+ for( FunNode fun : code._linker )
+ if( fun!=null && !fun.isDead() && !fun._type.isHigh() ) {
+ FunctionEffects effect=fun.summary()==null ? new FunctionEffects() : fun.summary()._effects;
+ effects.put(fun,effect);
+ if( fun.summary()==null ) effect.collect(fun);
+ }
+ // Sets only grow. Recursive components need no special fallback and
+ // cannot accidentally prove themselves effect-free before convergence.
+ boolean changed;
+ do {
+ changed=false;
+ for( FunctionEffects effect : effects.values() )
+ for( FunNode callee : effect._callees ) {
+ FunctionEffects child=effects.get(callee);
+ changed |= effect.merge(child);
+ }
+ } while( changed );
+ return effects;
+ }
+
+ private boolean merge(FunctionEffects other) {
+ int[] writes=other==null ? XInt.FULL : XInt.meet(_writes,other._writes);
+ boolean refs=other==null || _referenceWrites || other._referenceWrites;
+ TypeMem escapes=other==null ? TypeMem.BOT : _escapes.escapes(other._escapes);
+ boolean changed=writes!=_writes || refs!=_referenceWrites || escapes!=_escapes;
+ _writes=writes; _referenceWrites=refs; _escapes=escapes;
+ return changed;
+ }
+
+ private void collect(FunNode fun) {
+ BitSet seen=new BitSet();
+ ArrayDeque<Node> work=new ArrayDeque<>();
+ work.push(fun); work.push(fun.ret());
+ while( !work.isEmpty() ) {
+ Node n=work.pop();
+ if( seen.get(n._nid) ) continue;
+ seen.set(n._nid);
+ if( n instanceof CFGNode cfg && !(cfg instanceof ReturnNode) &&
+ (cfg==fun || !cfg.isFunLeaf()) )
+ for( Node use : cfg._outputs )
+ if( use instanceof CFGNode next && !cfg.skip(next) && !next._type.isHigh() ) work.push(next);
+ if( n.isFunLeaf() ) continue;
+ // Replacing the effect table can enable an alias-preservation peep
+ // even though no graph type changed. Wake its consumers explicitly.
+ if( n instanceof LoadNode load && "$init".equals(load._name) ) CodeGen.CODE.add(load);
+ // Raw addresses can hide a reference in an otherwise scalar store.
+ // Until raw effects have their own contract, they block ownership proofs.
+ if( n instanceof PtrToIntNode ) _referenceWrites=true;
+ if( n instanceof StoreNode st ) {
+ int alias=st._alias;
+ if( alias==1 && st.ptr()._type instanceof TypeMemPtr ptr ) {
+ Field field=ptr._obj.field(st._name);
+ if( field!=null ) alias=field._alias;
+ }
+ _writes=alias==1 ? XInt.FULL : XInt.make(_writes,alias);
+ if( reference(st.val()._type) ) {
+ _referenceWrites=true;
+ expose(st.val());
+ }
+ }
+ if( n instanceof EscapeNode esc && !esc._borrow ) {
+ _writes=XInt.make(_writes,esc.fld()._alias);
+ _referenceWrites |= reference(esc.fld()._t);
+ }
+ if( n instanceof CLInitNode init && !init.bypass() ) {
+ FunNode target=CodeGen.CODE.link(init.cu());
+ if( target==null ) merge(null);
+ else _callees.add(target);
+ }
+ if( n instanceof CallNode call ) call(call);
+ if( n instanceof CallEndNode end ) { work.push(end.call()); continue; }
+ // Memory walks find even unpinned Stores. Stop at incoming Parms,
+ // constants, and interprocedural return edges, not their cached types.
+ for( Node in : n._inputs ) if( in!=null ) work.push(in);
+ }
+ }
+
+ private static boolean reference(Type t) {
+ return !(t instanceof TypeInteger || t instanceof TypeFloat) && !t.isHigh() && t!=Type.NIL;
+ }
+
+ private void expose(Node value) {
+ // Incoming references are supplied at each imported call, not frozen
+ // into a library-wide set of possible callbacks. All reference arguments
+ // still conservatively escape when applying the summary.
+ if( value instanceof ParmNode parm && !(parm._idx==2 && parm.fun().isClz()) ) return;
+ _escapes=_escapes.escapesFrom(value._type);
+ }
+
+ private void call(CallNode call) {
+ if( Intrinsic.pure(call) ) return;
+ // The terminating native has no returning memory effects.
+ boolean exits=call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP;
+ TypeFunPtr fp=call.fptr()._type instanceof TypeFunPtr f ? f : null;
+ boolean unknown=fp==null || XInt.isHigh(fp.fidxs());
+ boolean external=unknown;
+ if( !unknown )
+ for( int idx=XInt.next(fp.fidxs(),0); idx>=0; idx=XInt.next(fp.fidxs(),idx) ) {
+ FunNode target=CodeGen.CODE.link(idx);
+ if( target==null ) external=true;
+ else _callees.add(target);
+ }
+ if( external && !exits ) { _writes=XInt.FULL; _referenceWrites=true; }
+ // Simple callees can retain parameters too. Using their actuals keeps
+ // this conservative without importing the caller's entire memory state.
+ int first=fp!=null && fp.nargs()>0 && fp.arg(0)==TypePtr.PTR ? 3 : 2;
+ for( int i=first; i<call.nIns()-1; i++ ) expose(call.in(i));
+ }
+}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java
index 6cd4035d..c6bf483d 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java
@@ -4,13 +4,14 @@ import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.*;
// The small, eagerly readable part of a function's serialized implementation.
-record FunctionSummary(TypeFunPtr sig, TypeTuple state, String name, int size, int[] classDependencyFIDXs) {
+record FunctionSummary(TypeFunPtr sig, TypeTuple state, String name, int size, int[] classDependencyFIDXs,
+ FunctionEffects effects, Allocation.Summary allocation) {
void install(CodeGen code, CompUnit cu) {
FunNode fun = new FunNode(null,sig,name,cu,null,cu._start);
fun._approxUIDs=size;
fun.init();
// First user stays in output slot zero until the summary is removed.
- SummaryNode body = new SummaryNode(state,classDependencyFIDXs,fun);
+ SummaryNode body = new SummaryNode(state,classDependencyFIDXs,effects,allocation,fun);
ParmNode rpc = new ParmNode("$rpc",0,TypeRPC.BOT,fun,code.con(TypeRPC.BOT)).init();
ParmNode mem = new ParmNode("$mem",1,TypeMem.BOT,fun,cu._start.proj(1)).init();
body.addDef(mem);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
index 882a0f8a..8026a5de 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
@@ -287,6 +287,9 @@ public abstract class ParseAll {
// into its callers without restarting whole-program analysis.
ProjNode startMem = cunit._start.proj(1);
if( startMem!=null ) code.keepUntilFinalize(startMem);
+ // Opto may have discarded declarations referenced by the saved body.
+ // Restore its dependency closure, not every declaration in the library.
+ restoreSummaries(code,elf);
Iter.imports(code,elf._nodes);
// Add the new top-level loaded class
@@ -311,6 +314,32 @@ public abstract class ParseAll {
}
}
+ private static void restoreSummaries(CodeGen code, ElfReader loaded) {
+ BitSet needed=new BitSet();
+ for( FunctionSummary summary : loaded._functions )
+ for( int fidx : summary.classDependencyFIDXs() ) needed.set(fidx);
+ boolean changed;
+ do {
+ changed=false;
+ for( CompUnit cu : code._compunits.values() ) {
+ if( cu._src!=null || cu._obj==null ) continue;
+ ElfReader elf=code.getElf(cu._obj);
+ if( elf._nodes!=null || elf._functions==null || !elf._units[0].equals(cu._fname) ) continue;
+ for( FunctionSummary summary : elf._functions ) {
+ if( !needed.get(summary.sig().fidx()) ) continue;
+ FunNode old=code._link(summary.sig().fidx());
+ if( old!=null && !old.isDead() ) continue;
+ if( cu._start==null || cu._start.isDead() ) cu.setStart(code);
+ if( cu._start.proj(1)==null )
+ code.keepUntilFinalize(new ProjNode(cu._start,1,"$mem").init());
+ summary.install(code,cu);
+ for( int fidx : summary.classDependencyFIDXs() ) needed.set(fidx);
+ changed=true;
+ }
+ }
+ } while( changed );
+ }
+
// Find the symbol in module, starting from cunit. This searches up the nested
// class chain and sideways 1 step, so that any prefix of the class chain can
// be skipped as a shortcut. Symbol can have dotted names, which then go
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..c3ae2566 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,13 @@ 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.
+ // Format 4 adds the deletable-array capability and allocation flag.
+ // Format 5 stores per-function effects, not the unit's incoming memory.
+ // Format 6 adds symbolic allocation contracts beside function effects.
+ // Format 7 carries consuming argument/field requirements.
+ // Format 8 marks effects not represented by the allocation field graph.
+ baos.write('C').write('0').write('D').write('8');
// Count unique Types
var types = new HashMap<Type,Integer>();
@@ -128,10 +134,10 @@ public class Serialize {
fun.sig().gather(types);
TypeTuple state = (TypeTuple)fun.ret()._type;
TypeMem mem = (TypeMem)state.mem();
- // Retention can happen on a path that never returns. The
- // unit's escape summary includes those native-call effects.
- TypeMem escaped = (TypeMem)((TypeTuple)fun._compunit._stop._type).mem();
- mem=mem.makeFrom(XInt.meet(mem._escFs,escaped._escFs),XInt.meet(mem._escAs,escaped._escAs));
+ // Only effects introduced by this function and its callees.
+ // Incoming memory and unrelated exported functions are not effects.
+ TypeMem escaped = CodeGen.CODE._effects.get(fun)._escapes;
+ mem=mem.makeFrom(escaped._escFs,escaped._escAs);
state=state.makeFrom(1,mem);
summaries.put(fun,state);
state.gather(types);
@@ -251,6 +257,14 @@ public class Serialize {
int[] edges = _init._edgess[fun.sig().fidx()];
baos.packed4(edges==null ? 0 : edges.length);
if( edges!=null ) for( int edge : edges ) baos.packed4(edge);
+ FunctionEffects effect=CodeGen.CODE._effects.get(fun);
+ baos.packed1(effect._referenceWrites ? 1 : 0);
+ if( effect._writes==XInt.FULL ) baos.packed4(-1);
+ else {
+ baos.packed4(XInt.bitCount(effect._writes));
+ for( int alias=XInt.next(effect._writes,0); alias>=0; alias=XInt.next(effect._writes,alias) ) baos.packed4(alias);
+ }
+ Allocation.write(baos,CodeGen.CODE._allocation.summary(fun));
}
// D - Write the nodes. Since this is expected to be the bulk of the
@@ -335,7 +349,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()!='8' )
throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file");
// B - Packed read of #strings, then strings
@@ -368,7 +382,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() != '8' )
throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" );
// B - Packed read of #strings, then strings
@@ -444,7 +458,12 @@ public class Serialize {
int size = bais.packed4();
int[] edges = new int[bais.packed4()];
for( int j = 0; j<edges.length; j++ ) edges[j]=fidxs.map(fileFidxs,bais.packed4());
- elf._functions[i]=new FunctionSummary(sig,state,name.isEmpty() ? fidxs.symbol(sig.fidx()) : name,size,edges);
+ boolean refs=bais.packed1()!=0;
+ int count=bais.packed4();
+ int[] writes=count<0 ? XInt.FULL : XInt.EMPTY;
+ for( int j=0; j<count; j++ ) writes=XInt.make(writes,aliases.map(fileAliases,bais.packed4()));
+ elf._functions[i]=new FunctionSummary(sig,state,name.isEmpty() ? fidxs.symbol(sig.fidx()) : name,size,edges,
+ new FunctionEffects(writes,refs,state.mem()),Allocation.read(bais));
}
return elf._types = new TypeRead(types,strs,fileAliases,fileFidxs,fileRpcs);
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java
index 418edaf6..c1773ece 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/TypeCheck.java
@@ -4,6 +4,7 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.Type;
import com.seaofnodes.simple.type.TypeScalar;
+import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.util.Ary;
// Reject invalid optimized programs before lowering erases their source-level
@@ -23,6 +24,11 @@ abstract class TypeCheck {
Ary<InitViewNode> views = new Ary<>(InitViewNode.class);
Ary<ArrayInitNode> arrays = new Ary<>(ArrayInitNode.class);
code._stop.walk( n -> {
+ if( n instanceof ConstantNode && n._type instanceof TypeFunPtr fp && fp.isConstant() &&
+ Intrinsic.ARRAY_DELETE.equals(code.externFunc(fp.fidx())) )
+ for( Node use : n._outputs )
+ if( !(use instanceof CallNode call && call.fptr()==n && Intrinsic.arrayDelete(call)) )
+ throw Parser.error("Array .del() must be called directly",null);
if( n.err() != null )
errs.add(n);
if( n instanceof CLInitNode ) code.add(n);
@@ -52,6 +58,13 @@ abstract class TypeCheck {
if( code._obs != null ) code._obs.error(min, min.err().getMessage());
throw min.err();
}
+ // Incoming requirements are part of the function's checked contract;
+ // Allocation has substituted and checked them at each concrete caller.
+ for( ArrayDelete deletion : code._allocation._deletes ) {
+ if( deletion._reject!=null || (!deletion.proven() && deletion._requirement==null) )
+ throw Parser.error(deletion.toString(),deletion._call._loc);
+ }
+ code._allocation.checkOwnership();
// Checked construction boundaries and views have no runtime behavior. Gathered
// above during the existing error walk; no separate graph pass/solve.
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/CLInitNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java
index fb762ff3..c82ce6c6 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java
@@ -148,7 +148,7 @@ public class CLInitNode extends CFGNode implements MultiNode {
};
CodeGen.CODE.add(parm).addDef(arg);
}
- if( CodeGen.CODE._phase.ordinal()>CodeGen.Phase.Opto.ordinal() ) {
+ if( !CodeGen.CODE._loadingBody && CodeGen.CODE._phase.ordinal()>CodeGen.Phase.Opto.ordinal() ) {
boolean repair = !target.compute().isa(target._type);
for( Node use : target._outputs )
if( use instanceof ParmNode && !use.compute().isa(use._type) ) repair = true;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
index 108dd024..58c1cc34 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
@@ -85,6 +85,10 @@ public class CallEndNode extends CFGNode implements MultiNode {
return ftype.isHigh() ? TypeTuple.STATE.dual() : TypeTuple.STATE;
// Mid-fold, just take the inlined callee's return.
if( _folding ) return in(1)._type;
+ // Keep the ordinary call/continuation CFG for this non-returning native.
+ // No memory or value comes back; mixed/unknown targets stay conservative.
+ if( tfp.isConstant() && "_exit".equals(CodeGen.CODE.externFunc(tfp.fidx())) )
+ return TypeTuple.make(Type.CONTROL,TypeMem.TOP,TypeScalar.TOP);
TypeTuple intrinsic=Intrinsic.compute(call,this);
if( intrinsic!=null ) return intrinsic;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 5506621b..94f88e9a 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -205,7 +205,7 @@ public class CallNode extends CFGNode {
// may bring escapes absent from the cached formal parameter types.
// Repair affected bounds before the next type-lifting peephole.
CodeGen code = CodeGen.CODE;
- if( code._phase.ordinal()>CodeGen.Phase.Opto.ordinal() &&
+ if( !code._loadingBody && code._phase.ordinal()>CodeGen.Phase.Opto.ordinal() &&
code._phase.ordinal()<CodeGen.Phase.Lower.ordinal() ) {
boolean repair = !fun.compute().isa(fun._type) || !cend().compute().isa(cend()._type);
for( Node use : fun._outputs )
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
index 0569f352..d57030bd 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
@@ -47,7 +47,7 @@ public class ConstantNode extends TypeNode {
return raw(type);
if( type instanceof TypeFunPtr tfp && tfp.isConstant() ) {
FunNode fun = CodeGen.CODE._link(tfp);
- if( fun != null )
+ if( fun != null && !fun.isDead() && !fun.ret().isDead() )
return new FunPtrNode(tfp,CodeGen.CODE._start,fun.ret()).init();
// TODO: A singleton FIDX can also emerge after merging and
// guarding several function pointers. Preserve that identity
@@ -86,6 +86,7 @@ public class ConstantNode extends TypeNode {
}
@Override public boolean isConst() { return true; }
+ @Override public boolean isFunLeaf() { return true; }
@Override public Type compute() { return _con; }
@Override public Node idealize() { return null; }
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java
index 8b6b347e..632b5fb4 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java
@@ -83,6 +83,8 @@ public class FunNode extends RegionNode {
}
public ParmNode rpc() { return parm(0); }
+ @Override public boolean isFunLeaf() { return true; }
+
// An unloaded body's Summary is constructed before every other user.
public SummaryNode summary() { return nOuts()>0 && out(0) instanceof SummaryNode summary ? summary : null; }
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FunPtrNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FunPtrNode.java
index 82053fd8..5e803510 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/FunPtrNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FunPtrNode.java
@@ -41,6 +41,7 @@ public class FunPtrNode extends TypeNode {
}
@Override public boolean isConst() { return true; }
+ @Override public boolean isFunLeaf() { return true; }
@Override public Type compute() {
ReturnNode ret = ret();
if( ret == null ) return _con;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/Intrinsic.java b/chapter33/src/main/java/com/seaofnodes/simple/node/Intrinsic.java
index 82626507..429b8d5c 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/Intrinsic.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/Intrinsic.java
@@ -9,6 +9,16 @@ import com.seaofnodes.simple.type.*;
// for calls whose target is not known at compile time.
public final class Intrinsic {
private Intrinsic() {}
+ public static final String ARRAY_DELETE="simple_array_delete";
+
+ public static boolean arrayDelete(CallNode call) {
+ return call.fptr()._type instanceof TypeFunPtr fp && fp.isConstant() &&
+ ARRAY_DELETE.equals(CodeGen.CODE.externFunc(fp.fidx()));
+ }
+
+ public static boolean arrayDeleteType(TypeFunPtr fp) {
+ return fp.nargs()==1 && fp.arg(0)==TypeMemPtr.NOTBOT && fp.ret()==TypeInteger.BOT;
+ }
private enum Op {
F64_BITS("simple_f64_bits",TypeFloat.F64,TypeInteger.BOT,true),
@@ -42,6 +52,9 @@ public final class Intrinsic {
}
public static Parser.ParseException err(CallNode call) {
+ if( arrayDelete(call) && (!arrayDeleteType(call.tfp()) || call.nargs()!=1 ||
+ !(call.arg(2)._type instanceof TypeMemPtr p && p._obj.isAry() && p._del && !p.nullable())) )
+ return Parser.error("Array .del() requires a non-null [^] array and no arguments",call._loc);
Op op=lookup(call);
return op==null || op.signature(call.tfp()) ? null : Parser.error(
"Intrinsic '"+op.symbol+"' requires { "+op.arg.str()+" -> "+op.ret.str()+" }",call._loc);
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/LoadNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java
index 14efa315..52dbfa8e 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java
@@ -66,6 +66,8 @@ public class LoadNode extends MemOpNode {
// Validate argument types
if( ptr0.isHigh() )
return TypeScalar.TOP;
+ if( _con instanceof TypeFunPtr && ptr0 instanceof TypeMemPtr array && array._obj.isAry() && "del".equals(_name) )
+ return _con;
if( !(mem0 instanceof TypeMem mem) )
return mem0.isHigh() ? TypeScalar.TOP : TypeScalar.BOT;
if( mem._t == Type.TOP )
@@ -136,6 +138,14 @@ public class LoadNode extends MemOpNode {
@Override
public Node idealize() {
+ if( _con instanceof TypeFunPtr && "del".equals(_name) && ptr()._type instanceof TypeMemPtr p ) {
+ if( p._obj.isAry() ) return new ExternNode(_con,Intrinsic.ARRAY_DELETE).peephole();
+ if( p._obj!=TypeStruct.BOT && !p._obj.isHigh() && !p._obj._fref ) {
+ // A forward receiver turned out to be an ordinary class with
+ // its own del member. Keep ordinary field/method semantics.
+ unlock(); _con=Type.BOTTOM; return this;
+ }
+ }
if( _type==TypeScalar.BOT ) return null;
Node mem = mem();
Node ptr = ptr();
@@ -163,6 +173,15 @@ public class LoadNode extends MemOpNode {
if( _alias == 1 )
return null;
+ // Whole-memory parameters lose individual alias types. Recover the
+ // class flag from every caller, without moving a load across a call.
+ // Wait for SCCP to finish discovering callers before folding it away.
+ if( "$init".equals(_name) && ptr._type instanceof TypeMemPtr clz &&
+ TypeStruct.startsClzPrefix(clz._obj._name) &&
+ CodeGen.CODE._phase.ordinal()>=CodeGen.Phase.IterPostOpto.ordinal() &&
+ classInitialized(mem,new BitSet()) )
+ return CodeGen.CODE.con(TypeInteger.TRUE);
+
Node slice = CLInitNode.slice(mem,_alias,this);
if( slice!=mem ) { setDef(1,slice); return this; }
@@ -230,6 +249,57 @@ public class LoadNode extends MemOpNode {
return null;
}
+ // A class flag has one global slot per alias. Unknown memory and cycles
+ // fail the proof; a cycle must not establish its own initialization.
+ private boolean classInitialized(Node mem, BitSet active) {
+ addDep(mem);
+ if( mem._type.isHigh() ) return true;
+ if( mem._type instanceof TypeMem tm && tm._alias==_alias && tm._t==TypeInteger.TRUE ) return true;
+ if( active.get(mem._nid) ) return false;
+ active.set(mem._nid);
+ boolean ready=false;
+ if( mem instanceof MemMergeNode merge )
+ ready=classInitialized(merge.alias(_alias),active);
+ else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CLInitNode init ) {
+ addDep(init);
+ FunNode target=CodeGen.CODE.link(init.cu());
+ if( target!=null ) {
+ addDep(target);
+ SummaryNode summary=target.summary();
+ if( summary!=null && !XInt.bit(summary._effects._writes,_alias) )
+ ready=classInitialized(init.mem(),active);
+ }
+ }
+ else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CallEndNode end ) {
+ addDep(end);
+ if( end.in(0) instanceof CallNode call ) {
+ Type ftype=addDep(call.fptr())._type;
+ FunNode target=ftype instanceof TypeFunPtr fp && fp.isConstant() ? CodeGen.CODE.link(fp.fidx()) : null;
+ var effects=CodeGen.CODE._effects;
+ if( target!=null && effects!=null ) {
+ addDep(target);
+ var effect=effects.get(target);
+ if( effect!=null && !XInt.bit(effect._writes,_alias) )
+ ready=classInitialized(call.mem(),active);
+ }
+ }
+ }
+ else if( mem instanceof StoreNode st ) {
+ if( st._alias==_alias ) ready=addDep(st.val())._type==TypeInteger.TRUE;
+ else if( st._alias>1 ) ready=classInitialized(st.mem(),active);
+ } else if( mem instanceof PhiNode phi ) {
+ addDep(phi.region());
+ if( !phi.inProgress() ) {
+ ready=true;
+ for( int i=1; i<phi.nIns(); i++ )
+ if( !addDep(phi.region().in(i))._type.isHigh() &&
+ !classInitialized(phi.in(i),active) ) { ready=false; break; }
+ }
+ }
+ active.clear(mem._nid);
+ return ready;
+ }
+
// Load a flavored zero from a New
private Node zero(NewNode nnn) {
// Object fields acquire values from their initializer's Stores.
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java
index 96a237e1..88a1242a 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java
@@ -16,20 +16,23 @@ import java.util.IdentityHashMap;
*/
public class NewNode extends Node implements MultiNode {
public TypeStruct _ts;
- public NewNode( TypeStruct ts, Node ctrl, Node size ) { super(ctrl,size); _ts = ts; }
+ public final boolean _deletable;
+ public NewNode( TypeStruct ts, Node ctrl, Node size ) { this(ts,ctrl,size,false); }
+ public NewNode( TypeStruct ts, Node ctrl, Node size, boolean deletable ) { super(ctrl,size); _ts = ts; _deletable=deletable; }
public Node ctrl() { return in(0); }
public Node size() { return in(1); }
// --- Serialization
- public NewNode(NewNode nnn) { super(nnn); _ts = nnn._ts; }
+ public NewNode(NewNode nnn) { super(nnn); _ts = nnn._ts; _deletable=nnn._deletable; }
@Override public Tag serialTag() { return Tag.New; }
@Override public void packed( BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node, Integer> anodes ) {
baos.packed2(types.get(_ts));
+ baos.write(_deletable ? 1 : 0);
}
static Node make( BAOS bais, Type[] types) {
TypeStruct ts = (TypeStruct)types[bais.packed2()];
- return new NewNode(ts,null,null);
+ return new NewNode(ts,null,null,bais.read()!=0);
}
@Override public String label() { return "new_"+(_ts.isAry() ? "ary_"+_ts._fields[1]._t.str() : _ts.str()); }
@@ -42,7 +45,7 @@ public class NewNode extends Node implements MultiNode {
if( ctrl()._type.isHigh() )
return TypeTuple.DEAD_NEW;
TypeStruct ts = _ts.isAry() ? _ts : _ts.makeInit();
- return TypeTuple.make(TypeMemPtr.make(_ts),
+ return TypeTuple.make(TypeMemPtr.make(_ts).withDelete(_deletable),
// Arrays get pre-zeroed by constructor.
// Object fields start at Scalar.BOT; declaration
// defaults are explicit Stores. This is private
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 ad4f47e0..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());
@@ -154,6 +156,11 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
public boolean isConst() { return false; }
+ // Stop a backward, function-local input walk here. Entry/caller links,
+ // constant anchors, and opaque summaries are not part of the local body.
+ // This is not a CFG-exit or serialization-boundary predicate.
+ public boolean isFunLeaf() { return false; }
+
// ------------------------------------------------------------------------
// Graph Node & Edge manipulation
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java
index aea402f6..c61d87b7 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java
@@ -49,6 +49,8 @@ public class ParmNode extends PhiNode {
public FunNode fun() { return (FunNode)in(0); }
+ @Override public boolean isFunLeaf() { return true; }
+
// The hidden constructor receiver has private memory for checking reads.
// Only borrowed source parameters need an initially empty field promise.
private Type declaredBound() {
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/node/StartNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/StartNode.java
index 36583884..bfabbb92 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/StartNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/StartNode.java
@@ -35,6 +35,8 @@ public class StartNode extends LoopNode implements MultiNode {
@Override public Tag serialTag() { return Tag.Start; }
public Type arg() { return _arg; }
+ @Override public boolean isFunLeaf() { return true; }
+
@Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) {
return p.p(label());
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/StopCUNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/StopCUNode.java
index ead635dd..75000917 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/StopCUNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/StopCUNode.java
@@ -79,7 +79,9 @@ public class StopCUNode extends StopNode {
// Capture (precisely?) all escaping pointer aliases and fidxs.
// Escaped fidxs means the linked world can call that function;
// escaped aliases means the linked world can R/W those aliases.
- xmem = xmem.escapesFrom(tret.ret(),start.outside(this));
+ // A dependency on an imported initializer is an internal call.
+ // Its incidental last expression is not an exported result.
+ if( !fun.isClz() || pub ) xmem = xmem.escapesFrom(tret.ret(),start.outside(this));
xmem = (TypeMem)xmem.meet(tret.mem());
}
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index 5b945457..ea2bdf03 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -9,23 +9,36 @@ import java.util.HashMap;
public class SummaryNode extends CFGNode implements MultiNode {
public TypeTuple _state;
+ public final FunctionEffects _effects;
+ public final Allocation.Summary _allocation;
// Callees and touched class initializers, by FIDX, for class-init cycle checks.
public final int[] _classDependencyFIDXs;
public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, Node... inputs) {
+ this(state,classDependencyFIDXs,new FunctionEffects(XInt.FULL,true,state.mem()),inputs);
+ }
+ public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, FunctionEffects effects, Node... inputs) {
+ this(state,classDependencyFIDXs,effects,null,inputs);
+ }
+ public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, FunctionEffects effects, Allocation.Summary allocation, Node... inputs) {
super(inputs);
_state = state;
+ _effects = effects;
+ _allocation = allocation;
_classDependencyFIDXs = classDependencyFIDXs;
CodeGen.CODE.add(CodeGen.CODE._globalEscapes);
}
@Override public String label() { return "Summary"; }
+ @Override public boolean isFunLeaf() { return true; }
@Override public boolean blockHead() { return true; }
@Override public Type compute() {
if( in(0)._type.isHigh() ) return TypeTuple.STATE.dual();
// A library summary does not forget escapes already present in the caller.
TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
- mem = (TypeMem)mem.meet(_state.mem());
+ if( _effects._writes!=XInt.EMPTY || _state.mem()._one )
+ mem = (TypeMem)mem.meet(_state.mem());
+ else mem = mem.escapes(_state.mem());
for( int i = firstArgument(); i<nIns(); i++ ) {
Type arg = in(i)._type;
// Only opaque arguments can hide identities supplied by outside code.
@@ -51,7 +64,7 @@ public class SummaryNode extends CFGNode implements MultiNode {
private int firstArgument() {
if( !(in(0) instanceof FunNode fun) ) return 2;
TypeFunPtr sig = fun.sig();
- return sig.nargs()>0 && sig.arg(0)==TypePtr.PTR ? 3 : 2;
+ return fun.isClz() || sig.nargs()>0 && sig.arg(0)==TypePtr.PTR ? 3 : 2;
}
@Override boolean _upgradeType(HashMap<String,Type> types) {
TypeTuple state = (TypeTuple)_state.upgradeType(types);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
index 64234045..8dad94ec 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
@@ -26,19 +26,20 @@ final class Allocations {
// Parse ary[ length_expr ]
if( P.match("[") ) {
boolean readonly = P.match("~");
+ boolean deletable = !readonly && P.match("^");
if( P.match("]") ) {
P.require("{");
- return P.arrays.parse(t,readonly,null,site);
+ return P.arrays.parse(t,readonly,deletable,null,site);
}
Node len = P.expressions.parseAssignment().keep();
P.require("]");
- if( P.match("{") ) return P.arrays.parse(t,readonly,len,site);
+ if( P.match("{") ) return P.arrays.parse(t,readonly,deletable,len,site);
if( !t.makeZero().isa(t) )
throw Parser.error("Cannot allocate a non-nullable, since arrays are always zero/null filled",site);
- if( readonly ) return new ReadOnlyNode(allocArray(P.types.typeAry(t,true),len)).peephole();
- return allocArray(P.types.typeAry(t,false),len);
+ if( readonly ) return new ReadOnlyNode(allocArray(P.types.typeAry(t,true),len,false)).peephole();
+ return allocArray(P.types.typeAry(t,false),len,deletable);
} else if( t instanceof TypeMemPtr ary && ary._obj.isAry() && P.match("{") ) {
- return P.arrays.parse(ary._obj.field("[]")._t,ary._ro,null,site);
+ return P.arrays.parse(ary._obj.field("[]")._t,ary._ro,ary._del,null,site);
} else {
if( !(t instanceof TypeMemPtr tmp) )
throw Parser.error("Cannot allocate a "+t.str(),site);
@@ -92,7 +93,7 @@ final class Allocations {
return args;
}
- private Node allocArray(TypeStruct ts, Node len) {
+ private Node allocArray(TypeStruct ts, Node len, boolean deletable) {
Field lenFld = ts.field("#" );
Field bodyFld = ts.field("[]");
@@ -101,7 +102,7 @@ final class Allocations {
Node size = P.peep(new AddNode(base,P.peep(new ShlNode(null,len,P.con(scale)))));
// Build a NewNode; takes in and puts out all aliases.
- NewNode nnn = new NewNode(ts, P.ctrl(), size ).init();
+ NewNode nnn = new NewNode(ts, P.ctrl(), size, deletable ).init();
ProjNode self = new ProjNode(nnn,0,ts.str()).init().keep();
ProjNode smem = new ProjNode(nnn,1,"#selfMem").init().keep();
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..99d990f1 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
@@ -24,7 +24,7 @@ final class ArrayInitializers {
ArrayInitializers(Parser P) { this.P=P; }
// Opening brace consumed; an absent length means a list with inferred size.
- Node parse(Type elem, boolean readonly, Node len, Lexer site) {
+ Node parse(Type elem, boolean readonly, boolean deletable, Node len, Lexer site) {
int pos=P.pos();
Type indexType=P.types.parseType();
String index=indexType==null ? null : P._lexer.matchId();
@@ -50,7 +50,7 @@ final class ArrayInitializers {
Field body=ts.field("[]"), length=ts.field("#");
Node size=new AddNode(ConFldOffNode.make(ts,"[]"),
new ShlNode(null,len,P.con(ts.aryScale())).peephole()).peephole();
- NewNode alloc=new NewNode(ts,P.ctrl(),size).init();
+ NewNode alloc=new NewNode(ts,P.ctrl(),size,deletable).init();
Node self=new ProjNode(alloc,0,ts.str()).init().keep();
Node mem=new ProjNode(alloc,1,"#arrayMem").init().keep();
Node slen=new StoreNode(site,"#",length._alias,TypeInteger.U32,null,mem,self,
@@ -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/References.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
index 91cf6859..f4103fe6 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -187,6 +187,7 @@ final class References {
}
}
+ boolean arrayMethod="del".equals(name) && (ts==null || ts.isAry());
Field fld = ts==null ? null : ts.field(name);
if( fld==null && ts!=null && !TypeStruct.startsClzPrefix(ts._name) ) {
Type clz0 = Parser.TYPES.get(TypeStruct.addClzPrefix(ts._name));
@@ -198,7 +199,7 @@ final class References {
}
if( fld==null && ts!=null )
fld = P.types.fieldOrOpen(ts,name,false);
- if( fld==null && ts!=null && !P.types.latestStruct(ts)._open )
+ if( fld==null && ts!=null && !arrayMethod && !P.types.latestStruct(ts)._open )
throw Parser.error("Accessing unknown field '"+name+"' from '*"+ts._name+"'",site);
// We have to record "active touches" of a new class, to track when we
@@ -222,6 +223,7 @@ final class References {
// Disambiguate "obj.fld==x" boolean test from "obj.fld=x" field assignment
if( pre==0 && P.matchOpx('=','=') ) {
+ if( arrayMethod && ts!=null && ts.isAry() ) throw Parser.error("Array .del is not a writable field",site);
// Field assignment
Node val = P.expressions.parseAssignment().keep();
// Lift value for store
@@ -248,11 +250,21 @@ final class References {
decl = conary.elem();
// Load field
- Node load = P.peep(new LoadNode(site,name,alias,P.ctrl(),mem,expr,off));
+ LoadNode member=new LoadNode(site,name,alias,P.ctrl(),mem,expr,off);
+ if( arrayMethod ) {
+ // Resolve like a field load, including forward receiver types.
+ // The generic memory-pointer receiver is a real ABI argument;
+ // the intrinsic checks the array capability after types settle.
+ int fidx=P._code.fidx(P._ref._cname);
+ P._code.externFunc(fidx,Intrinsic.ARRAY_DELETE);
+ member._con=TypeFunPtr.make(false,new Type[]{TypeMemPtr.NOTBOT},TypeInteger.BOT).makeFrom(fidx);
+ }
+ Node load = P.peep(member);
// Check for assign-update, "ptr.fld += expr" or "ary[idx]++"
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
if( ch!=0 ) {
+ if( arrayMethod && ts!=null && ts.isAry() ) throw Parser.error("Array .del is not a writable field",site);
if( fld!=null && decl==Type.BOTTOM && !ts._fref )
throw Parser.error( "'" + ts._name + "' is not fully initialized, field '" + fld._fname + "' needs to be set in a constructor",site );
Node op = P.expressions.opAssign(ch,load, decl ).keep();
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/parser/Types.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
index 501924f0..92117531 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
@@ -70,6 +70,8 @@ final class Types {
throw Parser.error("Type "+t0+" cannot be null",site);
} else if( P.match("[~]") ) {
t2 = TypeMemPtr.make(typeAry(t2,true)).makeRO();
+ } else if( P.match("[^]") ) {
+ t2 = TypeMemPtr.make(typeAry(t2,false)).withDelete(true);
} else if( P.match("[]") ) {
t2 = TypeMemPtr.make(typeAry(t2,false));
} else
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() ) {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java
index d9e11f8f..02d26a1e 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java
@@ -32,13 +32,16 @@ public class TypeMemPtr extends TypeNil {
// This reference may still depend on unfinished construction. Independent
// two-point lattice: meet ORs the restriction, dual complements it.
public boolean _partial;
+ // Capability to consume this array. Ordinary array types also accept
+ // borrowed deletable arrays; meet therefore ANDs this capability.
+ public boolean _del;
- public boolean _one; // Singleton pointer value; the pointer itself is constant.
+ public boolean _one; // Singleton identity; arrays also need a concrete payload.
public boolean _pub; // Escaped/public pointer. False means constructor-private.
private static final Ary<TypeMemPtr> FREE = new Ary<>(TypeMemPtr.class);
private TypeMemPtr(byte nil, TypeStruct obj, boolean one, boolean pub) { super(TMEMPTR,nil); init(nil,obj,one,pub); }
- private TypeMemPtr init(byte nil, TypeStruct obj, boolean one, boolean pub) { _nil = nil; _obj = obj; _ro = obj==TypeStruct.BOT; _partial = obj==TypeStruct.BOT; _one = one; _pub = pub; return this; }
+ private TypeMemPtr init(byte nil, TypeStruct obj, boolean one, boolean pub) { _nil = nil; _obj = obj; _ro = obj==TypeStruct.BOT; _partial = obj==TypeStruct.BOT; _del=false; _one = one; _pub = pub; return this; }
// Return a filled-in TypeMemPtr; either from free list or alloc new.
static TypeMemPtr malloc(byte nil, TypeStruct obj, boolean one, boolean pub) {
return FREE.isEmpty() ? new TypeMemPtr(nil,obj,one,pub) : FREE.pop().init(nil,obj,one,pub);
@@ -49,10 +52,10 @@ public class TypeMemPtr extends TypeNil {
return make(nil,obj,one,true);
}
public static TypeMemPtr make(byte nil, TypeStruct obj, boolean one, boolean pub) {
- return make(nil,obj,one,pub,obj==TypeStruct.BOT,obj==TypeStruct.BOT);
+ return make(nil,obj,one,pub,obj==TypeStruct.BOT,obj==TypeStruct.BOT,false);
}
- private static TypeMemPtr make(byte nil, TypeStruct obj, boolean one, boolean pub, boolean ro, boolean partial) {
- TypeMemPtr tmp = malloc(nil, obj, one, pub).access(ro).partial(partial);
+ private static TypeMemPtr make(byte nil, TypeStruct obj, boolean one, boolean pub, boolean ro, boolean partial, boolean del) {
+ TypeMemPtr tmp = malloc(nil, obj, one, pub).access(ro).partial(partial).deletable(del);
TypeMemPtr t2 = tmp.intern();
if( t2==tmp ) return tmp;
return VISIT.isEmpty() ? t2.free(tmp) : t2.delayFree(tmp);
@@ -75,20 +78,25 @@ public class TypeMemPtr extends TypeNil {
public static TypeMemPtr makeNullable(TypeStruct obj) { return make((byte)3, obj); }
public static TypeMemPtr makePrivate (TypeStruct obj) { return make((byte)2, obj, false, false); }
- public TypeMemPtr makeFrom(TypeStruct obj) { return obj==_obj ? this : make(_nil, obj, _one, _pub,_ro,_partial); }
+ public TypeMemPtr makeFrom(TypeStruct obj) { return obj==_obj ? this : make(_nil, obj, _one, _pub,_ro,_partial,_del); }
public TypeMemPtr makeNullable() { return makeFrom((byte)3); }
/** Inferred mutable local: nullable, public and non-singleton. */
public TypeMemPtr makeVar() { return (TypeMemPtr)makeStorage(); }
/** Public-memory shape: nullable and non-singleton, preserving the referent. */
- @Override TypeMemPtr _makeStorage() { return make(_nil,_obj._makeStorage(),false,true,_ro,_partial); }
- @Override TypeMemPtr makeFrom(byte nil) { return nil==_nil ? this : make(nil, _obj, _one, _pub,_ro,_partial); }
+ @Override TypeMemPtr _makeStorage() { return make(_nil,_obj._makeStorage(),false,true,_ro,_partial,_del); }
+ @Override TypeMemPtr makeFrom(byte nil) { return nil==_nil ? this : make(nil, _obj, _one, _pub,_ro,_partial,_del); }
@Override public Type nonZero() { return makeFrom((byte)(_nil <= 1 ? 1 : 2)); }
private TypeMemPtr access(boolean ro) { _ro=ro; return this; }
private TypeMemPtr partial(boolean partial) { _partial = partial; return this; }
+ private TypeMemPtr deletable(boolean del) { _del=del; return this; }
+
+ public TypeMemPtr withDelete(boolean del) {
+ return del==_del ? this : make(_nil,_obj,_one,_pub,_ro,_partial,del);
+ }
public TypeMemPtr withPartial(boolean partial) {
- return partial==_partial ? this : make(_nil,_obj,_one,_pub,_ro,partial);
+ return partial==_partial ? this : make(_nil,_obj,_one,_pub,_ro,partial,_del);
}
// A partial declaration promises no initialized slots. Actual callers may
@@ -121,6 +129,7 @@ public class TypeMemPtr extends TypeNil {
TypeMemPtr ptr = malloc(_nil, _obj, _one, _pub);
ptr._ro = ro;
ptr._partial = _partial;
+ ptr._del = _del;
TypeMemPtr res = ptr.intern();
if( res==ptr ) return ptr;
return VISIT.isEmpty() ? res.free(ptr) : res.delayFree(ptr);
@@ -130,6 +139,7 @@ public class TypeMemPtr extends TypeNil {
// must agree in both directions. A read-only outer view can weaken access.
@Override public boolean accessISA(Type dst) {
if( !(dst instanceof TypeMemPtr ptr) ) return true;
+ if( ptr._del && !_del ) return false;
if( _ro && !ptr._ro ) return false;
if( ptr._ro || _obj._fields==null || ptr._obj._fields==null || !_obj.isAry() || !ptr._obj.isAry() ) return true;
Type a = _obj._fields[1]._t, b = ptr._obj._fields[1]._t;
@@ -143,54 +153,65 @@ public class TypeMemPtr extends TypeNil {
public static final TypeMemPtr NOTBOT = make((byte)2,TypeStruct.BOT);
public static final TypeMemPtr TEST= make((byte)2, TypeStruct.TEST);
- public static void gather(ArrayList<Type> ts) { ts.add(NOTBOT); ts.add(BOT); ts.add(TEST); ts.add(TEST.makeRO()); ts.add(TEST.withPartial(true)); ts.add(TEST.withPartial(true).makeRO()); }
+ public static void gather(ArrayList<Type> ts) { ts.add(NOTBOT); ts.add(BOT); ts.add(TEST); ts.add(TEST.makeRO()); ts.add(TEST.withPartial(true)); ts.add(TEST.withPartial(true).makeRO()); ts.add(TEST.withDelete(true)); }
@Override
public TypeNil xmeet(Type t) {
TypeMemPtr that = (TypeMemPtr) t;
assert !isFree() && !that.isFree();
- // Can't keep _one if mixing two unequal singletons; the result is not
- // either singleton. Once either side is public, the meet is public.
- boolean one = _one && that._one && (_obj==that._obj || !(_obj.isConAry() || that._obj.isConAry()));
- return make(xmeet0(that), (TypeStruct)_obj.meet(that._obj), one, _pub | that._pub,_ro | that._ro, _partial | that._partial);
+ // Shape and singleton are independent lattice coordinates. Testing
+ // shape equality here breaks associativity and meet/join symmetry.
+ boolean one = _one && that._one;
+ return make(xmeet0(that), (TypeStruct)_obj.meet(that._obj), one, _pub | that._pub,_ro | that._ro, _partial | that._partial, _del & that._del);
}
@Override
- TypeMemPtr xdual() { return malloc( dual0(), _obj.dual(), !_one, !_pub).access(!_ro).partial(!_partial); }
+ TypeMemPtr xdual() { return malloc( dual0(), _obj.dual(), !_one, !_pub).access(!_ro).partial(!_partial).deletable(!_del); }
@Override TypeMemPtr rdual() {
if( _dual!=null ) return dual();
assert !_terned;
- TypeMemPtr d = malloc(dual0(), null, !_one, !_pub).access(!_ro).partial(!_partial);
+ TypeMemPtr d = malloc(dual0(), null, !_one, !_pub).access(!_ro).partial(!_partial).deletable(!_del);
(_dual = d)._dual = this; // Cross link duals
d._obj = _obj._terned ? _obj.dual() : _obj.rdual();
return d;
}
// RHS is NIL; do not deep-dual when crossing the center line
- @Override Type meet0() { return _nil==3 ? this : make((byte)3,_obj,false,true,_ro,_partial); }
+ @Override Type meet0() { return _nil==3 ? this : make((byte)3,_obj,false,true,_ro,_partial,_del); }
- @Override boolean _isConstant() { return _one; }
+ @Override boolean _isConstant() {
+ // A union of literal arrays can retain the singleton coordinate but
+ // no longer describes one concrete payload. Class objects have their
+ // own singleton identity, independent of their mutable field values.
+ return _one && (!_obj.isAry() || _obj.isConAry() &&
+ _obj._fields[0]._t instanceof TypeInteger len && len.isConstant() &&
+ len.value()==((TypeConAry)_obj._fields[1]._t).len());
+ }
@Override boolean _isFinal() { return _ro; }
@Override TypeMemPtr _makeRO() { return withAccess(true); }
- @Override TypeMemPtr _close( String name, HashMap<String, Type> TYPES ) { return malloc(_nil,_obj._close(name, TYPES ),_one,_pub).access(_ro).partial(_partial); }
+ @Override TypeMemPtr _close( String name, HashMap<String, Type> TYPES ) {
+ if( _obj==TypeStruct.BOT || _obj==TypeStruct.TOP ) return this;
+ return malloc(_nil,_obj._close(name, TYPES ),_one,_pub).access(_ro).partial(_partial).deletable(_del);
+ }
@Override Type _upgradeType(HashMap<String,Type> TYPES) {
+ if( _obj==TypeStruct.BOT || _obj==TypeStruct.TOP ) return this;
return makeFrom((TypeStruct)_obj._upgradeType(TYPES));
}
@Override public int log_size() { return 3; } // (1<<3)==8-byte pointers
- @Override int hash() { return (_partial ? 16384 : 0) ^ (_ro ? 8192 : 0) ^ _obj.hashCode() ^ super.hash() ^ (_one ? 2048 : 0) ^ (_pub ? 4096 : 0); }
+ @Override int hash() { return (_del ? 32768 : 0) ^ (_partial ? 16384 : 0) ^ (_ro ? 8192 : 0) ^ _obj.hashCode() ^ super.hash() ^ (_one ? 2048 : 0) ^ (_pub ? 4096 : 0); }
@Override boolean eq(Type t) {
TypeMemPtr ptr = (TypeMemPtr)t; // Invariant
- return _partial==ptr._partial && _ro==ptr._ro && super.eq(ptr) && _one == ptr._one && _pub == ptr._pub && _obj == ptr._obj;
+ return _del==ptr._del && _partial==ptr._partial && _ro==ptr._ro && super.eq(ptr) && _one == ptr._one && _pub == ptr._pub && _obj == ptr._obj;
}
@Override boolean cycle_eq(Type t) {
if( t._type != TMEMPTR ) return false;
TypeMemPtr ptr = (TypeMemPtr)t; // Invariant
- return _partial==ptr._partial && _ro==ptr._ro && super.eq(ptr) && _one == ptr._one && _pub == ptr._pub && _obj.cycle_eq(ptr._obj);
+ return _del==ptr._del && _partial==ptr._partial && _ro==ptr._ro && super.eq(ptr) && _one == ptr._one && _pub == ptr._pub && _obj.cycle_eq(ptr._obj);
}
@Override public int nkids() { return 1; }
@@ -198,7 +219,7 @@ public class TypeMemPtr extends TypeNil {
@Override public void set( int idx, Type t ) { _obj = (TypeStruct)t; }
// Reserve tags for null/not, one/general, public/private and read-only and incomplete access
- @Override int TAGOFF() { return 32; }
+ @Override int TAGOFF() { return 64; }
@Override public void packed( BAOS baos, HashMap<String,Integer> strs ) {
assert _nil>=2;
baos.write(TAGOFFS[_type]
@@ -206,23 +227,24 @@ public class TypeMemPtr extends TypeNil {
+ (!_one ? 0 : 2)
+ (!_pub ? 0 : 4)
+ (!_ro ? 0 : 8)
- + (!_partial ? 0 : 16) );
+ + (!_partial ? 0 : 16)
+ + (!_del ? 0 : 32) );
}
static TypeMemPtr packed( int tag, BAOS bais ) {
- return malloc((byte)((tag&1)+2),null,(tag&2)==2,(tag&4)==4).access((tag&8)==8).partial((tag&16)==16);
+ return malloc((byte)((tag&1)+2),null,(tag&2)==2,(tag&4)==4).access((tag&8)==8).partial((tag&16)==16).deletable((tag&32)==32);
}
@Override public String str() {
if( this==BOT ) return "PtrBot";
if( this==TOP ) return "PtrTop";
if( this== NOTBOT) return "*void";
- return (_partial ? "^" : "")+x()+"*"+(_obj==null?"---":_obj.str())+q();
+ return (_partial ? "^" : "")+x()+"*"+(_obj==null?"---":_obj.str())+(_del ? "[^]" : "")+q();
}
@Override SB _print(SB sb, BitSet visit, boolean html ) {
if( this==BOT ) return sb.p("PtrBot");
if( this==TOP ) return sb.p("PtrTop");
if( this== NOTBOT) return sb.p("*void");
- return _obj.print(sb.p(_partial ? "^" : "").p(x()).p("*"),visit,html).p(q());
+ return _obj.print(sb.p(_partial ? "^" : "").p(x()).p("*"),visit,html).p(_del ? "[^]" : "").p(q());
}
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/BrainFuckTest.java b/chapter33/src/test/java/com/seaofnodes/simple/BrainFuckTest.java
index 07e702c7..cbc86d92 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/BrainFuckTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/BrainFuckTest.java
@@ -14,8 +14,6 @@ import static org.junit.Assert.assertEquals;
public class BrainFuckTest {
@Test public void testBrainFuckAryu8() throws IOException {
-
-
String brain_fuck = "Hello World!\n";
String src =
"""
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java
index b1caae96..9cb5dacc 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java
@@ -21,7 +21,16 @@ public class Chapter18Test {
"int x=0; while(arg) { if(arg==2) while(1) { x++; } x++; arg--; } return x;"
};
for( String src : sources ) {
- CodeGen code = new CodeGen(src).driver(CodeGen.Phase.LoopTree);
+ CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck);
+ code._stop.walk(n -> {
+ assertFalse("Analysis must not insert synthetic exits",n instanceof NeverNode);
+ if( n instanceof LoopNode loop && !(loop instanceof StartNode) ) {
+ assertSame(loop,loop._ltree._head);
+ assertNotNull(loop._ltree._par);
+ }
+ return null;
+ });
+ code.driver(CodeGen.Phase.Unlink);
int[] nevers = {0};
code._stop.walk(n -> {
if( n instanceof FunNode fun )
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
new file mode 100644
index 00000000..fa52d09f
--- /dev/null
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
@@ -0,0 +1,2121 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.type.TypeFunPtr;
+import com.seaofnodes.simple.type.TypeMemPtr;
+import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeMem;
+import com.seaofnodes.simple.type.TypeScalar;
+import com.seaofnodes.simple.type.TypeTuple;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/** Small allocation poster children. Keep calls visible: this tests summaries,
+ * not whether an inliner happens to put the allocations in the right function. */
+public class Chapter33Test {
+ private static final String THING = """
+ struct Thing {
+ i64 x;
+ new Thing = { i64 x -> self.x=x; };
+ };
+ val read_noInline = { Thing t -> t.x; };
+ """;
+
+ private static CodeGen compile(String source) {
+ return new CodeGen(source).driver(CodeGen.Phase.TypeCheck);
+ }
+
+ private static List<Allocation.Site> allocations(Allocation.Summary sum, String type) {
+ sum.requireSupported();
+ var sites = new ArrayList<Allocation.Site>();
+ for( var site : sum._sites )
+ if( site._allocation!=null && site._allocation._ts._name.endsWith("."+type) )
+ sites.add(site);
+ return sites;
+ }
+
+ // 1. A call borrows a temporary. The caller can reclaim it on return.
+ @Test public void testAllocationLocalFrame() {
+ CodeGen code = compile(THING+"""
+ val work_noInline = { i64 n ->
+ val t=new Thing(n);
+ return read_noInline(t);
+ };
+ return work_noInline(arg);
+ """);
+ var sites = allocations(code._allocation.summary("work_noInline"),"Thing");
+ assertEquals(1,sites.size());
+ assertEquals("frame",sites.get(0).destination());
+ assertEquals("17",Eval2.eval(code,17));
+ }
+
+ // 2. A factory returns a graph through another factory. Both objects need
+ // result destinations, but the final consuming caller owns them locally.
+ @Test public void testAllocationFactoryGraph() {
+ CodeGen code=compile(THING+"""
+ struct Box {
+ Thing child;
+ new Box = { Thing child -> self.child=child; };
+ };
+ val make_noInline = { i64 n -> new Box(new Thing(n)); };
+ val forward_noInline = { i64 n -> make_noInline(n); };
+ val use_noInline = { Box b -> b.child.x; };
+ val work_noInline = { i64 n -> use_noInline(forward_noInline(n)); };
+ return work_noInline(arg);
+ """);
+ for( String name : new String[]{"make_noInline","forward_noInline"} ) {
+ var sum = code._allocation.summary(name);
+ assertEquals("result",allocations(sum,"Box" ).get(0).destination());
+ assertEquals("result",allocations(sum,"Thing").get(0).destination());
+ }
+ var work = code._allocation.summary("work_noInline");
+ assertEquals("frame",allocations(work,"Box" ).get(0).destination());
+ assertEquals("frame",allocations(work,"Thing").get(0).destination());
+ assertEquals("23",Eval2.eval(code,23));
+ }
+
+ private static final String HOLDER = """
+ struct Holder { Thing !c = new Thing(0); };
+ """;
+
+ // 3. A fresh reference escapes through a parameter, not the return value.
+ @Test public void testAllocationStoreThroughArgument() {
+ CodeGen code=compile(THING+HOLDER+"""
+ val fill_noInline = { !Holder h, i64 n -> h.c = new Thing(n); return n; };
+ val work_noInline = { i64 n ->
+ val h = new Holder;
+ fill_noInline(h,n);
+ return h.c.x;
+ };
+ return work_noInline(arg);
+ """);
+ var fill = allocations(code._allocation.summary("fill_noInline"),"Thing");
+ assertEquals(1,fill.size());
+ assertEquals("arg3",fill.get(0).destination()); // arg2 is the class receiver
+ for( var site : allocations(code._allocation.summary("work_noInline"),"Thing") )
+ assertEquals("frame",site.destination());
+ assertEquals("31",Eval2.eval(code,31));
+ }
+
+ // 4. One shared factory, two call sites, two unrelated destinations.
+ @Test public void testAllocationSeparateDestinations() {
+ CodeGen code=compile(THING+HOLDER+"""
+ val make_noInline = { i64 n -> new Thing(n); };
+ val fill_noInline = { !Holder a, !Holder b, i64 n ->
+ a.c = make_noInline(n);
+ b.c = make_noInline(n+1);
+ return n;
+ };
+ val a = new Holder, b = new Holder;
+ fill_noInline(a,b,arg);
+ return a.c.x*10+b.c.x;
+ """);
+ var sites=allocations(code._allocation.summary("fill_noInline"),"Thing");
+ assertEquals(2,sites.size());
+ assertNotEquals(sites.get(0)._name,sites.get(1)._name);
+ var destinations=new ArrayList<String>();
+ for( var site : sites ) destinations.add(site.destination());
+ Collections.sort(destinations);
+ assertEquals(List.of("arg3","arg4"),destinations);
+ assertEquals("45",Eval2.eval(code,4));
+ String dump=code._allocation.toString();
+ assertTrue(dump.contains("[arg3]"));
+ assertTrue(dump.contains(".c -->"));
+ assertTrue(dump.indexOf("+-- fill_noInline\n") < dump.indexOf("+-- make_noInline\n"));
+ }
+
+ // A join requires BOTH possible owners; it must not pick whichever input
+ // happens to be visited first. Alias actual arguments at a call as well.
+ @Test public void testAllocationConditionalAndAliasedOwners() {
+ CodeGen code=compile(THING+HOLDER+"""
+ val fill_noInline = { !Holder a, !Holder b, i64 n ->
+ val h=n ? a : b;
+ h.c=new Thing(n);
+ return n;
+ };
+ val a=new Holder, b=new Holder;
+ fill_noInline(a,b,arg);
+ fill_noInline(a,a,arg+1);
+ return a.c.x;
+ """);
+ var sites=allocations(code._allocation.summary("fill_noInline"),"Thing");
+ assertEquals(1,sites.size());
+ assertEquals("arg3 & arg4",sites.get(0).destination());
+ assertEquals("8",Eval2.eval(code,7));
+ }
+
+ @Test public void testAllocationBorrowAndObjectCycle() {
+ CodeGen borrow=compile(THING+"""
+ val choose_noInline={ Thing a, Thing b, i64 n -> n ? a : b; };
+ return read_noInline(choose_noInline(new Thing(arg),new Thing(arg+1),arg));
+ """);
+ var choose=borrow._allocation.summary("choose_noInline").requireSupported();
+ assertEquals(2,choose._returns.size());
+ var destinations=new ArrayList<String>();
+ for( var site : choose._returns ) {
+ assertNull(site._allocation);
+ destinations.add(site.destination());
+ }
+ Collections.sort(destinations);
+ assertEquals(List.of("result & arg3","result & arg4"),destinations);
+ assertEquals("1",Eval2.eval(borrow,0));
+ assertTrue(borrow.toString().contains("choose_noInline"));
+
+ CodeGen cycle=compile("""
+ struct Link { Link? !next; i64 x; new Link={ i64 n -> x=n; }; };
+ val cycle_noInline={ i64 n ->
+ val a=new Link(n), b=new Link(n+1);
+ a.next=b;
+ b.next=a;
+ return a;
+ };
+ return cycle_noInline(arg).x;
+ """);
+ var sites=allocations(cycle._allocation.summary("cycle_noInline"),"Link");
+ assertEquals(2,sites.size());
+ for( var site : sites ) assertEquals("result",site.destination());
+ assertEquals("9",Eval2.eval(cycle,9));
+ assertTrue(cycle.toString().contains("cycle_noInline"));
+ // Compiling cycle reset and recycled borrow's types. Its debugger string
+ // must neither crash on cleared types nor print their reused contents.
+ assertEquals("IR unavailable: shared types were reset after this compilation.",borrow.toString());
+ }
+
+ // Scalar results must not hide allocations when arithmetic is skipped.
+ @Test public void testAllocationScalarArrayUse() {
+ CodeGen code=compile("""
+ val work_noInline={ i64 n ->
+ val a=new i64[2];
+ a[0]=n;
+ return a[n&1]+n*n;
+ };
+ return work_noInline(arg);
+ """);
+ var sum=code._allocation.summary("work_noInline").requireSupported();
+ int arrays=0;
+ for( var site : sum._sites )
+ if( site._allocation!=null && site._allocation._ts.isAry() ) {
+ arrays++;
+ assertEquals("frame",site.destination());
+ }
+ assertEquals(1,arrays);
+ assertEquals("25",Eval2.eval(code,5));
+ assertEquals("20",Eval2.eval(code,4));
+ }
+
+ // Make unsupported plans explicit, without replacing existing TypeCheck
+ // diagnostics or changing the allocator used by older chapter tests.
+ @Test public void testAllocationRejectedPlans() {
+ String[] sources={
+ "val bad_noInline={ i64 n -> n ? bad_noInline(n-1) : 0; }; return bad_noInline(arg);",
+ "val bad_noInline={ i64 n -> new int[n]; }; return bad_noInline(arg);",
+ "{ i64 -> int[] } native=\"C\"; val bad_noInline={ i64 n -> native(n); }; return bad_noInline(arg);"
+ };
+ String[] reasons={"recursive", "variable-size", "native result"};
+ for( int i=0; i<sources.length; i++ ) {
+ CodeGen code=compile(sources[i]);
+ var sum=code._allocation.summary("bad_noInline");
+ assertFalse(sum.supported());
+ assertTrue(sum._reject,sum._reject.contains(reasons[i]));
+ try { sum.requireSupported(); fail("Rejected plan was usable"); }
+ catch( IllegalStateException expected ) {
+ assertTrue(expected.getMessage().contains(reasons[i]));
+ }
+ assertTrue(code._allocation.toString().contains("REJECT:"));
+ }
+ }
+
+ // A borrowed child is a separate origin. Returning it through helpers must
+ // retain the Thing, not the temporary Holder used to reach it.
+ @Test public void testAllocationReturnField() {
+ CodeGen code=compile(THING+HOLDER+"""
+ val get_noInline = { Holder h -> h.c; };
+ val forward_noInline = { Holder h -> get_noInline(h); };
+ val work_noInline={ i64 n ->
+ val h = new Holder;
+ h.c = new Thing(n);
+ return forward_noInline(h);
+ };
+ return read_noInline(work_noInline(arg));
+ """);
+ for( String name : new String[]{"get_noInline","forward_noInline"} ) {
+ var sum=code._allocation.summary(name).requireSupported();
+ assertEquals(1,sum._returns.size());
+ var child=sum._returns.iterator().next();
+ assertEquals("arg3.c",child._name);
+ assertEquals("result & arg3.c",child.destination());
+ for( var site : sum._sites )
+ if( site._arg==3 ) assertEquals("arg3",site.destination());
+ }
+ var work=code._allocation.summary("work_noInline");
+ assertEquals("frame",allocations(work,"Holder").get(0).destination());
+ assertEquals(2,allocations(work,"Thing").size()); // weak update retains the default too
+ for( var site : allocations(work,"Thing") ) assertEquals("result",site.destination());
+ assertEquals("17",Eval2.eval(code,17));
+ }
+
+ // Retention through a loaded reference composes across a wrapper. The
+ // source holder stays local even though its child escapes to the argument.
+ @Test public void testAllocationCopyField() {
+ CodeGen code=compile(THING+HOLDER+"""
+ val copy_noInline={ !Holder dst, Holder src -> dst.c=src.c; return 0; };
+ val forward_noInline={ !Holder dst, Holder src -> copy_noInline(dst,src); };
+ val work_noInline={ !Holder dst, i64 n ->
+ val src=new Holder;
+ src.c=new Thing(n);
+ return forward_noInline(dst,src);
+ };
+ val dst=new Holder;
+ work_noInline(dst,arg);
+ return dst.c.x;
+ """);
+ for( String name : new String[]{"copy_noInline","forward_noInline"} ) {
+ var sum=code._allocation.summary(name).requireSupported();
+ boolean found=false;
+ for( var site : sum._sites ) {
+ if( site._name.equals("arg4.c") ) {
+ found=true;
+ assertEquals("arg3 & arg4.c",site.destination());
+ }
+ if( site._arg==4 ) assertEquals("arg4",site.destination());
+ }
+ assertTrue(found);
+ }
+ var work=code._allocation.summary("work_noInline");
+ assertEquals("frame",allocations(work,"Holder").get(0).destination());
+ assertEquals(2,allocations(work,"Thing").size());
+ for( var site : allocations(work,"Thing") ) assertEquals("arg3",site.destination());
+ assertEquals("23",Eval2.eval(code,23));
+ }
+
+ // An argument's child can itself receive allocations. Its lifetime is a
+ // distinct destination, resolved to the actual Holder at the next call.
+ @Test public void testAllocationStoreThroughField() {
+ CodeGen code=compile(THING+HOLDER+"""
+ struct Outer { !Holder h=new Holder; };
+ val fill_noInline={ !Outer o, i64 n -> o.h.c=new Thing(n); return n; };
+ val get_noInline={ Outer o -> o.h.c; };
+ val work_noInline={ i64 n ->
+ val o=new Outer;
+ fill_noInline(o,n);
+ return get_noInline(o);
+ };
+ return read_noInline(work_noInline(arg));
+ """);
+ var fill=allocations(code._allocation.summary("fill_noInline"),"Thing");
+ assertEquals(1,fill.size());
+ assertEquals("arg3.h",fill.get(0).destination());
+ var get=code._allocation.summary("get_noInline").requireSupported();
+ assertEquals("arg3.h.c",get._returns.iterator().next()._name);
+ var work=code._allocation.summary("work_noInline");
+ assertEquals("frame",allocations(work,"Outer").get(0).destination());
+ assertEquals("frame",allocations(work,"Holder").get(0).destination());
+ assertEquals(2,allocations(work,"Thing").size());
+ for( var site : allocations(work,"Thing") ) assertEquals("result",site.destination());
+ assertEquals("31",Eval2.eval(code,31));
+ }
+
+ // A store through one formal must reach a load through another when actuals
+ // alias. Keeping all fields as weak unions also covers a load before a store.
+ @Test public void testAllocationAliasedFieldLoad() {
+ CodeGen code=compile(THING+HOLDER+"""
+ val fill_noInline={ !Holder a, Holder b, i64 n -> a.c=new Thing(n); return b.c; };
+ val same_noInline={ i64 n ->
+ val h=new Holder;
+ return fill_noInline(h,h,n);
+ };
+ val different_noInline={ i64 n ->
+ val a=new Holder, b=new Holder;
+ return fill_noInline(a,b,n);
+ };
+ return read_noInline(same_noInline(arg))+read_noInline(different_noInline(arg));
+ """);
+ for( String name : new String[]{"same_noInline","different_noInline"} ) {
+ var sum=code._allocation.summary(name);
+ for( var site : allocations(sum,"Holder") ) assertEquals("frame",site.destination());
+ int returned=0;
+ for( var site : allocations(sum,"Thing") )
+ if( site.destination().equals("result") ) returned++;
+ assertEquals(name.equals("same_noInline") ? 2 : 1,returned);
+ }
+ assertEquals("41",Eval2.eval(code,41));
+ }
+
+ // Weak updates can create fictitious repeated reads. Reject this case
+ // instead of building infinite p.next.next... paths or silently dropping one.
+ @Test public void testAllocationCyclicFieldPaths() {
+ CodeGen code=compile("""
+ struct Link { Link? !next; i64 x; new Link={ i64 n -> x=n; }; };
+ val skip_noInline={ !Link p ->
+ val a=p.next;
+ if( a ) p.next=a.next;
+ return p;
+ };
+ val a=new Link(arg), b=new Link(arg+1);
+ a.next=b;
+ return skip_noInline(a).x;
+ """);
+ var sum=code._allocation.summary("skip_noInline");
+ assertFalse(sum.supported());
+ assertTrue(sum._reject,sum._reject.contains("cyclic field-path expansion"));
+ assertEquals("5",Eval2.eval(code,5));
+ }
+
+ // Array indices share one conservative field. Both possible children need
+ // result storage; the fixed-size backing array itself remains temporary.
+ @Test public void testAllocationArrayElementOrigins() {
+ CodeGen code=compile(THING+"""
+ val get_noInline={ Thing?[] ts, i64 n -> ts[n&1]; };
+ val work_noInline={ i64 n ->
+ val ts=new Thing?[2];
+ ts[0]=new Thing(n);
+ ts[1]=new Thing(n+1);
+ return get_noInline(ts,n);
+ };
+ val t=work_noInline(arg);
+ return t ? t.x : -1;
+ """);
+ var work=code._allocation.summary("work_noInline").requireSupported();
+ assertEquals(2,allocations(work,"Thing").size());
+ for( var site : allocations(work,"Thing") ) assertEquals("result",site.destination());
+ int arrays=0;
+ for( var site : work._sites )
+ if( site._allocation!=null && site._allocation._ts.isAry() ) {
+ arrays++;
+ assertEquals("frame",site.destination());
+ }
+ assertEquals(1,arrays);
+ assertEquals("8",Eval2.eval(code,7));
+ assertEquals("6",Eval2.eval(code,6));
+ }
+
+ // One temporary per iteration, including allocations imported from a helper.
+ @Test public void testAllocationLoopTemporary() {
+ CodeGen code=compile(THING+"""
+ val make_noInline={ i64 n -> new Thing(n); };
+ val work_noInline={ i64 n ->
+ i64 s=0;
+ while( n>0 ) {
+ val t=make_noInline(n);
+ s+=read_noInline(t);
+ n--;
+ }
+ return s;
+ };
+ return work_noInline(arg);
+ """);
+ var sites=allocations(code._allocation.summary("work_noInline"),"Thing");
+ assertEquals(1,sites.size());
+ var temp=sites.get(0);
+ assertNotNull(temp._frame._loop);
+ assertSame(temp._frame,temp._scope);
+ assertEquals(temp._frame.name()+" iteration",temp.destination());
+ assertTrue(temp._frame._scratch.contains(temp));
+ assertFalse(temp._frame._continues.contains(temp));
+ assertFalse(temp._frame._returns.contains(temp));
+ assertEquals("15",Eval2.eval(code,5));
+ assertEquals("0",Eval2.eval(code,0));
+ }
+
+ // A loop can retain a winner while reclaiming unrelated scratch every turn.
+ // The winner is built by a factory, so its destination crosses a call too.
+ @Test public void testAllocationLoopWinnerAndScratch() {
+ CodeGen code=compile(THING+"""
+ struct Scratch { i64 x; new Scratch={ i64 n -> x=n; }; };
+ val readScratch_noInline={ Scratch s -> s.x; };
+ val make_noInline={ i64 n -> new Thing(n); };
+ val find_noInline={ i64 n ->
+ Thing? !winner=null;
+ while( n>0 ) {
+ val scratch=new Scratch(n);
+ val candidate=make_noInline(readScratch_noInline(scratch));
+ if( read_noInline(candidate)==3 ) { winner=candidate; break; }
+ n--;
+ }
+ return winner;
+ };
+ Thing? t=find_noInline(arg);
+ return t ? t.x : -1;
+ """);
+ var sum=code._allocation.summary("find_noInline").requireSupported();
+ var winner=allocations(sum,"Thing").get(0);
+ var scratch=allocations(sum,"Scratch").get(0);
+ assertNotNull(winner._frame._loop);
+ assertSame(winner._frame,scratch._frame);
+ assertEquals("result",winner.destination());
+ assertNull(winner._scope);
+ assertSame(scratch._frame,scratch._scope);
+ assertEquals(scratch._frame.name()+" iteration",scratch.destination());
+ var frame=winner._frame.requireSupported();
+ assertSame(sum,frame._parent);
+ assertTrue(sum._frames.contains(frame));
+ assertTrue(frame._returns.contains(winner));
+ assertFalse(frame._continues.contains(winner));
+ assertFalse(frame._scratch.contains(winner));
+ assertTrue(frame._scratch.contains(scratch));
+ assertFalse(frame._entry.isEmpty());
+ assertFalse(frame._next.isEmpty());
+ assertFalse(frame._exit.isEmpty());
+ String dump=code._allocation.toString();
+ assertTrue(dump.contains(frame.name()+" winner"));
+ assertEquals(dump.indexOf("\n+-- "),dump.indexOf("\n+-- class:Test.<clinit>\n"));
+ int others=dump.indexOf("Other retained functions");
+ assertTrue(dump.indexOf("\n+-- find_noInline\n") < others);
+ assertTrue(dump.indexOf("\n+-- make_noInline\n") < others);
+ assertTrue(dump.indexOf("\n+-- Test.Scratch.<new>\n") > others);
+ assertEquals("3",Eval2.eval(code,5));
+ assertEquals("-1",Eval2.eval(code,2));
+ assertEquals("-1",Eval2.eval(code,0));
+ }
+
+ // A collection needs multiple generations of an allocation site. Neither a
+ // loop-carried pointer nor a pointer hidden in pre-existing memory is a winner.
+ @Test public void testAllocationLoopRetainedCandidates() {
+ String[] sources={
+ """
+ struct Link { Link? next; i64 x; new Link={ Link? p, i64 n -> next=p; x=n; }; };
+ val work_noInline={ i64 n ->
+ Link? !head=null;
+ while( n>0 ) { head=new Link(head,n); n--; }
+ return head;
+ };
+ val t=work_noInline(arg);
+ return t ? t.x : -1;
+ """,
+ THING+"""
+ val work_noInline={ i64 n ->
+ val ts=new Thing?[2];
+ while( n>0 ) { ts[n&1]=new Thing(n); n--; }
+ return ts;
+ };
+ val ts=work_noInline(arg);
+ val t=ts[1];
+ return t ? t.x : -1;
+ """,
+ THING+HOLDER+"""
+ val fill_noInline={ !Holder h, i64 n -> h.c=new Thing(n); return n; };
+ val work_noInline={ i64 n ->
+ val h=new Holder;
+ while( n>0 ) { fill_noInline(h,n); n--; }
+ return h;
+ };
+ return work_noInline(arg).c.x;
+ """
+ };
+ for( String source : sources ) {
+ CodeGen code=compile(source);
+ var sum=code._allocation.summary("work_noInline");
+ assertFalse(sum.supported());
+ assertTrue(sum._reject,sum._reject.contains("across its backedge"));
+ assertEquals("1",Eval2.eval(code,3));
+ }
+ }
+
+ // Publishing on the exit arm is allowed. Publishing on the backedge was
+ // rejected above; both cases write through a pre-existing holder.
+ @Test public void testAllocationLoopWinnerStore() {
+ CodeGen code=compile(THING+HOLDER+"""
+ val fill_noInline={ !Holder h, i64 n ->
+ while( n>0 ) {
+ val t=new Thing(n);
+ if( read_noInline(t)==3 ) { h.c=t; break; }
+ n--;
+ }
+ return n;
+ };
+ val h=new Holder;
+ fill_noInline(h,arg);
+ return h.c.x;
+ """);
+ var sites=allocations(code._allocation.summary("fill_noInline"),"Thing");
+ assertEquals(1,sites.size());
+ assertEquals("arg3",sites.get(0).destination());
+ assertNotNull(sites.get(0)._frame._loop);
+ assertNull(sites.get(0)._scope);
+ assertTrue(sites.get(0)._frame._retained.contains(sites.get(0)));
+ assertEquals("3",Eval2.eval(code,5));
+ assertEquals("0",Eval2.eval(code,2));
+ }
+
+ // An inner winner can still be temporary in the enclosing iteration.
+ @Test public void testAllocationNestedLoopWinner() {
+ CodeGen code=compile(THING+"""
+ val work_noInline={ i64 n ->
+ i64 s=0;
+ while( n>0 ) {
+ Thing? !winner=null;
+ i64 i=3;
+ while( i>0 ) {
+ val t=new Thing(n+i);
+ if( read_noInline(t)==n+2 ) { winner=t; break; }
+ i--;
+ }
+ if( winner ) s+=read_noInline(winner);
+ n--;
+ }
+ return s;
+ };
+ return work_noInline(arg);
+ """);
+ var sites=allocations(code._allocation.summary("work_noInline"),"Thing");
+ assertEquals(1,sites.size());
+ var site=sites.get(0);
+ assertNotNull(site._frame._loop);
+ assertNotNull(site._scope);
+ assertSame(site._frame._parent,site._scope);
+ assertEquals(site._scope.name()+" iteration",site.destination());
+ assertTrue(site._frame._returns.contains(site));
+ assertFalse(site._frame._scratch.contains(site));
+ assertTrue(site._scope._scratch.contains(site));
+ assertEquals("12",Eval2.eval(code,3));
+ }
+
+ // The candidate's graph survives together, but the caller can consume that
+ // result locally. The helper's winner layout must not leak into its caller.
+ @Test public void testAllocationLoopWinnerGraph() {
+ CodeGen code=compile(THING+"""
+ struct Box { Thing child; new Box={ Thing t -> child=t; }; };
+ val use_noInline={ Box b -> b.child.x; };
+ val find_noInline={ i64 n ->
+ while( true ) {
+ val b=new Box(new Thing(n));
+ if( use_noInline(b)==3 ) return b;
+ n--;
+ }
+ };
+ val work_noInline={ i64 n -> use_noInline(find_noInline(n)); };
+ return work_noInline(arg);
+ """);
+ var find=code._allocation.summary("find_noInline").requireSupported();
+ for( String type : new String[]{"Thing","Box"} ) {
+ var winner=allocations(find,type).get(0);
+ assertEquals("result",winner.destination());
+ assertNotNull(winner._frame._loop);
+ assertNull(winner._scope);
+ var caller=allocations(code._allocation.summary("work_noInline"),type).get(0);
+ assertEquals("frame",caller.destination());
+ assertSame(code._allocation.summary("work_noInline"),caller._frame);
+ assertSame(caller._frame,caller._scope);
+ assertTrue(caller._frame._scratch.contains(caller));
+ }
+ assertEquals("3",Eval2.eval(code,5));
+ }
+
+ // Continuation ports can return borrowed references into the next activation.
+ // They do not require retaining any storage created by the iteration.
+ @Test public void testAllocationBorrowedContinuation() {
+ CodeGen code=compile(THING+"""
+ val work_noInline={ Thing a, Thing b, i64 n ->
+ Thing !p=a;
+ i64 s=0;
+ while( n>0 ) {
+ s+=read_noInline(p);
+ p=(n&1) ? a : b;
+ n--;
+ }
+ return s+read_noInline(p);
+ };
+ return work_noInline(new Thing(10),new Thing(20),arg);
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ assertEquals(1,fun._frames.size());
+ var loop=fun._frames.get(0).requireSupported();
+ assertEquals(2,loop._continues.size());
+ for( var site : loop._continues ) {
+ assertNull(site._allocation);
+ assertTrue(site._arg==3 || site._arg==4);
+ assertTrue(loop._returns.contains(site));
+ }
+ assertTrue(loop._scratch.isEmpty());
+ assertEquals("50",Eval2.eval(code,3));
+ assertEquals("10",Eval2.eval(code,0));
+ }
+
+ // Both exits clean the same scratch. The normal result here is a scalar,
+ // loaded before cleanup; returning it does not retain the temporary object.
+ @Test public void testAllocationScalarLoopExit() {
+ CodeGen code=compile(THING+"""
+ val work_noInline={ i64 n ->
+ i64 result=-1;
+ while( n>0 ) {
+ val t=new Thing(n);
+ val x=read_noInline(t);
+ if( n==3 ) { result=x; break; }
+ n--;
+ }
+ return result;
+ };
+ return work_noInline(arg);
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ var temp=allocations(fun,"Thing").get(0);
+ var loop=temp._frame.requireSupported();
+ assertSame(loop,temp._scope);
+ assertTrue(loop._scratch.contains(temp));
+ assertTrue(loop._returns.isEmpty());
+ assertTrue(loop._continues.isEmpty());
+ boolean scalar=false;
+ for( var value : loop._exit.values() )
+ if( value._type instanceof com.seaofnodes.simple.type.TypeInteger ) scalar=true;
+ assertTrue(scalar);
+ assertEquals("3",Eval2.eval(code,5));
+ assertEquals("-1",Eval2.eval(code,2));
+ }
+
+ // Returning from an inner loop exports through both enclosing interfaces;
+ // each exited frame has its own cleanup obligations.
+ @Test public void testAllocationNestedFrameReturn() {
+ CodeGen code=compile(THING+"""
+ struct Scratch { i64 x; new Scratch={ i64 n -> x=n; }; };
+ val readScratch_noInline={ Scratch s -> s.x; };
+ val find_noInline={ i64 n ->
+ while( n>0 ) {
+ val scratch=new Scratch(n);
+ i64 i=readScratch_noInline(scratch);
+ while( i>0 ) {
+ val candidate=new Thing(i);
+ if( read_noInline(candidate)==3 ) return candidate;
+ i--;
+ }
+ n--;
+ }
+ return null;
+ };
+ Thing? t=find_noInline(arg);
+ return t ? t.x : -1;
+ """);
+ var fun=code._allocation.summary("find_noInline").requireSupported();
+ var winner=allocations(fun,"Thing").get(0);
+ var scratch=allocations(fun,"Scratch").get(0);
+ var inner=winner._frame;
+ var outer=scratch._frame;
+ assertSame(outer,inner._parent);
+ assertSame(fun,outer._parent);
+ assertTrue(inner._returns.contains(winner));
+ assertTrue(outer._returns.contains(winner));
+ assertTrue(fun._returns.contains(winner));
+ assertNull(winner._scope);
+ assertSame(outer,scratch._scope);
+ assertTrue(outer._scratch.contains(scratch));
+ assertFalse(inner._scratch.contains(scratch));
+ assertEquals("3",Eval2.eval(code,5));
+ assertEquals("-1",Eval2.eval(code,2));
+ }
+
+ @Test public void testAllocationExitlessLoop() {
+ CodeGen code=compile(THING+"""
+ val spin_noInline={ i64 n ->
+ while( true ) {
+ val t=new Thing(n);
+ n=read_noInline(t)+1;
+ }
+ return 7;
+ };
+ spin_noInline(arg);
+ return 7;
+ """);
+ var fun=code._allocation.summary("spin_noInline").requireSupported();
+ assertEquals(1,fun._frames.size());
+ var loop=fun._frames.get(0).requireSupported();
+ assertNotNull(loop._loop);
+ assertSame(loop._loop,loop._loop._ltree._head);
+ assertSame(fun,loop._parent);
+ var temp=allocations(fun,"Thing").get(0);
+ assertSame(loop,temp._scope);
+ assertTrue(loop._scratch.contains(temp));
+ assertTrue(loop._returns.isEmpty());
+ assertTrue(loop._continues.isEmpty());
+ // No synthetic return before TypeCheck or serialization; scheduling
+ // supplies the exit later. The evaluator still cannot return.
+ assertSame(com.seaofnodes.simple.type.Type.XCONTROL,fun._fun.ret().ctrl()._type);
+ assertNull(Eval2.eval(code,0,10));
+ }
+
+ @Test public void testAllocationNativeBorrow() {
+ CodeGen code=compile("""
+ { i64 i64 -> i64 } native="C";
+ val work_noInline={i64 n ->
+ val a=new u8[16], b=new u8[16];
+ i64 pa=a, pb=b;
+ i64 p=n ? pa : pb;
+ return native(p+2,8);
+ };
+ return work_noInline(arg);
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ int count=0;
+ for( var site : fun._sites ) if( site._allocation!=null ) {
+ count++;
+ assertSame(fun,site._scope);
+ assertTrue(fun._scratch.contains(site));
+ assertFalse(fun._returns.contains(site));
+ }
+ assertEquals(2,count);
+ assertTrue(code._allocation.toString().contains("native (borrow; no retain)"));
+ }
+
+ @Test public void testAllocationNativeLoopBorrow() {
+ CodeGen code=compile("""
+ { i64 i64 -> i64 } native="C";
+ val borrow_noInline={u8[] bytes ->
+ i64 p=bytes;
+ return native(p,bytes#);
+ };
+ val work_noInline={i64 n ->
+ i64 total=0;
+ while(n>0) {
+ val bytes=new u8[16];
+ total+=borrow_noInline(bytes);
+ i64 p=bytes;
+ total+=native(p+1,8);
+ n--;
+ }
+ return total;
+ };
+ return work_noInline(arg);
+ """);
+ code._allocation.summary("borrow_noInline").requireSupported();
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ int count=0;
+ for( var site : fun._sites ) if( site._allocation!=null ) {
+ count++;
+ assertNotNull(site._frame._loop);
+ assertSame(site._frame,site._scope);
+ assertTrue(site._scope._scratch.contains(site));
+ assertFalse(site._scope._continues.contains(site));
+ }
+ assertEquals(1,count);
+ }
+
+ @Test public void testAllocationRawAddressBoundaries() {
+ String[] bodies={
+ """
+ i64 p=0;
+ while(n>0) {
+ if(p) native(p);
+ val bytes=new u8[16];
+ p=bytes;
+ n--;
+ }
+ return 0;
+ """,
+ "val bytes=new u8[16]; i64 p=bytes; addresses[0]=p; return native(addresses[0]);"
+ };
+ for( int i=0; i<bodies.length; i++ ) {
+ CodeGen code=compile("{ i64 -> i64 } native=\"C\"; val addresses=new i64[1]; "+
+ "val work_noInline={i64 n -> "+bodies[i]+"}; return work_noInline(arg);");
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ for( var site : fun._sites ) if( site._allocation!=null ) {
+ // Carrying the integer across iterations does not carry its
+ // backing storage. The first program uses a stale raw address.
+ assertSame(site._frame,site._scope);
+ assertTrue(site._scope._scratch.contains(site));
+ }
+ }
+ }
+
+ private static List<KeepAliveNode> keeps(CodeGen code) {
+ var keeps=new ArrayList<KeepAliveNode>();
+ code._start.walk(n -> { if( n instanceof KeepAliveNode k ) keeps.add(k); return null; });
+ return keeps;
+ }
+
+ @Test public void testKeepAliveWrappersAndReplacement() {
+ CodeGen code=compile("""
+ { i64 -> i64 } native="C";
+ val forward_noInline={ i64 p -> native(p); };
+ val wrapper_noInline={ i64 p -> forward_noInline(p); };
+ val addresses=new i64[2];
+ val work_noInline={ i64 n ->
+ i64 raw=new u8[16];
+ addresses[0]=raw;
+ raw=new u8[32];
+ addresses[1]=raw;
+ return wrapper_noInline(addresses[n&1]);
+ };
+ return work_noInline(arg);
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ int count=0;
+ for( var site : fun._sites ) if( site._allocation!=null ) {
+ count++;
+ assertSame(fun,site._scope);
+ assertTrue(fun._scratch.contains(site));
+ }
+ assertEquals(2,count);
+ assertEquals(1,keeps(code).size());
+ KeepAliveNode keep=keeps(code).get(0);
+ assertTrue(keep.in(1) instanceof KeepAliveNode.Values);
+ assertSame(keep,fun._fun.ret().ctrl());
+ assertTrue(keep.in(0) instanceof CProjNode);
+ }
+
+ @Test public void testKeepAliveConditionalAndErasure() {
+ CodeGen code=compile("""
+ { i64 -> i64 } native="C";
+ val work_noInline={ i64 n ->
+ i64 raw=0;
+ n && ((raw=new u8[16])!=null);
+ return native(raw);
+ };
+ return work_noInline(arg);
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ assertEquals(1,keeps(code).size());
+ KeepAliveNode keep=keeps(code).get(0);
+ assertTrue(keep.in(1) instanceof PhiNode);
+ assertSame(keep,fun._fun.ret().ctrl());
+ CallNode call=((CallEndNode)keep.in(0).in(0)).call();
+ Node raw=call.arg(3);
+ KeepAliveNode.erase(code._start);
+ assertTrue(keeps(code).isEmpty());
+ assertSame(raw,call.arg(3)); // Shared ordinary Phi must survive erasure.
+ assertFalse(raw.isDead());
+ }
+
+ @Test public void testKeepAliveLoopExits() {
+ CodeGen code=compile("""
+ { i64 -> i64 } native="C";
+ val work_noInline={ i64 n ->
+ i64 total=0;
+ while(n>0) {
+ i64 raw=new u8[16];
+ total+=native(raw);
+ if(n==1) return total;
+ if(n==2) break;
+ n--;
+ if(n==3) continue;
+ total++;
+ }
+ return total;
+ };
+ return work_noInline(arg);
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ assertFalse(keeps(code).isEmpty());
+ for( var site : fun._sites ) if( site._allocation!=null ) {
+ assertNotNull(site._frame._loop);
+ assertFalse(site._frame._continues.contains(site));
+ assertNotNull(site._scope);
+ }
+ }
+
+ @Test public void testKeepAliveOuterLoopScope() {
+ CodeGen code=compile("""
+ { i64 -> i64 } native="C";
+ val work_noInline={ i64 n ->
+ i64 raw=0;
+ while((raw=new u8[16]) && native(raw) && n-->0) { }
+ return n;
+ };
+ return work_noInline(arg);
+ """);
+ var fun=code._allocation.summary("work_noInline");
+ // Predicate conversions belong to the enclosing scope; every iteration
+ // adds storage to that scope, unlike a conversion in the loop body.
+ assertFalse(fun.supported());
+ assertTrue(fun._reject,fun._reject.contains("across its backedge"));
+ }
+
+ @Test public void testKeepAliveRawReturnAndUnused() {
+ CodeGen code=compile("""
+ val work_noInline={ ->
+ i64 raw=new u8[16];
+ return raw+17;
+ };
+ return work_noInline();
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ assertTrue(fun._returns.isEmpty()); // Returned integer has no lifetime contract.
+ assertFalse(fun._scratch.isEmpty());
+ assertEquals(1,keeps(code).size());
+ code=compile("val work_noInline={ -> val a=new u8[16]; i64 unused=a; return 1; }; return work_noInline();");
+ assertTrue(keeps(code).isEmpty());
+ assertEquals("1",Eval2.eval(code,0));
+ }
+
+ @Test public void testKeepAliveImportedBody() throws Exception {
+ Path build=Path.of("build/objs/separate");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"keepalive-");
+ new CodeGen(null,lib.toString(),null,"Borrow","""
+ { i64 -> i64 } native="C";
+ val borrow={ u8[] a -> i64 raw=a; return native(raw); };
+ """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ CodeGen code=new CodeGen(null,lib.toString(),paths,"BorrowClient",
+ "return Borrow.borrow(new u8[16]);",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertFalse(keeps(code).isEmpty());
+ code.driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ assertTrue(keeps(code).isEmpty());
+ }
+
+ @Test public void testKeepAliveForwardConversion() {
+ CodeGen code=compile("""
+ { i64 -> i64 } native="C";
+ val work_noInline={ -> i64 raw=make_noInline(); return native(raw); };
+ val make_noInline={ -> new u8[16]; };
+ return work_noInline();
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ assertEquals(1,keeps(code).size());
+ assertFalse(fun._scratch.isEmpty());
+ assertTrue(fun._returns.isEmpty());
+ }
+
+ @Test public void testKeepAliveImplicitScopes() {
+ CodeGen code=compile("""
+ { i64 -> i64 } native="C";
+ val work_noInline={ i64 n ->
+ i64 raw=0;
+ if(n) raw=new u8[16]; else raw=new u8[32];
+ return native(raw);
+ };
+ return work_noInline(arg);
+ """);
+ code._allocation.summary("work_noInline").requireSupported();
+ // Each unbraced arm ends its own borrowing scope. The subsequent call
+ // deliberately uses stale integers; it must not move these endpoints.
+ assertEquals(2,keeps(code).size());
+ for( KeepAliveNode keep : keeps(code) ) {
+ assertTrue(keep.in(0) instanceof CProjNode);
+ assertTrue(keep.in(0).in(0) instanceof IfNode);
+ boolean merges=false;
+ for( Node use : keep._outputs ) if( use instanceof RegionNode ) merges=true;
+ assertTrue(merges);
+ }
+ }
+
+ @Test public void testKeepAliveNestedFunction() {
+ CodeGen code=compile("""
+ { i64 -> i64 } native="C";
+ val work_noInline={ i64 n ->
+ i64 raw=new u8[16];
+ val helper_noInline={i64 k -> while(k>0) k--; return k;};
+ helper_noInline(n);
+ return native(raw);
+ };
+ return work_noInline(arg);
+ """);
+ var fun=code._allocation.summary("work_noInline").requireSupported();
+ assertEquals(1,keeps(code).size());
+ assertSame(keeps(code).get(0),fun._fun.ret().ctrl());
+ assertFalse(fun._scratch.isEmpty());
+ }
+
+ // Until ^ and .del() have a checked source contract, a native call supplies
+ // the real control/memory boundary at which we ask the ownership question.
+ // These programs are analyzed only: retire is not linked or executed.
+ private static ArrayDelete deletion(CodeGen code) {
+ var calls=new ArrayList<CallNode>();
+ code._start.walk(n -> { if( n instanceof CallNode call ) calls.add(call); return null; });
+ CallNode checkpoint=null;
+ for( CallNode call : calls )
+ if( call.external() ) {
+ assertNull("Expected one deletion checkpoint",checkpoint);
+ checkpoint=call;
+ }
+ assertNotNull("Missing deletion checkpoint",checkpoint);
+ return code._allocation.checkArrayDelete(checkpoint,3);
+ }
+
+ @Test public void testArrayDeleteLocalAndBorrow() {
+ CodeGen code=compile("""
+ val work_noInline={i64 n ->
+ { u8[] -> i64 } retire="C";
+ val copy_noInline={u8[] dst, u8[] src, i64 len ->
+ for(i64 i=0; i<len; i++) dst[i]=src[i];
+ return len;
+ };
+ val old=new u8[n], next=new u8[n*2];
+ copy_noInline(next,old,n);
+ retire(old);
+ return next[0];
+ };
+ return work_noInline(arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertTrue(check.toString(),check.proven());
+ }
+
+ private static final String BUFFER = "struct Buffer { u8[] !buf=new u8[8]; };\n";
+
+ @Test public void testArrayDeleteFieldReplacement() {
+ CodeGen code=compile(BUFFER+"""
+ val resize_noInline={!Buffer b, i64 n ->
+ { u8[] -> i64 } retire="C";
+ val copy_noInline={u8[] dst, u8[] src, i64 len ->
+ for(i64 i=0; i<len; i++) dst[i]=src[i];
+ return len;
+ };
+ val old=b.buf;
+ val next=new u8[n];
+ copy_noInline(next,old,old#);
+ b.buf=next;
+ retire(old);
+ return b.buf[0];
+ };
+ return resize_noInline(new Buffer,arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertNull(check.toString(),check._reject);
+ // Local kills are proved, caller uniqueness is NOT silently assumed.
+ assertNotNull(check._unique);
+ assertFalse(check.proven());
+ assertTrue(check.toString().contains("requires unique entry"));
+ }
+
+ @Test public void testArrayDeleteSurvivingAlias() {
+ for( String alias : new String[]{"old", "n ? old : new u8[8]"} ) {
+ CodeGen code=compile("""
+ val work_noInline={i64 n ->
+ { u8[] -> i64 } retire="C";
+ val old=new u8[n];
+ val saved=
+ """+alias+";"+"""
+ retire(old);
+ return saved[0];
+ };
+ return work_noInline(arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertNotNull(check.toString(),check._reject);
+ assertTrue(check.toString(),check._reject.contains("survives deletion"));
+ }
+ }
+
+ @Test public void testArrayDeleteConditionalKill() {
+ for( boolean both : new boolean[]{false,true} ) {
+ CodeGen code=compile(BUFFER+"""
+ val resize_noInline={!Buffer b, i64 n ->
+ { u8[] -> i64 } retire="C";
+ val old=b.buf;
+ if(n) b.buf=new u8[16];
+ """+(both ? "else b.buf=new u8[32];" : "")+"""
+ retire(old);
+ return b.buf[0];
+ };
+ return resize_noInline(new Buffer,arg);
+ """);
+ ArrayDelete check=deletion(code);
+ if( both ) assertNull(check.toString(),check._reject);
+ else {
+ assertNotNull(check.toString(),check._reject);
+ assertTrue(check.toString(),check._reject.contains("still holds the array"));
+ }
+ }
+ }
+
+ @Test public void testArrayDeleteFreshOwnerAndStoredAlias() {
+ for( boolean saved : new boolean[]{false,true} ) {
+ CodeGen code=compile("""
+ struct Buffer { u8[] !buf=new u8[8]; u8[]? !saved=null; };
+ val work_noInline={i64 n ->
+ { u8[] -> i64 } retire="C";
+ val b=new Buffer;
+ val old=new u8[n];
+ b.buf=old;
+ """+(saved ? "b.saved=old;" : "")+"""
+ b.buf=new u8[n*2];
+ retire(old);
+ return b;
+ };
+ return work_noInline(arg);
+ """);
+ ArrayDelete check=deletion(code);
+ if( !saved ) assertTrue(check.toString(),check.proven());
+ else {
+ assertNotNull(check.toString(),check._reject);
+ assertTrue(check.toString(),check._reject.contains("still holds the array"));
+ }
+ }
+ }
+
+ @Test public void testArrayDeleteAliasedOwner() {
+ CodeGen code=compile(BUFFER+"""
+ val resize_noInline={!Buffer b, !Buffer other, i64 n ->
+ { u8[] -> i64 } retire="C";
+ val old=b.buf;
+ val saved=other.buf;
+ b.buf=new u8[n];
+ retire(old);
+ return saved[0];
+ };
+ val b=new Buffer;
+ return resize_noInline(b,b,arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertNotNull(check.toString(),check._reject);
+ assertTrue(check.toString(),check._reject.contains("survives deletion"));
+ }
+
+ @Test public void testArrayDeleteRetainingHelper() {
+ CodeGen code=compile("""
+ struct Buffer { u8[] !buf=new u8[8]; u8[]? !saved=null; };
+ val work_noInline={i64 n ->
+ { u8[] -> i64 } retire="C";
+ val retain_noInline={!Buffer b -> b.saved=b.buf; return 0; };
+ val b=new Buffer;
+ val old=new u8[n];
+ b.buf=old;
+ retain_noInline(b);
+ b.buf=new u8[n*2];
+ retire(old);
+ return b;
+ };
+ return work_noInline(arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertNotNull(check.toString(),check._reject);
+ assertTrue(check.toString(),check._reject.contains("field .saved still holds the array"));
+ }
+
+ @Test public void testArrayDeleteRawBorrowAndRepeatedDelete() {
+ CodeGen code=compile("""
+ val work_noInline={i64 n ->
+ { u8[] -> i64 } retire="C";
+ val old=new u8[n];
+ i64 address=old;
+ retire(old);
+ return address;
+ };
+ return work_noInline(arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertNotNull(check.toString(),check._reject);
+ assertTrue(check.toString(),check._reject.contains("raw-address borrow"));
+
+ code=compile("""
+ val work_noInline={i64 n ->
+ { u8[] -> i64 } retire="C";
+ val old=new u8[8];
+ while(n>0) { retire(old); n--; }
+ return n;
+ };
+ return work_noInline(arg);
+ """);
+ check=deletion(code);
+ assertNotNull(check.toString(),check._reject);
+ assertTrue(check.toString(),check._reject.contains("backedge"));
+ }
+
+ @Test public void testArrayDeleteRehash() {
+ CodeGen code=compile("""
+ struct Table { i64[] !keys=new i64[8]; };
+ val rehash_noInline={!Table table ->
+ { i64[] -> i64 } retire="C";
+ val old=table.keys;
+ val next=new i64[old#*2];
+ for(i64 i=0; i<old#; i++) {
+ val key=old[i];
+ if(key) {
+ i64 j=key & (next#-1);
+ while(next[j]) j=(j+1) & (next#-1);
+ next[j]=key;
+ }
+ }
+ table.keys=next;
+ retire(old);
+ return table.keys#;
+ };
+ return rehash_noInline(new Table);
+ """);
+ ArrayDelete check=deletion(code);
+ assertNull(check.toString(),check._reject);
+ assertNotNull(check._unique);
+ assertFalse(check.proven());
+ }
+
+ @Test public void testArrayDeleteCopiedElementReference() {
+ CodeGen code=compile("""
+ struct Item { i64 x=42; };
+ val work_noInline={i64 n ->
+ { Item?[] -> i64 } retire="C";
+ val item=new Item;
+ val old=new Item?[n];
+ old[0]=item;
+ val saved=old[0];
+ retire(old);
+ return saved ? saved.x : 0;
+ };
+ return work_noInline(arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertTrue(check.toString(),check.proven());
+ }
+
+ @Test public void testArrayDeleteConstructorRetention() {
+ CodeGen code=compile("""
+ struct Box {
+ u8[] buf;
+ new Box={u8[] buf -> self.buf=buf;};
+ };
+ val work_noInline={i64 n ->
+ { u8[] -> i64 } retire="C";
+ val old=new u8[n];
+ val box=new Box(old);
+ retire(old);
+ return box;
+ };
+ return work_noInline(arg);
+ """);
+ ArrayDelete check=deletion(code);
+ assertNotNull(check.toString(),check._reject);
+ assertFalse(check.proven());
+ }
+
+ @Test public void testArrayDeleteSourceSyntax() {
+ for( String allocation : new String[]{"new u8[^arg]", "new u8[^]{1,2,3}", "new u8[^8]{int i -> i;}"} ) {
+ CodeGen code=compile("{ u8[^] a="+allocation+"; a.del(); return 42; }");
+ code._allocation.requireSupported();
+ assertEquals(1,code._allocation._deletes.size());
+ assertTrue(code._allocation._deletes.get(0).toString(),code._allocation._deletes.get(0).proven());
+ }
+ CodeGen code=compile("""
+ val work_noInline={i64 n ->
+ val read_noInline={u8[~] a -> a[0];};
+ val a=new u8[^n];
+ val answer=read_noInline(a);
+ a.del();
+ return answer;
+ };
+ return work_noInline(arg);
+ """);
+ assertTrue(code._allocation._deletes.get(0).toString(),code._allocation._deletes.get(0).proven());
+ code._allocation.summary("work_noInline").requireSupported();
+ }
+
+ private static void deleteError(String source, String message) {
+ try { compile("{"+source+"}"); fail("Expected deletion rejection"); }
+ catch( com.seaofnodes.simple.parser.Parser.ParseException e ) {
+ assertTrue(e.getMessage(),e.getMessage().contains(message));
+ }
+ }
+
+ @Test public void testArrayDeleteSourceErrors() {
+ deleteError("val a=new u8[8]; a.del(); return 0;","requires a non-null [^]");
+ deleteError("u8[^] a=new u8[8]; return a#;","not of declared type");
+ deleteError("val a=new u8[^8]; a.del(); return a[0];","survives deletion");
+ deleteError("val a=new u8[^8]; a.del(); a.del(); return 0;","after deletion");
+ deleteError("val a=new u8[^8]; return a.del;","must be called directly");
+ deleteError("val a=new u8[^8]; a.del=0; return 0;","not a writable field");
+ compile("""
+ val consume_noInline={u8[^] a -> a.del(); return 0;};
+ return consume_noInline(new u8[^8]);
+ """);
+ }
+
+ @Test public void testArrayDeleteExecutionNotImplemented() {
+ CodeGen code=compile("{ val a=new u8[^8]; a.del(); return 0; }");
+ try { Eval2.eval(code,0); fail("Deletion must not silently become a no-op"); }
+ catch( UnsupportedOperationException e ) {
+ assertTrue(e.getMessage(),e.getMessage().contains("runtime recycling is not implemented"));
+ }
+ }
+
+ @Test public void testArrayDeleteSerializedBody() throws Exception {
+ Path build=Path.of("build/objs/separate");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"array-delete-");
+ new CodeGen(null,lib.toString(),null,"DeleteLib","""
+ val work={i64 n -> val a=new u8[^n]; a.del(); return n;};
+ """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ CodeGen code=new CodeGen(null,lib.toString(),paths,"DeleteClient",
+ "return DeleteLib.work(arg);",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertFalse(code._allocation._deletes.isEmpty());
+ for( ArrayDelete deletion : code._allocation._deletes ) assertTrue(deletion.toString(),deletion.proven());
+ }
+
+ @Test public void testArrayDeleteSourceField() {
+ CodeGen code=compile("""
+ struct Buffer { u8[^] !buf=new u8[^8]; };
+ val work_noInline={i64 n ->
+ val b=new Buffer;
+ val old=b.buf;
+ b.buf=new u8[^n];
+ old.del();
+ return b;
+ };
+ return work_noInline(arg);
+ """);
+ assertEquals(1,code._allocation._deletes.size());
+ assertTrue(code._allocation._deletes.get(0).toString(),code._allocation._deletes.get(0).proven());
+ }
+
+ @Test public void testArrayDeleteForwardMember() {
+ CodeGen code=compile("""
+ val work_noInline={ -> val b=make(); val old=b.buf; b.buf=new u8[^16]; old.del(); return b; };
+ struct Buffer { u8[^] !buf=new u8[^8]; };
+ val make={ -> new Buffer; };
+ return work_noInline();
+ """);
+ assertFalse(code._allocation._deletes.isEmpty());
+ for( ArrayDelete deletion : code._allocation._deletes ) assertTrue(deletion.toString(),deletion.proven());
+ // A forward receiver with a user-defined del is an ordinary method.
+ code=compile("""
+ val work_noInline={ -> make().del(); };
+ struct Thing { val del={ -> 17; }; };
+ val make={ -> new Thing; };
+ return work_noInline();
+ """);
+ assertTrue(code._allocation._deletes.isEmpty());
+ assertEquals("17",Eval2.eval(code,0));
+ }
+
+ // Read the same remote bound as ary.capacity, without that helper or
+ // ary.copy obscuring the initializer's effect on the deletion proof.
+ @Test public void testArrayDeleteAryu8IntegerInit() {
+ var paths=new Ary<>(new String[]{TestC.RELEASE_SYS_DIR});
+ CodeGen code=new CodeGen(null,null,paths,"Test","""
+ { i32 -> i64 } _exit="C";
+ struct aryu8 {
+ u32 !len = 0;
+ u8[^] !buf = new u8[^1];
+ val _grow_noInline = { u32 len2 ->
+ if( len+len2 <= buf# ) return self;
+ i64 newlen = buf#*2;
+ // Triggers <clinit> for sys.integer
+ if( newlen > sys.integer.MAX_U32 ) _exit(1);
+ val old = buf;
+ val next = new u8[^newlen];
+ for(u32 i=0; i<len; i++) next[i] = old[i];
+ buf = next;
+ old.del();
+ return self;
+ };
+ };
+ u32 extra=arg;
+ return new aryu8()._grow_noInline(extra);
+ """,126,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ assertEquals(2,code._allocation._deletes.size());
+ ArrayDelete deletion=code._allocation._deletes.get(0);
+ assertTrue(code._allocation._deletes.get(1).toString(),code._allocation._deletes.get(1).proven());
+ FunNode integerInit=code.link(code._compunits.get("sys/integer"));
+ SummaryNode summary=integerInit.summary();
+ // Break here to inspect the imported summary and the deletion memory.
+ assertNotNull("Exercise a loaded summary, not a parsed initializer body",summary);
+ assertFalse(summary._effects._referenceWrites);
+ assertNotSame(TypeMem.BOT,summary._state.mem());
+ assertNull(deletion.toString(),deletion._reject);
+ assertNotNull(deletion.toString(),deletion._unique);
+ for( FunNode fun : code._linker )
+ assertTrue("Unreferenced DateTime must not survive Opto",
+ fun==null || fun.isDead() || fun._name==null || !fun._name.contains("sys.time.DateTime"));
+ var grow=code._allocation.summary("_grow_noInline").requireSupported();
+ boolean dynamic=false;
+ for( Allocation.Site site : grow._sites )
+ if( site._allocation!=null && site._bytes<0 ) {
+ assertEquals("buddy",site.destination());
+ assertFalse(grow._scratch.contains(site));
+ dynamic=true;
+ }
+ assertTrue(dynamic);
+ var inits=new ArrayList<CLInitNode>();
+ code._start.walk(n -> { if( n instanceof CLInitNode init ) inits.add(init); return null; });
+ boolean found=false;
+ for( CLInitNode init : inits )
+ if( init.cu()==integerInit._compunit ) {
+ assertFalse(init.bypass());
+ found=true;
+ }
+ assertTrue("The remote initialization guard must remain",found);
+ code.driver(CodeGen.Phase.TypeCheck);
+ }
+
+ @Test public void testExitCallEnd() {
+ CodeGen code=compile("""
+ { i32 -> i64 } _exit="C";
+ if(arg) return _exit(1);
+ return 17;
+ """);
+ var ends=new ArrayList<CallEndNode>();
+ code._start.walk(n -> { if( n instanceof CallEndNode end ) ends.add(end); return null; });
+ assertEquals(1,ends.size());
+ assertEquals(TypeTuple.make(Type.CONTROL,TypeMem.TOP,TypeScalar.TOP),ends.get(0)._type);
+ // The concrete call survives scheduling and encoding; do not execute it.
+ code.driver(CodeGen.Phase.Encoding,TestC.CPU_PORT,TestC.CALL_CONVENTION);
+ var calls=new ArrayList<CallNode>();
+ code._start.walk(n -> { if( n instanceof CallNode call ) calls.add(call); return null; });
+ assertEquals(1,calls.size());
+ assertTrue(calls.get(0) instanceof MachNode);
+ }
+
+ @Test public void testExitMixedTargets() {
+ CodeGen code=compile("""
+ { i32 -> i64 } _exit="C", other="C";
+ return (arg ? _exit : other)(1);
+ """);
+ var ends=new ArrayList<CallEndNode>();
+ code._start.walk(n -> { if( n instanceof CallEndNode end ) ends.add(end); return null; });
+ assertEquals(1,ends.size());
+ TypeTuple state=(TypeTuple)ends.get(0)._type;
+ assertEquals(Type.CONTROL,state.ctl());
+ assertNotEquals(TypeMem.TOP,state._types[1]);
+ assertEquals(TypeInteger.BOT,state.ret());
+ // A Simple function named _exit has ordinary return semantics.
+ code=compile("val _exit={i64 x -> x+1;}; return _exit(arg);");
+ assertEquals("18",Eval2.eval(code,17));
+ }
+
+ @Test public void testAllocationBuddyLoop() {
+ // Two iterations' blocks may coexist; neither occupies iteration scratch.
+ CodeGen code=compile("""
+ val work_noInline={i64 n ->
+ u8[^] !last=new u8[^1];
+ i64 total=0;
+ while(n>0) {
+ val next=new u8[^n];
+ total+=last#;
+ last=next;
+ n--;
+ }
+ return total+last#;
+ };
+ return work_noInline(arg);
+ """);
+ var sum=code._allocation.summary("work_noInline").requireSupported();
+ boolean carried=false;
+ for( Allocation.Summary loop : sum._frames )
+ for( Allocation.Site site : loop._continues )
+ if( site._allocation!=null && site._frame==loop ) {
+ assertTrue(site.buddy());
+ assertFalse(loop._scratch.contains(site));
+ carried=true;
+ }
+ assertTrue(carried);
+ }
+
+ @Test public void testSummaryOwnEffects() throws Exception {
+ Path base=Files.createDirectories(Path.of("build/objs/summary-effects"));
+ Path lib=Files.createTempDirectory(base,"own-");
+ new CodeGen(null,lib.toString(),null,"Effects","""
+ u8[] !saved=new u8[0];
+ val retain_noInline={u8[] xs -> saved=xs; return 0;};
+ val _callback_noInline={i64 n -> n+1;};
+ val _unused_noInline={i64 n -> n+2;};
+ val clean_noInline={i64 n -> n+3;};
+ val publish_noInline={ ->
+ { {i64 -> i64} -> i64 } publish="C";
+ publish(_callback_noInline);
+ while(true) {}
+ };
+ """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ CodeGen code=new CodeGen(null,null,paths,"Clean",
+ "return Effects.clean_noInline(arg);",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
+ for( FunNode fun : code._linker )
+ if( fun!=null && !fun.isDead() && fun._name!=null ) {
+ assertFalse(fun._name,fun._name.contains("publish_noInline"));
+ assertFalse(fun._name,fun._name.contains("_callback_noInline"));
+ assertFalse(fun._name,fun._name.contains("_unused_noInline"));
+ if( fun._name.endsWith("clean_noInline") ) {
+ assertNotNull(fun.summary());
+ assertSame(com.seaofnodes.simple.type.XInt.EMPTY,fun.summary()._effects._writes);
+ }
+ }
+ assertEquals("20",Eval2.eval(code,17));
+
+ code=new CodeGen(null,null,paths,"Retain",
+ "Effects.retain_noInline(new u8[3]); return Effects.saved#;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ boolean retained=false;
+ for( FunNode fun : code._linker )
+ if( fun!=null && !fun.isDead() && fun._name!=null && fun._name.endsWith("retain_noInline") ) {
+ assertNotNull(fun.summary());
+ assertTrue(fun.summary()._effects._referenceWrites);
+ assertNotSame(com.seaofnodes.simple.type.XInt.EMPTY,fun.summary()._effects._writes);
+ retained=true;
+ }
+ assertTrue(retained);
+ assertEquals("3",Eval2.eval(code,0));
+
+ // Retention on a nonreturning path must survive saving/loading too.
+ code=new CodeGen(null,null,paths,"Publish",
+ "if(arg) Effects.publish_noInline(); return 7;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ boolean callback=false;
+ for( FunNode fun : code._linker )
+ if( fun!=null && !fun.isDead() && fun._name!=null && fun._name.endsWith("_callback_noInline") ) {
+ assertTrue(fun.unknownCallers());
+ callback=true;
+ }
+ assertTrue("The native can retain the callback before the infinite loop",callback);
+ }
+
+ @Test public void testArrayDeleteAryu8Copy() {
+ var paths=new Ary<>(new String[]{TestC.RELEASE_SYS_DIR});
+ CodeGen code=new CodeGen(null,null,paths,"Test","""
+ struct aryu8 {
+ u32 !len = 0;
+ u8[^] !buf = new u8[^1];
+ val _grow_noInline = { u32 len2 ->
+ if( len2 <= buf# ) return self;
+ val old = buf;
+ val next = new u8[^len2];
+ sys.ary.copy(next,0,old,0,len);
+ buf = next;
+ old.del();
+ return self;
+ };
+ };
+ u32 extra=arg;
+ return new aryu8()._grow_noInline(extra);
+ """,126,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ assertEquals(2,code._allocation._deletes.size());
+ ArrayDelete deletion=code._allocation._deletes.get(0);
+ assertTrue(code._allocation._deletes.get(1).toString(),code._allocation._deletes.get(1).proven());
+ FunNode copy=null;
+ for( FunNode fun : code._linker )
+ if( fun!=null && !fun.isDead() && "sys.ary.copy".equals(fun._name) ) copy=fun;
+ assertNotNull(copy);
+ CallNode copyCall=null;
+ for( CallNode call : code._calls )
+ if( !call.isDead() && call.fptr()._type instanceof TypeFunPtr fp &&
+ fp.isConstant() && fp.fidx()==copy.sig().fidx() ) copyCall=call;
+ assertNotNull(copyCall);
+ var effects=code._effects.get(copy);
+ var contract=code._allocation.summary("sys.ary.copy").requireSupported();
+ // Break here: the unloaded copy's contract returns arg3 (dst).
+ assertNotNull(copy.summary());
+ assertNotNull(copy.summary()._allocation);
+ assertEquals(1,contract._returns.size());
+ assertEquals(3,contract._returns.iterator().next()._arg);
+ assertFalse(effects._referenceWrites);
+ assertTrue(copy.ret().expr()._type instanceof TypeMemPtr);
+ assertNull(deletion.toString(),deletion._reject);
+ assertNotNull(deletion._unique);
+ code.driver(CodeGen.Phase.TypeCheck);
+ }
+
+ @Test public void testAllocationSerializedContracts() throws Exception {
+ Path base=Files.createDirectories(Path.of("build/objs/allocation-contracts"));
+ Path lib=Files.createTempDirectory(base,"graph-");
+ var paths=new Ary<>(new String[]{lib.toString()});
+ new CodeGen(null,lib.toString(),null,"Contracts",THING+HOLDER+"""
+ val make_noInline={i64 n -> new Thing(n);};
+ val holder_noInline={ -> new Holder;};
+ val field_noInline={Holder h -> h.c;};
+ val put_noInline={ !Holder h, Thing t -> h.c=t; return 0;};
+ val choose_noInline={Thing a, Thing b, i64 n -> n ? a : b;};
+ struct Link { Link? !next; i64 x; new Link={i64 n -> x=n;}; };
+ val cycle_noInline={i64 n ->
+ val a=new Link(n), b=new Link(n+1);
+ a.next=b; b.next=a; return a;
+ };
+ val unsupported_noInline={u32 n -> new u8[n];};
+ val buddy_noInline={u32 n -> new u8[^n];};
+ """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ CodeGen code=new CodeGen(null,null,paths,"Use","""
+ val work_noInline={i64 n ->
+ val h=Contracts.holder_noInline();
+ val a=Contracts.make_noInline(n), b=Contracts.make_noInline(n+1);
+ Contracts.put_noInline(h,a);
+ return Contracts.choose_noInline(Contracts.field_noInline(h),b,n);
+ };
+ return work_noInline(arg).x + Contracts.cycle_noInline(arg).x;
+ """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
+ for( String name : new String[]{"make_noInline","field_noInline","put_noInline","choose_noInline","cycle_noInline"} ) {
+ var sum=code._allocation.summary(name).requireSupported();
+ assertNotNull("Contract must work without loading "+name,sum._fun.summary());
+ }
+ var make=code._allocation.summary("make_noInline");
+ var made=make._returns.iterator().next();
+ assertTrue(made._fresh);
+ assertNull(made._allocation);
+ assertTrue(made._bytes>0);
+ assertEquals("arg3.c",code._allocation.summary("field_noInline")._returns.iterator().next()._name);
+ assertEquals(2,code._allocation.summary("choose_noInline")._returns.size());
+ assertEquals(4,code._allocation.summary("put_noInline")._retained.iterator().next()._arg);
+ var cycle=code._allocation.summary("cycle_noInline");
+ var a=cycle._returns.iterator().next();
+ var b=a._fields.get("next").iterator().next();
+ assertTrue(b._fields.get("next").contains(a));
+ var work=code._allocation.summary("work_noInline").requireSupported();
+ int copies=0;
+ for( Allocation.Site site : work._sites )
+ if( site._fresh && site._name.endsWith("/"+made._name) ) {
+ assertTrue(work._returns.contains(site));
+ copies++;
+ }
+ assertEquals("Each call imports distinct fresh storage",2,copies);
+ assertEquals("34",Eval2.eval(code,17));
+
+ // Contracts composed from imported contracts survive another export.
+ new CodeGen(null,lib.toString(),paths,"Bridge",
+ "val forward_noInline={i64 n -> Contracts.make_noInline(n);};",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ code=new CodeGen(null,null,paths,"UseBridge","return Bridge.forward_noInline(arg).x;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ var forward=code._allocation.summary("forward_noInline").requireSupported();
+ assertNotNull(forward._fun.summary());
+ assertTrue(forward._returns.iterator().next()._fresh);
+ assertEquals(made._bytes,forward._returns.iterator().next()._bytes);
+ assertEquals("19",Eval2.eval(code,19));
+
+ code=new CodeGen(null,null,paths,"Unsupported","u32 n=arg; return Contracts.unsupported_noInline(n)#;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.Allocation);
+ var unsupported=code._allocation.summary("unsupported_noInline");
+ assertNotNull(unsupported._fun.summary());
+ assertFalse(unsupported.supported());
+ assertTrue(unsupported._reject,unsupported._reject.contains("variable-size allocation"));
+
+ code=new CodeGen(null,null,paths,"Buddy","u32 n=arg; return Contracts.buddy_noInline(n)#;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ var buddy=code._allocation.summary("buddy_noInline").requireSupported();
+ assertNotNull(buddy._fun.summary());
+ var block=buddy._returns.iterator().next();
+ assertTrue(block._fresh);
+ assertTrue(block.buddy());
+ assertEquals(-1,block._bytes);
+ }
+
+ @Test public void testArrayDeleteImportedReturnedAlias() throws Exception {
+ Path base=Files.createDirectories(Path.of("build/objs/allocation-contracts"));
+ Path lib=Files.createTempDirectory(base,"borrow-");
+ var paths=new Ary<>(new String[]{lib.toString()});
+ new CodeGen(null,lib.toString(),null,"Borrow","val identity_noInline={u8[] xs -> xs;};",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ for( boolean after : new boolean[]{false,true} ) {
+ String source="{ val a=new u8[^8]; val b=Borrow.identity_noInline(a); "+
+ (after ? "a.del(); return b[0]; }" : "val x=b[0]; a.del(); return x; }");
+ CodeGen code=new CodeGen(null,null,paths,"Use",source,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.Allocation);
+ var contract=code._allocation.summary("identity_noInline").requireSupported();
+ assertNotNull(contract._fun.summary());
+ ArrayDelete deletion=code._allocation._deletes.get(0);
+ if( after ) {
+ assertNotNull(deletion.toString(),deletion._reject);
+ assertTrue(deletion._reject,deletion._reject.contains("survives deletion"));
+ } else {
+ assertTrue(deletion.toString(),deletion.proven());
+ code.driver(CodeGen.Phase.TypeCheck);
+ }
+ }
+ }
+
+ private static final String OWNED_BUFFER="""
+ struct Buffer {
+ u8[^] !buf = new u8[^1];
+ val grow_noInline = { u32 n ->
+ if( n <= buf# ) return 0;
+ val old = buf;
+ buf = new u8[^n];
+ old.del();
+ return 0;
+ };
+ };
+ """;
+
+ @Test public void testArrayConsumeCallers() {
+ compile(OWNED_BUFFER.replace("return 0;","return self;")+"""
+ { val v=new Buffer; return v.grow_noInline(8).buf#; }
+ """);
+ for( String body : new String[]{
+ "val v=new Buffer; v.grow_noInline(8); return v.buf#;",
+ "val v=new Buffer; val w=v; v.grow_noInline(8); return w.buf#;",
+ "val v=new Buffer; val saved=v.buf; val x=saved[0]; v.grow_noInline(8); return x;"} ) {
+ CodeGen code=compile(OWNED_BUFFER+"{"+body+"}");
+ boolean required=false, checked=false;
+ for( ArrayDelete deletion : code._allocation._deletes ) {
+ assertNull(deletion.toString(),deletion._reject);
+ if( deletion._requirement!=null ) {
+ assertEquals("arg2.buf",deletion._requirement.toString()); required=true;
+ } else { assertTrue(deletion.proven()); checked=true; }
+ }
+ assertTrue(required); assertTrue(checked);
+ }
+ for( String body : new String[]{
+ "val v=new Buffer; val saved=v.buf; v.grow_noInline(8); return saved[0];",
+ "val v=new Buffer; val saved=v.buf; v.grow_noInline(8); return saved#;",
+ "val v=new Buffer; val saved=v.buf; v.grow_noInline(8); saved[0]=1; return 0;"} )
+ deleteError(OWNED_BUFFER+"{"+body+"}","deletion");
+ }
+
+ @Test public void testArrayConsumeForwarding() {
+ CodeGen code=compile(OWNED_BUFFER+"""
+ val forward_noInline={ !Buffer v,u32 n -> v.grow_noInline(n);};
+ { val v=new Buffer; forward_noInline(v,8); return v.buf#; }
+ """);
+ assertEquals(List.of(new ArrayDelete.Consume(3,List.of("buf"))),
+ code._allocation.summary("forward_noInline")._consumes);
+ deleteError(OWNED_BUFFER+"""
+ val forward_noInline={ !Buffer v,u32 n -> v.grow_noInline(n);};
+ { val v=new Buffer; val saved=v.buf; forward_noInline(v,8); return saved[0]; }
+ ""","deletion");
+ String nested=OWNED_BUFFER+"""
+ struct Outer {!Buffer !b; new Outer={!Buffer b -> self.b=b;};};
+ val nested_noInline={ !Outer o -> o.b.grow_noInline(8);};
+ """;
+ code=compile(nested+"{val v=new Buffer; val o=new Outer(v); nested_noInline(o); return o.b.buf#;}");
+ assertEquals(List.of(new ArrayDelete.Consume(3,List.of("b","buf"))),
+ code._allocation.summary("nested_noInline")._consumes);
+ deleteError(nested+"{val v=new Buffer; val o=new Outer(v); val saved=v.buf; nested_noInline(o); return saved[0];}","deletion");
+
+ String redirected=OWNED_BUFFER+"""
+ struct Outer {!Buffer !b; new Outer={!Buffer b -> self.b=b;};};
+ val redirect_noInline={ !Outer o,!Buffer b -> o.b=b; o.b.grow_noInline(8);};
+ """;
+ code=compile(redirected+"{val a=new Buffer,b=new Buffer; val o=new Outer(a); redirect_noInline(o,b); return o.b.buf#;}");
+ assertEquals(List.of(new ArrayDelete.Consume(4,List.of("buf"))),
+ code._allocation.summary("redirect_noInline")._consumes);
+ deleteError(redirected+"{val a=new Buffer,b=new Buffer; val o=new Outer(a); val saved=b.buf; redirect_noInline(o,b); return saved[0];}","deletion");
+ }
+
+ @Test public void testArrayConsumeStoredAliases() {
+ String saved="struct Saved {u8[]? !a;};";
+ deleteError(OWNED_BUFFER+saved+"""
+ { val v=new Buffer; val saved=new Saved; saved.a=v.buf;
+ v.grow_noInline(8); return saved.a==null; }
+ ""","still holds the array");
+ deleteError(OWNED_BUFFER+saved+"""
+ { val v=new Buffer; val saved=new Saved; saved.a=v.buf;
+ if(arg) saved.a=null;
+ v.grow_noInline(8); return saved.a==null; }
+ ""","still holds the array");
+ compile(OWNED_BUFFER+saved+"""
+ { val v=new Buffer; val saved=new Saved; saved.a=v.buf;
+ saved.a=null; v.grow_noInline(8); return v.buf#; }
+ """);
+ // Aliasing two formal parameters must not evade the callee's check.
+ deleteError(OWNED_BUFFER+"""
+ val bad_noInline={ !Buffer v,u8[] saved -> v.grow_noInline(8); return saved[0];};
+ { val v=new Buffer; return bad_noInline(v,v.buf); }
+ ""","deletion");
+ deleteError(OWNED_BUFFER+"""
+ val consume_noInline={u8[^] a -> a.del(); return 0;};
+ { val v=new Buffer; consume_noInline(v.buf); return v.buf#; }
+ ""","still holds the array");
+ }
+
+ @Test public void testArrayConsumeIndirect() {
+ String functions="""
+ val consume_noInline={u8[^] a -> a.del(); return 0;};
+ val leave_noInline={u8[^] a -> a#;};
+ """;
+ compile(functions+"{val a=new u8[^8]; return (arg ? consume_noInline : leave_noInline)(a);}");
+ deleteError(functions+"""
+ {val a=new u8[^8]; (arg ? consume_noInline : leave_noInline)(a); return a[0];}
+ ""","deletion");
+ deleteError("""
+ val recurse_noInline={u8[^] a,i64 n -> if(n) return recurse_noInline(a,n-1); a.del(); return 0;};
+ return recurse_noInline(new u8[^8],arg);
+ ""","recursive consuming");
+ deleteError(functions+"""
+ val invoke_noInline={ {u8[^] -> i64} f,u8[^] a -> f(a);};
+ return invoke_noInline(consume_noInline,new u8[^8]);
+ ""","ownership contract");
+ deleteError(functions+"""
+ struct Handler { val f=consume_noInline; };
+ { {Handler -> i64} invoke="C";
+ return invoke(new Handler); }
+ ""","Consuming callback");
+ }
+
+ @Test public void testArrayConsumeImported() throws Exception {
+ Path base=Files.createDirectories(Path.of("build/objs/ownership"));
+ Path lib=Files.createTempDirectory(base,"consume-");
+ var paths=new Ary<>(new String[]{lib.toString()});
+ new CodeGen(null,lib.toString(),null,"Types","struct Buffer {u8[^] !buf=new u8[^1];};",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),paths,"Grow","""
+ val grow_noInline={ !Types.Buffer v,u32 n ->
+ if(n<=v.buf#) return 0;
+ val old=v.buf; v.buf=new u8[^n]; old.del(); return 0;
+ };
+ """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),paths,"Forward","""
+ val forward_noInline={ !Types.Buffer v,u32 n -> Grow.grow_noInline(v,n);};
+ """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ for( int variant=0; variant<4; variant++ ) {
+ boolean alias=variant==1;
+ String grow=variant==3 ? "Forward.forward_noInline(v,8); Forward.forward_noInline(v,16);" :
+ variant==2 ? "for(u32 i=2; i<arg; i++) Forward.forward_noInline(v,i);" :
+ "Forward.forward_noInline(v,8);";
+ CodeGen code=new CodeGen(null,null,paths,"Use","""
+ { val v=new Types.Buffer;
+ """+(alias ? "val saved=v.buf;" : "")+grow+" return "+
+ (alias ? "saved[0];}" : "v.buf#;}"),123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ var sum=code._allocation.summary("forward_noInline");
+ assertNotNull("Use the serialized requirement without loading the body",sum._fun.summary());
+ assertEquals(List.of(new ArrayDelete.Consume(3,List.of("buf"))),sum._consumes);
+ if( alias ) {
+ try { code.driver(CodeGen.Phase.TypeCheck); fail("Saved alias must reject"); }
+ catch( com.seaofnodes.simple.parser.Parser.ParseException e ) {
+ assertTrue(e.getMessage(),e.getMessage().contains("deletion"));
+ }
+ } else {
+ for( ArrayDelete check : code._allocation._deletes ) assertTrue(check.toString(),check.proven());
+ code.driver(CodeGen.Phase.TypeCheck);
+ }
+ }
+ }
+
+ @Test public void testArrayConsumeGrowLoop() {
+ // Reduced from parseAryI64: nums.add(...) repeatedly calls _grow,
+ // which may replace/delete the backing buffer on each iteration.
+ CodeGen code=new CodeGen(OWNED_BUFFER+"""
+ {
+ val v=new Buffer;
+ u32 n=arg;
+ for(u32 i=2; i<n; i++) v.grow_noInline(i);
+ return v.buf#;
+ }
+ """).driver(CodeGen.Phase.Allocation);
+ ArrayDelete repeated=null;
+ for( ArrayDelete check : code._allocation._deletes )
+ if( !Intrinsic.arrayDelete(check._call) ) repeated=check;
+ assertNotNull("Exercise the repeated consuming call",repeated);
+ CallNode growCall=repeated._call;
+ FunNode grow=code.link((TypeFunPtr)growCall.fptr()._type);
+ var contract=code._allocation.summary(grow._name);
+ // Break here: code, repeated, growCall, grow, and contract are available.
+ assertEquals(List.of(new ArrayDelete.Consume(2,List.of("buf"))),contract._consumes);
+ assertTrue(repeated.toString(),repeated.proven());
+ code.driver(CodeGen.Phase.TypeCheck);
+ }
+
+ @Test public void testArrayConsumeLoopBackedges() {
+ compile(OWNED_BUFFER+"""
+ val many_noInline={ !Buffer v,u32 n ->
+ val same=v;
+ for(u32 i=2; i<n; i++) same.grow_noInline(i);
+ return v.buf#;
+ };
+ u32 n=arg;
+ return many_noInline(new Buffer,n);
+ """);
+ compile(OWNED_BUFFER+"""
+ { val v=new Buffer;
+ u32 n=arg;
+ for(u32 i=2; i<n; i++) {
+ val before=v.buf#;
+ v.grow_noInline(i);
+ if(before>4) break;
+ }
+ return v.buf#;
+ }
+ """);
+ compile(OWNED_BUFFER+"""
+ { val v=new Buffer;
+ u32 n=arg;
+ for(u32 i=2; i<n; i++)
+ for(u32 j=2; j<i; j++) v.grow_noInline(j);
+ return v.buf#;
+ }
+ """);
+ // Each iteration gets its own allocation. Repeating delete on one
+ // allocation instead must fail, even without any other array accesses.
+ compile("{ for(int i=0; i<arg; i++) { val a=new u8[^8]; a.del(); } return 0; }");
+ deleteError("val a=new u8[^8]; for(int i=0; i<arg; i++) a.del(); return 0;","backedge");
+
+ deleteError(OWNED_BUFFER+"""
+ val v=new Buffer;
+ val saved=v.buf;
+ u32 n=arg;
+ for(u32 i=2; i<n; i++) v.grow_noInline(i);
+ return saved;
+ ""","backedge");
+
+ deleteError(OWNED_BUFFER+"""
+ val v=new Buffer;
+ val saved=v.buf;
+ u32 n=arg;
+ int sum=0;
+ for(u32 i=2; i<n; i++) {
+ sum+=saved[0];
+ v.grow_noInline(i);
+ }
+ return sum;
+ ""","backedge");
+ // A previous iteration's local is still an alias, not a fresh reload.
+ deleteError(OWNED_BUFFER+"""
+ val v=new Buffer;
+ u8[^]? !saved=null;
+ u32 n=arg;
+ int sum=0;
+ for(u32 i=2; i<n; i++) {
+ if(saved) sum+=saved[0];
+ saved=v.buf;
+ v.grow_noInline(i);
+ }
+ return sum;
+ ""","backedge");
+ // Conservatively reject copies of the replacement across the boundary.
+ // The SSA case could pass with a proof that its last use precedes the
+ // next grow; that ordering is not yet an iteration-entry contract.
+ deleteError(OWNED_BUFFER+"""
+ val v=new Buffer;
+ u8[^]? !saved=null;
+ u32 n=arg;
+ int sum=0;
+ for(u32 i=2; i<n; i++) {
+ if(saved) sum+=saved[0];
+ v.grow_noInline(i);
+ saved=v.buf;
+ }
+ return sum;
+ ""","backedge");
+ deleteError(OWNED_BUFFER+"""
+ struct Saved { u8[^]? !a=null; };
+ val v=new Buffer;
+ val saved=new Saved;
+ u32 n=arg;
+ for(u32 i=2; i<n; i++) {
+ v.grow_noInline(i);
+ saved.a=v.buf;
+ }
+ return saved.a ? saved.a# : 0;
+ ""","backedge");
+ deleteError(OWNED_BUFFER+"""
+ struct Saved { u8[^]? !a=null; };
+ val save_noInline={ !Saved saved,!Buffer v -> saved.a=v.buf; return 0; };
+ val v=new Buffer;
+ val saved=new Saved;
+ u32 n=arg;
+ for(u32 i=2; i<n; i++) {
+ v.grow_noInline(i);
+ save_noInline(saved,v);
+ }
+ return saved.a ? saved.a# : 0;
+ ""","backedge");
+ // A consuming contract describes the entry buffer. It must not hide
+ // the callee publishing a new alias of its replacement before return.
+ deleteError(OWNED_BUFFER.replace("u8[^] !buf = new u8[^1];",
+ "u8[^] !buf = new u8[^1]; u8[^]? !saved=null;")
+ .replace("old.del();","old.del(); saved=buf;")+"""
+ val v=new Buffer;
+ u32 n=arg;
+ for(u32 i=2; i<n; i++) v.grow_noInline(i);
+ return v.saved ? v.saved# : 0;
+ ""","backedge");
+ }
+ @Test public void testArrayConsumeTwoGrows() {
+ // Reduced from text.string's padding, text, and trailing-padding grows.
+ CodeGen code=new CodeGen(OWNED_BUFFER+"""
+ {
+ val v=new Buffer;
+ v.grow_noInline(8);
+ v.grow_noInline(16);
+ return v.buf#;
+ }
+ """).driver(CodeGen.Phase.Allocation);
+ ArrayDelete first=null, second=null;
+ for( ArrayDelete check : code._allocation._deletes ) {
+ if( Intrinsic.arrayDelete(check._call) ) continue;
+ if( first==null ) first=check;
+ else if( check._call.dominates(first._call,null) ) { second=first; first=check; }
+ else second=check;
+ }
+ assertNotNull(first);
+ assertNotNull(second);
+ // Break here: code, first, and second expose both caller checkpoints.
+ assertTrue(first.toString(),first.proven());
+ assertTrue(second.toString(),second.proven());
+ code.driver(CodeGen.Phase.TypeCheck);
+ }
+
+ @Test public void testArrayConsumeComposedCalls() {
+ compile(OWNED_BUFFER+"""
+ { val v=new Buffer;
+ if(arg) v.grow_noInline(8);
+ v.grow_noInline(16);
+ return v.buf#;
+ }
+ """);
+ compile(OWNED_BUFFER+"""
+ { val v=new Buffer; u32 n=arg;
+ for(u32 i=2; i<n; i++) {
+ v.grow_noInline(i);
+ v.grow_noInline(n);
+ }
+ return v.buf#;
+ }
+ """);
+ compile(OWNED_BUFFER.replace("u8[^] !buf = new u8[^1];","""
+ u8[^] !buf;
+ new Buffer={u8[^] initial -> buf=initial;};
+ """)+"""
+ { val v=new Buffer(new u8[^1]);
+ v.grow_noInline(8); v.grow_noInline(16); return v.buf#;
+ }
+ """);
+ String append=OWNED_BUFFER+"""
+ val append_noInline={ !Buffer v,u8[~] xs ->
+ v.grow_noInline(8); return xs[0]+v.buf#;
+ };
+ """;
+ compile(append+"{val v=new Buffer; return append_noInline(v,\"hello\");}");
+ deleteError(append+"{val v=new Buffer; return append_noInline(v,v.buf);}","aliases the array");
+ // Distinct wrapper formals can still name the same wrapper. A saved
+ // field load cannot inherit the direct-array-parameter disjointness.
+ deleteError(OWNED_BUFFER+"""
+ val peek_noInline={ !Buffer a,!Buffer b ->
+ val saved=a.buf; b.grow_noInline(8); return saved[0];
+ };
+ { val v=new Buffer; return peek_noInline(v,v); }
+ ""","deletion");
+ for( boolean between : new boolean[]{false,true} )
+ deleteError(OWNED_BUFFER+"{val v=new Buffer;"+
+ (between ? "v.grow_noInline(8); val saved=v.buf;" : "val saved=v.buf; v.grow_noInline(8);")+
+ "v.grow_noInline(16); return saved[0];}","deletion");
+ deleteError(OWNED_BUFFER+"""
+ struct Saved {u8[^]? !a=null;};
+ { val v=new Buffer; val s=new Saved; u32 n=arg;
+ for(u32 i=2; i<n; i++) {
+ v.grow_noInline(i); v.grow_noInline(n); s.a=v.buf;
+ }
+ return s.a ? s.a# : 0;
+ }
+ ""","backedge");
+ compile("""
+ struct Saved {u8[^]? !a=null;};
+ val save_noInline={ !Saved s,u8[^] a -> s.a=a; return 0;};
+ { val s=new Saved; val a=new u8[^8];
+ save_noInline(s,a); s.a=null; a.del(); return 0;
+ }
+ """);
+ try {
+ compile("""
+ u8[^]? !saved=null;
+ val save_noInline={u8[^] a -> saved=a; return 0;};
+ {val a=new u8[^8]; save_noInline(a); a.del(); return saved ? saved# : 0;}
+ """);
+ fail("Global retained alias must reject");
+ } catch( com.seaofnodes.simple.parser.Parser.ParseException e ) {
+ // The helper's global initialization remains an opaque effect.
+ assertTrue(e.getMessage(),e.getMessage().contains("unknown reference effects"));
+ }
+ }
+
+ @Test public void testArrayConsumeImportedOpaqueEffects() throws Exception {
+ Path base=Files.createDirectories(Path.of("build/objs/ownership"));
+ Path lib=Files.createTempDirectory(base,"opaque-");
+ var paths=new Ary<>(new String[]{lib.toString()});
+ new CodeGen(null,lib.toString(),null,"Types","struct Saved {i64 !address=0;};",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),paths,"Opaque","""
+ val save_noInline={ !Types.Saved s,u8[] a -> s.address=a; return 0;};
+ """,123,true,TypeInteger.BOT).driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ CodeGen code=new CodeGen(null,null,paths,"Use","""
+ { val s=new Types.Saved; val a=new u8[^8];
+ Opaque.save_noInline(s,a); a.del(); return s.address;
+ }
+ """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ assertNotNull(code._allocation.summary("save_noInline")._fun.summary());
+ try { code.driver(CodeGen.Phase.TypeCheck); fail("Raw store must remain opaque after loading its summary"); }
+ catch( com.seaofnodes.simple.parser.Parser.ParseException e ) {
+ assertTrue(e.getMessage(),e.getMessage().contains("unknown reference effects"));
+ }
+ }
+}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java b/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java
index d6d97ef1..8eadd25a 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java
@@ -215,6 +215,8 @@ public abstract class Eval2 {
// Make a call.
private static CFGNode call( CallNode call ) {
+ if( Intrinsic.arrayDelete(call) )
+ throw new UnsupportedOperationException("Array .del(): runtime recycling is not implemented yet");
int nargs = call.nargs()+1; // Include memory.
for( int i = 0; i<nargs; i++ ) VALUE_CACHE.setX(i,val(call.in(i+1)));
return enter(CODE.link(tfp(call.fptr())),call.cend());
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java
index 6505009d..2794fca9 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java
@@ -27,7 +27,7 @@ public class PhaseTest {
code.driver(Phase.TypeCheck); // A repeated request does not rerun anything.
assertEquals("45",Eval2.eval(code,10));
code.driver(Phase.LocalSched);
- assertEquals("Parse Iter Opto IterPostOpto FinalizeIR TypeCheck LoopTree Unlink Schedule LocalSched",
+ assertEquals("Parse Iter Opto IterPostOpto FinalizeIR LoopTree Allocation TypeCheck Unlink Schedule LocalSched",
String.join(" ",phases));
assertNull(code._serial);
assertNull(code._mach);
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java
index 447025f6..4e590d2e 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java
@@ -224,12 +224,13 @@ public class SelectiveLoadingTest {
"if(arg==0) return -1; return Lib.api.p_noInline(((arg<<32)>>32));",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
assertNotNull(function(code,"Lib.Api.p_noInline").summary());
assertNotNull(function(code,"Lib.Work.write_noInline").summary());
- assertNotNull(function(code,"Lib.Unused.f").summary());
+ assertAbsent(code,"Lib.Unused.f");
assertEquals("-1",Eval2.eval(code,0));
assertNotNull("An untaken branch does not load its target",function(code,"Lib.Api.p_noInline").summary());
assertEquals("42",Eval2.eval(code,41));
assertNull(function(code,"Lib.Work.write_noInline").summary());
- assertNotNull("Evaluation leaves unrelated objects unloaded",function(code,"Lib.Unused.f").summary());
+ assertNull("Evaluation leaves unrelated objects unloaded",
+ code.getElf(code._compunits.get("Lib/Unused")._obj)._nodes);
assertEquals("6",Eval2.eval(code,5));
code=new CodeGen(null,app.toString(),paths,"Main",
@@ -237,7 +238,7 @@ public class SelectiveLoadingTest {
.driver(CodeGen.Phase.TypeCheck);
assertNull("p requested Api's implementation",function(code,"Lib.Api.p").summary());
assertNotNull("The remaining call needs a signature, not a body",function(code,"Lib.Work.write_noInline").summary());
- assertNotNull("A namespace reexport does not request IR",function(code,"Lib.Unused.f").summary());
+ assertAbsent(code,"Lib.Unused.f");
code.driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
Path driver = app.resolve("driver.c");
Files.writeString(driver,"""
@@ -260,6 +261,11 @@ public class SelectiveLoadingTest {
} catch( RuntimeException ex ) { assertTrue(ex.getMessage(),ex.getMessage().contains("Lib/Work")); }
}
+ private static void assertAbsent(CodeGen code, String name) {
+ for( FunNode fun : code._linker )
+ assertTrue(name,fun==null || fun.isDead() || !name.equals(fun._name));
+ }
+
private static FunNode function(CodeGen code, String name) {
for( FunNode fun : code._linker ) if( fun!=null && name.equals(fun._name) ) return fun;
throw new AssertionError("Missing function "+name);
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java b/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java
index adcc1b3a..ceea5157 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java
@@ -383,4 +383,23 @@ public class TypeTest {
Type mt = open.meet(list);
Assert.assertEquals(list,mt);
}
+
+ @Test public void testConstantArrayPointerLattice() {
+ TypeMemPtr empty=TypeMemPtr.make((byte)2,TypeStruct.makeAry("[]u8",2,3,TypeConAry.make("")),true);
+ TypeMemPtr now=TypeMemPtr.make((byte)2,TypeStruct.makeAry("[]u8",2,3,TypeConAry.make("now")),true);
+ TypeMemPtr abc=TypeMemPtr.make((byte)2,TypeStruct.makeAry("[]u8",2,3,TypeConAry.make("abc")),true);
+ Assert.assertTrue(empty.isConstant());
+ Assert.assertTrue(now.isConstant());
+ Assert.assertFalse(empty.meet(now).isConstant());
+ Assert.assertFalse(now.meet(abc).isConstant());
+ Type[] types={empty,now,abc,empty.dual(),now.dual(),abc.dual(),now.makeVar()};
+ for( Type a : types ) for( Type b : types ) {
+ check_symmetric(a,b);
+ Assert.assertTrue(a.isa(a.meet(b)));
+ for( Type c : types ) {
+ assertSame(a.meet(b).meet(c),a.meet(b.meet(c)));
+ Assert.assertTrue(a.join(c).isa(a.meet(b).join(c)));
+ }
+ }
+ }
}