summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--chapter33/README.md18
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java11
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java19
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/PointsTo.java460
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/BreakoutTest.java12
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/PointsToTest.java377
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Simple.java2
9 files changed, 899 insertions, 4 deletions
diff --git a/chapter33/README.md b/chapter33/README.md
index 2c995ca5..9dd0116a 100644
--- a/chapter33/README.md
+++ b/chapter33/README.md
@@ -6,7 +6,23 @@ English | [日本語](README.ja.md)
This chapter starts with the completed chapter 32 compiler. Automatic memory
management will be introduced in small steps, keeping the full test suite passing.
-No new allocation analysis or reclamation is implemented yet.
+The `Allocation` phase follows loop normalization and computes points-to facts
+through the separate `PointsTo` analysis. It does not change the IR, choose
+storage, or insert reclamation.
+
+`PointsTo` is a flow-insensitive, field-sensitive inclusion analysis: one site
+per `NewNode` or static pointer constant, with weak field updates and one shared
+element field per array. Calls share callee facts; earlier inlining supplies
+context separation. Unloaded/native calls conservatively expose reference
+arguments and may return unknown storage or compatible escaped sites. These
+boundary approximations are not ownership or lifetime proofs.
+
+Tests can stop at `CodeGen.Phase.Allocation`, inspect
+`code._allocation._pointsTo`, and explicitly call `verify()` to recheck the
+fixed point. Normal compilation does not run that extra verification walk.
+Use `--dump-after-allocation` to print the facts, or set the JVM property
+`-Dsimple.pointsTo.dump=true` when running tests. `PointsToTest` covers local
+objects, fields, arrays, loops, recursion, escapes, and imported summaries.
Unloaded function summaries retain their possible callees through function-pointer
edges. These references keep a single default caller on each target without
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..f743e84e
--- /dev/null
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java
@@ -0,0 +1,11 @@
+package com.seaofnodes.simple.codegen;
+
+/** Memory-management phase. For now it only computes points-to facts;
+ * lifetime selection and allocation/reclamation rewrites come later. */
+public final class Allocation {
+ public final PointsTo _pointsTo;
+
+ public Allocation(CodeGen code) { _pointsTo = new PointsTo(code); }
+
+ @Override public String toString() { return _pointsTo.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 e677e855..3a7ec826 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
@@ -28,6 +28,7 @@ public class CodeGen {
IterPostOpto, // Peepholes and inlining using SCCP results
FinalizeIR, // Field layout, offset cleanup, function/CU roots
LoopTree, // Normalize loops and insert structural exits
+ Allocation, // Compute points-to facts; no storage changes yet
TypeCheck, // Last check for bad programs
Serialize, // Save ideal IR, including opaque class initialization
Lower, // Expand checked class initialization to ordinary IR
@@ -197,6 +198,7 @@ public class CodeGen {
// 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
@@ -254,6 +256,10 @@ public class CodeGen {
if( (dump & (1<<p2)) == 0 ) return;
if( (dump & (1<<30)) != 0 )
System.err.println("After "+_phase+":");
+ if( _phase==Phase.Allocation ) {
+ System.err.print(_allocation);
+ return;
+ }
System.err.println(_phase.ordinal() >= Phase.LocalSched.ordinal()
? asm(new SB()).toString()
: IRPrinter.prettyPrint(this));
@@ -553,7 +559,18 @@ public class CodeGen {
// ---------------------------
// Last check for bad programs
- public CodeGen typeCheck() { return phase(Phase.TypeCheck, _phase==Phase.LoopTree, () -> TypeCheck.run(this)); }
+ public CodeGen typeCheck() {
+ if( _phase==Phase.LoopTree ) allocation();
+ return phase(Phase.TypeCheck, _phase==Phase.Allocation, () -> TypeCheck.run(this));
+ }
+
+ public Allocation _allocation;
+ public CodeGen allocation() {
+ return phase(Phase.Allocation, _phase==Phase.LoopTree, () -> {
+ _allocation = new Allocation(this);
+ if( Boolean.getBoolean("simple.pointsTo.dump") ) System.out.print(_allocation);
+ });
+ }
// ---------------------------
// TypeCheck queued surviving CLInits during its existing error walk.
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/PointsTo.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/PointsTo.java
new file mode 100644
index 00000000..ea4aaefe
--- /dev/null
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/PointsTo.java
@@ -0,0 +1,460 @@
+package com.seaofnodes.simple.codegen;
+
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.*;
+
+import java.util.*;
+
+/** Flow-insensitive, field-sensitive, inclusion-based points-to analysis.
+ * One abstract site per NewNode; calls share their callee's facts (context
+ * sensitivity comes from earlier inlining). Fields use weak updates and array
+ * indices share one field. This pass neither proves ownership nor changes IR.
+ * <p></p>
+ * Facts only grow. Reading a fact registers a dependency; changing it
+ * schedules its readers. Loads/stores discover field dependencies as their
+ * bases grow. Unknown denotes storage outside the local Site collection.
+ * Unloaded and native callees conservatively escape reference arguments and
+ * return unknown storage or compatible escaped sites. This is not an ownership
+ * or lifetime proof and does not authorize storage reclamation.
+ */
+public final class PointsTo {
+ private final CodeGen _code;
+
+ // ---------------------------------
+ // Things that can be pointed-at; a NewNode allocation or a static pre-
+ // initialized Constant (basically a NewNode moved to program startup).
+ public static final class Site {
+ public final Node _node; // NewNode or static ConstantNode
+ // Each field has its own set of things it points to. This array is
+ // indexed by Field index; it may be null if there are no reference
+ // fields; each element can be null if e.g. its a non-pointer, OR if no
+ // points-to info is discovered.
+ public final Points[] _byFld;
+ // A Site is an allocated TypeStruct, with all reference fields
+ // holding points-to info
+ private Site(Node n) {
+ _node = n;
+ TypeStruct ts = type();
+ Points[] byFld = null;
+ if( ts._fields != null )
+ for( int fx=0; fx<ts._fields.length; fx++ )
+ if( reference(ts._fields[fx]._t) )
+ { byFld = new Points[ts._fields.length]; break; }
+ _byFld = byFld;
+ }
+
+ public String name() { return (_node instanceof NewNode ? "new#" : "static#")+_node._nid; }
+ public int nid() { return _node._nid; }
+ public TypeStruct type() {
+ return _node instanceof NewNode nnn ? nnn._ts : ((TypeMemPtr)(_node._type))._obj;
+ }
+
+
+ // Test access
+ public Points field(String name) {
+ if( _byFld==null ) return null;
+ int fx = type().find(name);
+ return fx<0 ? null : _byFld[fx];
+ }
+
+ // Return Site outgoing points-to on the field's alias.
+ Points field( int alias ) {
+ if( _byFld==null ) return null;
+ assert alias>1;
+ int fx = type().findAlias(alias);
+ if( fx<0 || !reference(type().at(fx)._t) ) return null;
+ Points field = _byFld[fx];
+ if( field==null )
+ _byFld[fx] = field = new Points();
+ return field;
+ }
+
+ @Override public String toString() { return str(new SB()).toString(); }
+ public SB str( SB sb ) {
+ TypeStruct ts = type();
+ sb.p(name()).p(':').p(ts._name);
+ FunNode fun = function(_node);
+ if( fun!=null ) sb.p(" in ").p(fun._name);
+ if( _node instanceof NewNode alloc ) sb.p(" bytes=").p(alloc.size()._type.toString());
+ sb.p('\n');
+ // Print field breakdown
+ if( _byFld !=null )
+ for( int fx=0; fx<_byFld.length; fx++ ) {
+ Points fld = _byFld[fx];
+ if( fld!=null ) {
+ sb.p(" .").p(ts._fields[fx]._fname).p(" -> ");
+ fld.strSite(sb).p('\n');
+ }
+ }
+ return sb;
+ }
+ }
+
+ // All allocation Sites by Node
+ public final IdentityHashMap<Node,Site> _sites = new IdentityHashMap<>();
+ private Site site(Node n) { Site site = new Site(n); _sites.put(n,site); return site; }
+
+ // ---------------------------------
+ // Outgoing edge structure; all the things a Node might point to. This is
+ // treated as an extra field on Nodes, found by HashMap lookup instead of
+ // field name.
+ public static final class Points {
+ // All the Sites we point to. This changes during solving as we
+ // discover more points-to relations
+ public final HashSet<Site> _sites = new HashSet<>();
+
+ // Might point to storage not represented in the Site collection.
+ public boolean _unknown;
+
+ // HashSet of readers of this PointsTo; if this Points changes, these
+ // readers hit the worklist. Identity is required: Node.hashCode
+ // caches the GVN lock.
+ private IdentityHashMap<Node,String> _readers;
+ Points addDep( Node dep ) {
+ if( _readers==null ) _readers = new IdentityHashMap<>();
+ _readers.put(dep,"");
+ return this;
+ }
+
+ private Points() { }
+
+ // A half-dozen variants of merge()
+ //
+ // Have a Point, merge the Point._unknown and all Point._sites.
+ // Have a HashSet<Site> instead.
+ // Have a Type, filter by Type.
+ // Have a WorkList, add changes if progress.
+
+ // Merge Site into our existing Sites, return true if progress
+ boolean merge( Site site ) { return _sites.add(site); }
+
+ void merge( Site site, WorkList<Node> work ) {
+ if( merge(site) )
+ changed(work);
+ }
+
+ boolean merge( Points p, Type t ) {
+ boolean progress = !_unknown && p._unknown && (_unknown = true);
+ for( Site site : p._sites )
+ if( t==null || site.type().isa(t) )
+ progress |= _sites.add(site);
+ return progress;
+ }
+
+ boolean merge( Points p ) { return merge(p,(Type)null); }
+
+ // Merge Points into self Points; queue readers if progress
+ void merge( Points p, WorkList<Node> work ) {
+ if( merge(p,(Type)null) )
+ changed(work);
+ }
+
+ void changed( WorkList<Node> work ) {
+ if( _readers != null )
+ for( Node n : _readers.keySet() )
+ work.push(n);
+ }
+
+ public boolean contains(Site site) {
+ // Unknown sites are outside this collection.
+ return _sites.contains(site);
+ }
+
+ @Override public String toString() { return str(new SB(),null).toString(); }
+ public SB str( SB sb, Node n ) {
+ if( n != null ) {
+ sb.p("#").p(n._nid).p(' ').p(n.label());
+ FunNode fun = function(n);
+ if( fun!=null ) sb.p(" in ").p(fun._name);
+ }
+ return strSite(sb.p(" => ")).p('\n');
+ }
+
+ SB strSite( SB sb ) {
+ sb.p('{');
+ for( Site site : _sites.stream().sorted(Comparator.comparingInt(Site::nid)).toList() )
+ sb.p(site.name()).p(", ");
+ if( _unknown )
+ sb.p("...");
+ else if( !_sites.isEmpty() )
+ sb.unchar(2);
+ return sb.p('}');
+ }
+ }
+
+ // Map from a Node to what it might point-to
+ public final IdentityHashMap<Node,Points> _points = new IdentityHashMap<>();
+
+ // Set or add points-to from a Node
+ private Points points(Node n) { return _points.computeIfAbsent( n, k -> new Points() ); }
+ public Points getPts(Node n) { return _points.get(n); }
+
+
+ // All local allocations that escape
+ public final Points _escapes;
+
+
+ // ---------------------------------
+ // Worklist; iterate to a solution
+ private final WorkList<Node> _work = new WorkList<>();
+ private final WorkList<Node> _escapeWork = new WorkList<>();
+
+ // TypePtr is a mix of TypeMemPtr and TypeFunPtr; disallowed from following
+ // it to the pointed-at memory
+ private static boolean reference(Type type) {
+ if( type.isHigh() ) return false;
+ if( type instanceof TypeMemPtr ) return true;
+ if( type instanceof TypeTuple tt && tt._types.length==3 && tt.ret() instanceof TypeMemPtr ) return true;
+ return false;
+ }
+
+ private static boolean constraint(Node n) {
+ return !n._type.isHigh() && (reference(n._type) || n instanceof CallEndNode ||
+ n instanceof SummaryNode || n instanceof PtrToIntNode ||
+ (n instanceof StoreNode st && reference(st.val()._type)));
+ }
+
+ public PointsTo(CodeGen code) {
+ _code = code;
+ _escapes = new Points();
+ _escapes._unknown = true;
+
+ // Establish the finite object universe before solving any constraints.
+ code._start.walk(n -> {
+ if( n instanceof NewNode ) {
+ // Make new memory, without pointing to it
+ site(n);
+
+ } else if( reference(n._type) ) {
+ // Node n points-to something
+ points(_work.push(n));
+ // ConstantNodes imply some memory was pre-allocated at
+ // start time (unlike NewNodes, which make new every time)
+ if( n instanceof ConstantNode && n._type.isConstant() )
+ getPts(n).merge(site(n));
+
+ } else if( constraint(n) ) {
+ // Includes Calls and Summaries that call external functions
+ // and escape all arguments, even if they do not return a reference.
+ _work.push(n);
+ }
+
+ return null;
+ });
+
+ // Solve the points-to
+ solve();
+ }
+
+ // Solve the points-to
+ private void solve() {
+ Node n;
+ while( (n = _work.pop()) != null )
+ transfer( n );
+ }
+
+ private Points read(Node node, Node dep) {
+ return points(node).addDep(dep);
+ }
+
+ // Transfer functions only update analysis facts, never IR or its worklist.
+ private void transfer(Node n) {
+ switch( n ) {
+ case StoreNode store when store.val()._type instanceof TypeMemPtr -> {
+ Points bases = read(store.ptr(),n), src = read(store.val(),n);
+ for( Site site : bases._sites ) {
+ Points field = site.field(store._alias);
+ if( field!=null )
+ field.merge(src,_work);
+ }
+ if( bases._unknown ) escape(src,n);
+ }
+
+ case CallEndNode cend -> cend(cend);
+ case SummaryNode sum -> {
+ FunNode fun=(FunNode)sum.in(0);
+ escapeCallArgs(sum,firstArgument(fun.sig()),2+fun.sig().nargs(),sum);
+ if( reference(sum._type) ) unknownResult(sum,((TypeTuple)sum._type).ret());
+ }
+ case ReturnNode ret -> {
+ if( reference(ret.expr()._type) ) {
+ Points result = read(ret.expr(),n);
+ points(n).merge(result, _work);
+ if( ret.fun().unknownCallers() ) escape(result,n);
+ }
+ }
+ case ConstantNode con -> { // Constant static memory already handled
+ assert n._type instanceof TypeMemPtr;
+ // Constant non-constants are the default argument from an unknown
+ // caller; means any escaped allocation of the correct type might
+ // come in here
+ if( !n._type.isConstant() && points(n).merge(_escapes.addDep(n),((TypeMemPtr)n._type)._obj) )
+ points(n).changed(_work);
+ }
+
+ case PhiNode phi -> {
+ boolean progress = false;
+ Points dst = points(n);
+ for( int i = 1; i<n.nIns(); i++ ) {
+ if( phi.region().in(i)._type.isHigh() ) continue;
+ if( phi.in(i)._type==Type.NIL ) continue; // null does not point to anything
+ if( phi.in(i)._type.isHigh() ) continue; // Never-exit as a TOP here
+ // Unknown-caller memory carries the escape bound, not a
+ // pointer value. TypeCheck diagnoses other malformed inputs.
+ if( reference(phi.in(i)._type) ) progress |= dst.merge(read(phi.in(i),n));
+ // If getting from the unknown caller, might get all the escapes
+ if( phi instanceof ParmNode && i==1 && phi.region().in(i) instanceof StartNode )
+ progress |= dst.merge(_escapes.addDep(phi),((TypeMemPtr)phi._type)._obj);
+ }
+ if( progress ) dst.changed(_work);
+ }
+
+ case LoadNode load -> {
+ boolean progress = false;
+ Points dst = points(n);
+ Points bases = read(load.ptr(),n);
+ for( Site site : bases._sites ) {
+ Points field = site.field(load._alias);
+ if( field!=null ) progress |= dst.merge(field.addDep(n));
+ }
+ if( bases._unknown )
+ // Loading from an unknown; dst includes all escapees of the correct type
+ progress |= dst.merge(_escapes.addDep(load), ((TypeMemPtr)load._type)._obj );
+ if( progress ) dst.changed(_work);
+ }
+
+ case ProjNode proj -> {
+ switch( proj.in(0) ) {
+ case NewNode nnn -> { assert proj._idx==0; points(n).merge( _sites.get(nnn), _work ); }
+ case CallEndNode cend -> { assert proj._idx==2; points(n).merge(read(cend,n), _work ); }
+ case SummaryNode sum -> { assert proj._idx==2; points(n).merge(read(sum,n),_work); }
+ case StartNode start -> unknownResult(n,n._type);
+ default -> throw Utils.TODO("points-to projection: "+proj.in(0).getClass().getSimpleName());
+ };
+ }
+
+ case ReadOnlyNode ro -> forward(ro);
+ case GuardNode guard -> forward(guard);
+ case ConstructNode con -> forward(con);
+ case InitViewNode view -> forward(view);
+ case ConvertNode conv -> {
+ if( reference(conv.in(1)._type) ) forward(conv);
+ }
+ case ArrayInitNode init -> points(n).merge(read(init.in(2),n),_work);
+ case PtrToIntNode raw -> escape(read(raw.in(1),raw),raw);
+ default ->
+ throw Utils.TODO("transfer: "+n.getClass().getSimpleName());
+ }
+ }
+
+ private void forward(Node n) {
+ if( reference(n.in(1)._type) ) points(n).merge(read(n.in(1),n),_work);
+ }
+
+ private void cend(CallEndNode cend) {
+ CallNode call = cend.call();
+ if( Intrinsic.pure(call) ) return;
+ if( !(call.fptr()._type instanceof TypeFunPtr fp) ) return; // TypeCheck diagnoses bad calls.
+ // Calls unknown functions?
+ boolean unknown = !fp.fidxs().isFinite();
+
+ if( !(cend._type instanceof TypeTuple state) ) return;
+ Type result = state.ret();
+
+ // Can be here for Calls returning non-references, but to escaping functions
+ Points p = reference(result) ? points(cend) : null;
+ boolean progress = false;
+ // Walk target functions
+ for( int fidx=nextTarget(fp.fidxs(),0); fidx>=0; fidx=nextTarget(fp.fidxs(),fidx) ) {
+ FunNode fun = _code._link(fidx);
+ if( fun==null || fun._extern || fun.summary()!=null ) unknown=true;
+ else if( p!=null ) {
+ progress |= p.merge(read(fun.ret(),cend));
+ }
+ }
+
+ if( unknown ) {
+ // Might return some unknown allocation
+ if( p!=null ) unknownResult(cend,result);
+ // All arguments escape as well
+ escapeCallArgs(call,firstArgument(fp),call.nIns()-1,cend);
+ }
+ if( progress ) p.changed(_work);
+ }
+
+ private static int firstArgument(TypeFunPtr sig) {
+ return sig.nargs()>0 && sig.arg(0)==TypePtr.PTR ? 3 : 2;
+ }
+
+ private int nextTarget(TypeSet targets, int after) {
+ return targets.isFinite() ? targets.next(after) : targets.nextKnown(after,_code._linker.len());
+ }
+
+ private void unknownResult(Node n, Type type) {
+ if( type instanceof TypeMemPtr ptr && points(n).merge(_escapes.addDep(n),ptr._obj) )
+ points(n).changed(_work);
+ }
+
+ // Summary inputs end at the signature's last argument; later FunPtrs are
+ // call dependencies, not arguments. Calls end before their target input.
+ private void escapeCallArgs(Node call, int first, int end, Node dep) {
+ for( int i=first; i<end; i++ )
+ if( reference(call.in(i)._type) ) escape(read(call.in(i),dep),dep);
+ }
+
+ private void escape(Points roots, Node dep) {
+ _escapeWork.clear();
+ for( Site site : roots._sites ) _escapeWork.push(site._node);
+ boolean progress=false;
+ Node n;
+ while( (n=_escapeWork.popOnce())!=null ) {
+ Site site=_sites.get(n);
+ progress |= _escapes.merge(site);
+ if( site._byFld==null ) continue;
+ for( Field fld : site.type()._fields ) {
+ Points field=site.field(fld._alias);
+ if( field==null ) continue;
+ // Watch empty fields too: a later Store can extend this graph
+ // after the base site has already entered the escape set.
+ field.addDep(dep);
+ for( Site child : field._sites ) _escapeWork.push(child._node);
+ }
+ }
+ if( progress ) _escapes.changed(_work);
+ }
+
+
+ // ---------------------------------
+ /** Explicit test/debug check before later phases rewrite the graph.
+ * Normal compilation does not pay for this walk. */
+ public boolean verify() {
+ String before = toString();
+ _code._start.walk( n -> {
+ if( constraint(n) ) _work.push(n);
+ return null;
+ });
+ solve();
+
+ return before.equals(toString());
+ }
+
+ // Diagnostic only: unpinned points and global constants have no local CFG.
+ public static FunNode function(Node node) {
+ CFGNode cfg = node instanceof CFGNode c ? c : node.cfg0();
+ return cfg==null ? null : cfg.fun();
+ }
+
+ @Override public String toString() {
+ SB out = new SB("Points-to\n");
+ // All allocation sites
+ for( Site site : _sites.values().stream().sorted(Comparator.comparingInt(Site::nid)).toList() )
+ site.str(out);
+ _escapes.str(out.p("Escapes: "),null);
+ // All Nodes' points-to
+ for( Node n : _points.keySet().stream().sorted(Comparator.comparingInt(n -> n._nid)).toList() )
+ getPts(n).str(out,n);
+
+ return out.toString();
+ }
+}
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 2bf2d62b..8cbe074f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
@@ -46,7 +46,7 @@ public class ConstantNode extends TypeNode {
CodeGen.CODE._phase.ordinal() > CodeGen.Phase.Lower.ordinal() )
return raw(type);
if( type instanceof TypeFunPtr tfp && tfp.isConstant() ) {
- FunNode fun = CodeGen.CODE._link(tfp);
+ FunNode fun = CodeGen.CODE.link(tfp.fidx());
if( fun != null )
return new FunPtrNode(tfp,CodeGen.CODE._start,fun.ret()).init();
// TODO: A singleton FIDX can also emerge after merging and
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/BreakoutTest.java b/chapter33/src/test/java/com/seaofnodes/simple/BreakoutTest.java
index f374d397..fb00b991 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/BreakoutTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/BreakoutTest.java
@@ -1,5 +1,8 @@
package com.seaofnodes.simple;
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -11,6 +14,15 @@ import static org.junit.Assert.*;
// Exercise the actual Simple game and rasterizer in native code, without a window.
public class BreakoutTest {
+ @Test public void testSourceLibraryFunctionPointerLifetime() throws Exception {
+ Path out=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"breakout-source-");
+ String source=Files.readString(Path.of("docs/examples/Breakout.smp"));
+ // Compile the complete game and sys sources. Folding debounce's
+ // action parameter must not reconnect _serve to a dead Return.
+ new CodeGen("src/main/smp",out.toString(),new Ary<>(new String[]{TestC.RELEASE_SYS_DIR}),
+ "Breakout",source,123,true,TypeInteger.BOT).driver(CodeGen.Phase.IterPostOpto);
+ }
+
private static String game() throws Exception {
String source = Files.readString(Path.of("docs/examples/Breakout.smp"));
// Physics/rendering tests supply their own entry point. Input and
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java
index 36ac1477..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 LoopTree TypeCheck 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/PointsToTest.java b/chapter33/src/test/java/com/seaofnodes/simple/PointsToTest.java
new file mode 100644
index 00000000..7af0e390
--- /dev/null
+++ b/chapter33/src/test/java/com/seaofnodes/simple/PointsToTest.java
@@ -0,0 +1,377 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.IdentityHashMap;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/** Allocation-site points-to facts; no allocation decisions or IR rewrites. */
+public class PointsToTest {
+ @Test public void testAnalysisDoesNotChangeIR() {
+ CodeGen code=new CodeGen("""
+ struct Box { u8[] data=new u8[8]; };
+ val _read_noInline={Box b -> b.data#;};
+ return _read_noInline(new Box);
+ """).driver(CodeGen.Phase.LoopTree);
+ var types=new IdentityHashMap<Node,Type>();
+ var inputs=new IdentityHashMap<Node,Node[]>();
+ code._start.walk(n -> { types.put(n,n._type); inputs.put(n,n._inputs.asAry()); return null; });
+ code.allocation();
+ assertTrue(code._allocation._pointsTo.verify());
+ assertTrue(code._iter._work.isEmpty());
+ int[] count={0};
+ code._start.walk(n -> {
+ assertTrue("Analysis must not create IR nodes",types.containsKey(n));
+ assertSame(types.get(n),n._type);
+ assertArrayEquals(inputs.get(n),n._inputs.asAry());
+ count[0]++;
+ return null;
+ });
+ assertEquals(types.size(),count[0]);
+ }
+
+ @Test public void testEscapedCycleAndLateFieldGrowth() {
+ for( long seed : new long[]{1,123,987654321} ) {
+ CodeGen code=new CodeGen("""
+ struct Box { Box? !next=null; u8[]? !data=null; };
+ {Box -> i64} retain="C";
+ {i64 -> u8[]} fetch="C";
+ {
+ val a=new Box; val b=new Box;
+ int n=retain(a);
+ a.next=b; b.next=a;
+ b.data=new u8[arg];
+ return n+fetch(0)#;
+ }
+ """,seed,true).driver(CodeGen.Phase.Allocation);
+ PointsTo a=code._allocation._pointsTo;
+ for( var box : sites(a,"Box") ) {
+ assertTrue(a._escapes.contains(box));
+ for( var child : box.field("next")._sites ) assertTrue(a._escapes.contains(child));
+ if( box.field("data")!=null )
+ for( var data : box.field("data")._sites ) assertTrue(a._escapes.contains(data));
+ }
+ int arrays=0;
+ for( var site : a._sites.values() )
+ if( site._node instanceof NewNode && site.type().isAry() ) {
+ assertTrue(a._escapes.contains(site));
+ arrays++;
+ }
+ assertEquals(1,arrays);
+ assertTrue(a.verify());
+ }
+ }
+
+ @Test public void testRecursivePointerReturn() {
+ PointsTo a=points(THING+"""
+ val _pass_noInline={Thing t,i64 n -> n ? _pass_noInline(t,n-1) : t;};
+ { val t=new Thing(arg); return read_noInline(_pass_noInline(t,arg)); }
+ """);
+ var things=sites(a,"Thing");
+ assertEquals(1,things.size());
+ int calls=0;
+ for( var entry : a._points.entrySet() )
+ if( entry.getKey() instanceof CallEndNode end && "_pass_noInline".equals(end.call().name()) ) {
+ assertFalse(entry.getValue()._unknown);
+ assertTrue(entry.getValue().contains(things.get(0)));
+ calls++;
+ }
+ assertEquals(2,calls);
+ }
+
+ 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 PointsTo points(String source) {
+ CodeGen code=new CodeGen(source).driver(CodeGen.Phase.Allocation);
+ assertTrue(code._allocation._pointsTo.verify());
+ return code._allocation._pointsTo;
+ }
+
+ private static ArrayList<PointsTo.Site> sites(PointsTo analysis, String type) {
+ var sites = new ArrayList<PointsTo.Site>();
+ for( var site : analysis._sites.values() )
+ if( site._node instanceof NewNode &&
+ !com.seaofnodes.simple.type.TypeStruct.startsClzPrefix(site.type()._name) &&
+ site.type()._name.endsWith("."+type) ) {
+ FunNode fun = ((NewNode)site._node).cfg0().fun();
+ // Inspect inlined allocations, excluding the retained constructor body.
+ if( !fun._name.endsWith(".<new>") )
+ sites.add(site);
+ }
+ return sites;
+ }
+
+ @Test public void testPointsToSharedFactory() {
+ PointsTo a = points(THING+"""
+ val make_noInline={i64 x -> new Thing(x);};
+ val first=make_noInline(arg);
+ val second=make_noInline(arg+1);
+ return read_noInline(first)+read_noInline(second);
+ """);
+ var things = sites(a,"Thing");
+ assertEquals("A shared factory has one abstract NewNode, not a copy per call",1,things.size());
+ int[] calls={0};
+ CodeGen.CODE._start.walk(n -> {
+ if( n instanceof CallEndNode cend && "make_noInline".equals(cend.call().name()) ) {
+ assertFalse(a.getPts(cend)._unknown);
+ assertEquals(1,a.getPts(cend)._sites.size());
+ assertTrue(a.getPts(cend).contains(things.get(0)));
+ calls[0]++;
+ }
+ return null;
+ });
+ assertEquals(2,calls[0]);
+ }
+
+ @Test public void testPointsToSeparateObjectsAndWeakStores() {
+ PointsTo a=points(THING+"""
+ struct Box { Thing? !child=null; };
+ val get_noInline = { Box b -> b.child ? read_noInline(b.child) : 0;};
+ val b = new Box;
+ val c = new Box;
+ b.child = new Thing(arg);
+ c.child = new Thing(arg+1);
+ int result=get_noInline(b)+get_noInline(c);
+ b.child = new Thing(arg+2);
+ return result+get_noInline(b);
+ """);
+ var boxes = sites(a,"Box");
+ var things= sites(a,"Thing");
+ assertEquals(2,boxes.size());
+ assertEquals(3,things.size());
+ var b = boxes.get(0).field("child");
+ var c = boxes.get(1).field("child");
+ assertFalse(b._unknown); assertFalse(c._unknown);
+ assertEquals(3,b._sites.size()+c._sites.size());
+ assertTrue("One field remembers both pre- and post-overwrite values",
+ b._sites.size()==2 || c._sites.size()==2);
+ for( var site : b._sites )
+ assertFalse("Fields belong to sites, not the shared TypeStruct",c.contains(site));
+ for( var site : c._sites )
+ assertFalse("Fields belong to sites, not the shared TypeStruct",b.contains(site));
+ for( var thing : things ) {
+ int incoming=0;
+ for( var base : a._sites.values() )
+ if( base._byFld!=null )
+ for( var field : base._byFld )
+ if( field!=null && field.contains(thing) ) incoming++;
+ assertEquals(1,incoming);
+ }
+ }
+
+ @Test public void testPointsToLoopAndPhi() {
+ PointsTo a = points("""
+ struct Cell { Cell? next; i64 x; new Cell = { Cell? n, i64 x -> next=n; self.x=x;}; };
+ val read_noInline = { Cell? c -> c ? c.x : 0;};
+ Cell? !head = null;
+ for(int i=0;i<arg;i++) head = new Cell(head,i);
+ return read_noInline(head);
+ """);
+ var cells = sites(a,"Cell");
+ assertEquals(1,cells.size());
+ var cell = cells.get(0);
+ assertFalse(cell.field("next")._unknown);
+ assertTrue("A summary self edge represents distinct list cells",cell.field("next").contains(cell));
+ for( Node n : a._points.keySet() )
+ if( n instanceof PhiNode && !(n instanceof ParmNode) )
+ assertTrue( a.getPts(n).contains(cell) );
+ }
+
+ @Test public void testPointsToPointerArrays() {
+ PointsTo a=points(THING+"""
+ val readArray_noInline={Thing?[] xs,u32 i -> xs[i] ? read_noInline(xs[i]) : 0;};
+ val xs=new Thing?[2];
+ xs[0]=new Thing(arg);
+ xs[1]=new Thing(arg+1);
+ return readArray_noInline(xs,0)+readArray_noInline(xs,1);
+ """);
+ var things = sites(a,"Thing");
+ assertEquals(2,things.size());
+ int arrays=0;
+ for( var site : a._sites.values() ) {
+ var elements = site.field("[]");
+ if( elements!=null ) {
+ assertFalse(elements._unknown);
+ assertEquals(2,elements._sites.size());
+ for( var thing : things ) assertTrue(elements.contains(thing));
+ arrays++;
+ }
+ }
+ assertEquals(1,arrays);
+ }
+
+ @Test public void testPointsToUnknownBoundary() {
+ PointsTo a = points("""
+ {i64 -> u8[]} native="C";
+ val get_noInline={i64 n -> native(n);};
+ return get_noInline(arg)#;
+ """);
+ int cnt=0;
+ for( Node n : a._points.keySet() )
+ if( n instanceof CallEndNode cend &&
+ "get_noInline".equals(cend.call().name()) ) {
+ assertTrue("An external result is unknown",a.getPts(cend)._unknown);
+ cnt++;
+ }
+ assertEquals(1,cnt);
+ }
+
+ @Test public void testPointsToExternalParameters() {
+ CodeGen code=new CodeGen(null,null,null,"External",
+ THING+"val borrow_noInline = { Thing t -> read_noInline(t); };",
+ 123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ PointsTo a = code._allocation._pointsTo;
+ int cnt = 0;
+ for( Node n : a._points.keySet() )
+ if( n instanceof ParmNode p && p._idx==3 && "borrow_noInline".equals(p.fun()._name) ) {
+ assertTrue("Start's memory input denotes an external pointer, even with no known escaping objects",a.getPts(p)._unknown);
+ cnt++;
+ }
+ assertEquals(1,cnt);
+ assertTrue(a.verify());
+ }
+
+ @Test public void testPointsToImportedSignatureAndRefinedReturn() {
+ var paths = new Ary<>(new String[]{"build/release/"+TestC.CPU_PORT+"_"+TestC.CALL_CONVENTION});
+ CodeGen code = new CodeGen(null,null,paths,"Use","""
+ val main = { u8[~][] args ->
+ val nums = sys.aryi64.parseAryI64(args[0]);
+ val dst = new u8[8];
+ sys.ary.copy(dst,0,args[0],0,1);
+ return nums ? nums.len+dst# : 0;
+ };
+ """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ PointsTo a = code._allocation._pointsTo;
+ boolean[] found={false,false};
+ code._start.walk(n -> {
+ if( n._type.isHigh() ) return null;
+ if( n instanceof CallEndNode end && "sys.aryi64.parseAryI64".equals(end.call().name()) ) {
+ var pts=a.getPts(end);
+ assertNotNull(pts);
+ assertTrue(pts._unknown || !pts._sites.isEmpty());
+ found[0]=true;
+ }
+ if( n instanceof SummaryNode ) found[1]=true;
+ return null;
+ });
+ assertTrue(found[0]); assertTrue(found[1]);
+ assertTrue(a.verify());
+ }
+
+ @Test public void testPointsToImportedParameterConstants() {
+ var paths=new Ary<>(new String[]{"build/release/"+TestC.CPU_PORT+"_"+TestC.CALL_CONVENTION});
+ CodeGen code=new CodeGen(null,null,paths,"Copy","""
+ val main={u8[~][] args ->
+ val dst=new u8[8];
+ sys.ary.copy(dst,0,args[0],0,1);
+ return dst[0];
+ };
+ """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ PointsTo a=code._allocation._pointsTo;
+ int[] receivers={0};
+ code._start.walk(n -> {
+ if( n instanceof ParmNode parm && parm._idx==2 && "sys.ary.copy".equals(parm.fun()._name) ) {
+ // The hidden TypePtr receiver is not a memory reference.
+ assertNull(a.getPts(parm));
+ receivers[0]++;
+ }
+ return null;
+ });
+ assertEquals(1,receivers[0]);
+ assertTrue(a.verify());
+ }
+
+ // A newly escaped byte array must requeue the unknown call's result.
+ @Test public void testPointsToEscapeCallProgress() {
+ CodeGen code=new CodeGen("""
+ {i64 -> u8[]?[]} get="C";
+ {i64 -> u8[]} take="C";
+ { val sink=get(0); sink[0]=new u8[8]; return take(0)#; }
+ """).driver(CodeGen.Phase.Allocation);
+ assertTrue(code._allocation._pointsTo.verify());
+ }
+
+ // The load and its guard likewise need to refire when escapes grow.
+ @Test public void testPointsToEscapeLoadProgress() {
+ CodeGen code=new CodeGen("""
+ struct Sink { u8[]? !a=null; };
+ {i64 -> !Sink} get="C";
+ { val sink=get(0); sink.a=new u8[8];
+ val other=get(1); return other.a ? other.a# : 0; }
+ """).driver(CodeGen.Phase.Allocation);
+ assertTrue(code._allocation._pointsTo.verify());
+ }
+
+ @Test public void testPointsToImportedPointerIdentity() throws Exception {
+ Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs")),"points-import-");
+ new CodeGen(null,lib.toString(),null,"Identity","val echo_noInline={u8[] a -> a;};",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,"UseIdentity","""
+ { val a=new u8[arg]; return Identity.echo_noInline(a)#; }
+ """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ PointsTo a=code._allocation._pointsTo;
+ PointsTo.Site local=null;
+ for( var site : a._sites.values() ) if( site._node instanceof NewNode ) local=site;
+ assertNotNull(local);
+ assertTrue(a._escapes.contains(local));
+ int summaries=0;
+ for( Node n : a._points.keySet() )
+ if( n instanceof SummaryNode ) {
+ assertTrue(a.getPts(n)._unknown);
+ assertTrue("A returned argument remains a possible local target",a.getPts(n).contains(local));
+ summaries++;
+ }
+ assertEquals(1,summaries);
+ assertTrue(a.verify());
+ }
+
+ @Test public void testPointsToOpaqueScalarCallEscapesGraph() {
+ CodeGen code=new CodeGen("""
+ struct Box { u8[] !child=new u8[8]; };
+ {!Box -> i64} native="C";
+ { val b=new Box; return native(b); }
+ """).driver(CodeGen.Phase.Allocation);
+ PointsTo a=code._allocation._pointsTo;
+ int roots=0;
+ for( var box : sites(a,"Box") ) {
+ assertTrue(a._escapes.contains(box));
+ assertNotNull(box.field("child"));
+ assertFalse(box.field("child")._sites.isEmpty());
+ for( var child : box.field("child")._sites ) assertTrue(a._escapes.contains(child));
+ roots++;
+ }
+ assertEquals(1,roots);
+ assertTrue(a.verify());
+ }
+
+ // Return escape growth must requeue unknown-caller constants and parameters.
+ @Test public void testPointsToReturnEscapeProgress() {
+ CodeGen code=new CodeGen(null,null,null,"Progress","""
+ val make_noInline={i64 n -> new u8[n];};
+ val read_noInline={u8[] a -> a#;};
+ """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ assertTrue(code._allocation._pointsTo.verify());
+ }
+
+
+ @Test public void testPointsToReturnEscapeProgressEscapeDraw() {
+ var paths = new Ary<>(new String[]{"build/release/"+TestC.CPU_PORT+"_"+TestC.CALL_CONVENTION});
+ CodeGen code = new CodeGen(null,null,paths,"Use",
+ "val _draw={i64 x -> x+1;}; val main={ -> sys.math.max(1,2);};",
+ 123,true,TypeInteger.BOT).driver(CodeGen.Phase.Allocation);
+ assertTrue(code._allocation._pointsTo.verify());
+ }
+}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Simple.java b/chapter33/src/test/java/com/seaofnodes/simple/Simple.java
index 78b1e76d..25bb1287 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Simple.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Simple.java
@@ -50,6 +50,7 @@ Options:
--dump-after-opto - dump intermediate representation after SCCP
--dump-after-iter-post-opto - dump after SCCP-driven peepholes and inlining
--dump-after-finalize-ir - dump after field layout and IR finalization
+ --dump-after-allocation - dump points-to facts; allocation is analysis-only
--dump-after-type-check - dump intermediate representation after type check pass
--dump-after-lower - dump expanded class initialization before loop trees
--dump-after-select - dump intermediate representation after instruction selection pass
@@ -138,6 +139,7 @@ Options:
case "--dump-after-type-check": dump |= 1<<Phase.TypeCheck .ordinal() ; break;
case "--dump-after-lower": dump |= 1<<Phase.Lower .ordinal() ; break;
case "--dump-after-loop-tree": dump |= 1<<Phase.LoopTree .ordinal() ; break;
+ case "--dump-after-allocation": dump |= 1<<Phase.Allocation.ordinal() ; break;
case "--dump-after-select": dump |= 1<<Phase.Select .ordinal() ; break;
case "--dump-after-gcm": dump |= 1<<Phase.Schedule .ordinal() ; break;
case "--dump-after-local-sched": dump |= 1<<Phase.LocalSched.ordinal() ; break;