summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--chapter05/README.md15
-rw-r--r--chapter05/src/main/java/com/seaofnodes/simple/node/PhiNode.java34
-rw-r--r--chapter05/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter06/src/main/java/com/seaofnodes/simple/node/PhiNode.java34
-rw-r--r--chapter06/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter07/src/main/java/com/seaofnodes/simple/node/PhiNode.java34
-rw-r--r--chapter07/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter08/src/main/java/com/seaofnodes/simple/node/PhiNode.java34
-rw-r--r--chapter08/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter09/src/main/java/com/seaofnodes/simple/node/PhiNode.java34
-rw-r--r--chapter09/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter10/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter10/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter11/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter11/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter12/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter12/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter13/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter13/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter14/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter14/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter15/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter15/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter16/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter16/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter17a/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter17a/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter17b/src/main/java/com/seaofnodes/simple/node/PhiNode.java37
-rw-r--r--chapter17b/src/test/java/com/seaofnodes/simple/Chapter05Test.java23
-rw-r--r--chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java36
-rw-r--r--chapter18/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter18/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter19/src/main/java/com/seaofnodes/simple/node/PhiNode.java36
-rw-r--r--chapter19/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter19/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter20/src/main/java/com/seaofnodes/simple/node/PhiNode.java36
-rw-r--r--chapter20/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter20/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter21/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter21/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter21/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter21/src/test/java/com/seaofnodes/simple/Chapter21Test.java3
-rw-r--r--chapter22/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter22/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter22/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter23/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter23/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter23/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter24a/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter24a/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter24a/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter24b/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter24b/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter24b/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter25/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter25/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter25/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter26/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter26/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter26/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter27/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter27/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter27/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter28a/README.md46
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/Parser.java101
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java11
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java2
-rw-r--r--chapter28a/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter28a/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter28a/src/test/java/com/seaofnodes/simple/Chapter20Test.java6
-rw-r--r--chapter28a/src/test/java/com/seaofnodes/simple/Chapter21Test.java8
-rw-r--r--chapter28a/src/test/java/com/seaofnodes/simple/Chapter22Test.java6
-rw-r--r--chapter28a/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java71
-rw-r--r--chapter28a/src/test/java/com/seaofnodes/simple/ReceiverTest.java93
-rw-r--r--chapter28b/README.md9
-rw-r--r--chapter28b/src/main/java/com/seaofnodes/simple/Parser.java101
-rw-r--r--chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java11
-rw-r--r--chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java2
-rw-r--r--chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java11
-rw-r--r--chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java6
-rw-r--r--chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java8
-rw-r--r--chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java6
-rw-r--r--chapter28b/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java71
-rw-r--r--chapter28b/src/test/java/com/seaofnodes/simple/ReceiverTest.java94
-rw-r--r--chapter29/README.md3
-rw-r--r--chapter29/docs/29-grammar.md9
-rw-r--r--chapter29/src/main/java/com/seaofnodes/simple/node/CallNode.java11
-rw-r--r--chapter29/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter29/src/main/java/com/seaofnodes/simple/node/RegionNode.java2
-rw-r--r--chapter29/src/main/java/com/seaofnodes/simple/node/SummaryNode.java11
-rw-r--r--chapter29/src/main/java/com/seaofnodes/simple/parser/Expressions.java3
-rw-r--r--chapter29/src/main/java/com/seaofnodes/simple/parser/Functions.java16
-rw-r--r--chapter29/src/main/java/com/seaofnodes/simple/parser/References.java60
-rw-r--r--chapter29/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter29/src/test/java/com/seaofnodes/simple/Chapter09Test.java2
-rw-r--r--chapter29/src/test/java/com/seaofnodes/simple/Chapter20Test.java6
-rw-r--r--chapter29/src/test/java/com/seaofnodes/simple/Chapter21Test.java8
-rw-r--r--chapter29/src/test/java/com/seaofnodes/simple/Chapter22Test.java6
-rw-r--r--chapter29/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java71
-rw-r--r--chapter29/src/test/java/com/seaofnodes/simple/ReceiverTest.java94
-rw-r--r--chapter30/README.md3
-rw-r--r--chapter30/docs/30-grammar.md9
-rw-r--r--chapter30/src/main/java/com/seaofnodes/simple/node/CallNode.java11
-rw-r--r--chapter30/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter30/src/main/java/com/seaofnodes/simple/node/RegionNode.java2
-rw-r--r--chapter30/src/main/java/com/seaofnodes/simple/node/SummaryNode.java11
-rw-r--r--chapter30/src/main/java/com/seaofnodes/simple/parser/Expressions.java3
-rw-r--r--chapter30/src/main/java/com/seaofnodes/simple/parser/Functions.java16
-rw-r--r--chapter30/src/main/java/com/seaofnodes/simple/parser/References.java60
-rw-r--r--chapter30/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter30/src/test/java/com/seaofnodes/simple/Chapter20Test.java4
-rw-r--r--chapter30/src/test/java/com/seaofnodes/simple/Chapter21Test.java6
-rw-r--r--chapter30/src/test/java/com/seaofnodes/simple/Chapter22Test.java6
-rw-r--r--chapter30/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java71
-rw-r--r--chapter30/src/test/java/com/seaofnodes/simple/ReceiverTest.java94
-rw-r--r--chapter31/Makefile4
-rw-r--r--chapter31/README.md3
-rw-r--r--chapter31/docs/31-grammar.md9
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java11
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/PhiNode.java38
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/RegionNode.java2
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/node/SummaryNode.java11
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java3
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java14
-rw-r--r--chapter31/src/main/java/com/seaofnodes/simple/parser/References.java55
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/Chapter05Test.java24
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/Chapter20Test.java4
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/Chapter21Test.java7
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/Chapter22Test.java6
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/Chapter23Test.java2
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java71
-rw-r--r--chapter31/src/test/java/com/seaofnodes/simple/ReceiverTest.java93
-rw-r--r--chapter32/Makefile31
-rw-r--r--chapter32/README.ja.md6
-rw-r--r--chapter32/README.md381
-rw-r--r--chapter32/docs/32-grammar.md10
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/codegen/IFG.java96
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java7
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/codegen/Serialize.java23
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java15
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java21
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java39
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java3
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java11
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java7
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java3
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java14
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/parser/References.java55
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java5
-rw-r--r--chapter32/src/main/java/com/seaofnodes/simple/util/BAOS.java45
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java28
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/BAOSTest.java58
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java35
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java4
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java11
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java6
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java71
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/MemMergeTest.java5
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/ModTest.java27
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java93
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java36
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/StringFormatTest.java113
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/TestWorkspace.java2
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/TypeTest.java81
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java6
-rw-r--r--chapter32/src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java20
-rw-r--r--skills/chapter25-codex-notes.md25
171 files changed, 3975 insertions, 829 deletions
diff --git a/chapter05/README.md b/chapter05/README.md
index 40886af2..0955f36a 100644
--- a/chapter05/README.md
+++ b/chapter05/README.md
@@ -413,6 +413,21 @@ return a;
+### Factoring after strength reduction
+
+Peephole order should not hide the same arithmetic from Phi factoring.
+`Phi(x+x,y+x)` can become `Phi(x,y)+x`, but an earlier peephole may already have
+replaced `x+x` with `x*2`. The Phi matcher therefore views `x*2` as two copies of
+`x` while factoring mixed Add/Mul arms. It does not expand the graph into an Add
+that would immediately fold back to a multiply. If all arms are multiplies,
+ordinary multiply factoring still applies.
+
+[Chapter05Test](src/test/java/com/seaofnodes/simple/Chapter05Test.java)
+checks the factored operands before and after strength reduction and with either
+arm order. Later chapters extend this same view to `x<<1` when shifts arrive.
+The rule stays local to doubling; arbitrary coefficients would require creating
+another multiplication, with a less clear benefit.
+
[^1]: Click, C. (1995).
Combining Analyses, Combining Optimizations, 132.
diff --git a/chapter05/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter05/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index da3917c7..0db72880 100644
--- a/chapter05/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter05/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
public class PhiNode extends Node {
@@ -40,14 +41,14 @@ public class PhiNode extends Node {
// Phi, but Phis do not make code.
// Phi(op(A,B),op(Q,R),op(X,Y)) becomes
// op(Phi(A,Q,X), Phi(B,R,Y)).
- Node op = in(1);
- if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op() ) {
+ Node op = factoringOp();
+ if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op(op) ) {
Node[] lhss = new Node[nIns()];
Node[] rhss = new Node[nIns()];
lhss[0] = rhss[0] = in(0); // Set Region
for( int i=1; i<nIns(); i++ ) {
- lhss[i] = in(i).in(1);
- rhss[i] = in(i).in(2);
+ lhss[i] = factoringInput(op,in(i),1);
+ rhss[i] = factoringInput(op,in(i),2);
}
Node phi_lhs = new PhiNode(_label,lhss).peephole();
Node phi_rhs = new PhiNode(_label,rhss).peephole();
@@ -57,9 +58,28 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
- for( int i=2; i<nIns(); i++ )
- if( in(1).getClass() != in(i).getClass() )
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
+ for( int i=1; i<nIns(); i++ )
+ if( op.getClass()!=in(i).getClass() && !(op instanceof AddNode && doubled(in(i))) )
return false;
return true;
}
diff --git a/chapter05/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter05/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index d6c91a4a..282215f1 100644
--- a/chapter05/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter05/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -222,4 +222,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter06/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter06/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 6acb5535..ff7d5cf7 100644
--- a/chapter06/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter06/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
public class PhiNode extends Node {
@@ -41,14 +42,14 @@ public class PhiNode extends Node {
// Phi, but Phis do not make code.
// Phi(op(A,B),op(Q,R),op(X,Y)) becomes
// op(Phi(A,Q,X), Phi(B,R,Y)).
- Node op = in(1);
- if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op() ) {
+ Node op = factoringOp();
+ if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op(op) ) {
Node[] lhss = new Node[nIns()];
Node[] rhss = new Node[nIns()];
lhss[0] = rhss[0] = in(0); // Set Region
for( int i=1; i<nIns(); i++ ) {
- lhss[i] = in(i).in(1);
- rhss[i] = in(i).in(2);
+ lhss[i] = factoringInput(op,in(i),1);
+ rhss[i] = factoringInput(op,in(i),2);
}
Node phi_lhs = new PhiNode(_label,lhss).peephole();
Node phi_rhs = new PhiNode(_label,rhss).peephole();
@@ -58,9 +59,28 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
- for( int i=2; i<nIns(); i++ )
- if( in(1).getClass() != in(i).getClass() )
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
+ for( int i=1; i<nIns(); i++ )
+ if( op.getClass()!=in(i).getClass() && !(op instanceof AddNode && doubled(in(i))) )
return false;
return true;
}
diff --git a/chapter06/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter06/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index d6c91a4a..282215f1 100644
--- a/chapter06/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter06/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -222,4 +222,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter07/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter07/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 64cd3dd7..2f94e486 100644
--- a/chapter07/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter07/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
public class PhiNode extends Node {
@@ -49,14 +50,14 @@ public class PhiNode extends Node {
// Phi, but Phis do not make code.
// Phi(op(A,B),op(Q,R),op(X,Y)) becomes
// op(Phi(A,Q,X), Phi(B,R,Y)).
- Node op = in(1);
- if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op() ) {
+ Node op = factoringOp();
+ if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op(op) ) {
Node[] lhss = new Node[nIns()];
Node[] rhss = new Node[nIns()];
lhss[0] = rhss[0] = in(0); // Set Region
for( int i=1; i<nIns(); i++ ) {
- lhss[i] = in(i).in(1);
- rhss[i] = in(i).in(2);
+ lhss[i] = factoringInput(op,in(i),1);
+ rhss[i] = factoringInput(op,in(i),2);
}
Node phi_lhs = new PhiNode(_label,lhss).peephole();
Node phi_rhs = new PhiNode(_label,rhss).peephole();
@@ -66,9 +67,28 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
- for( int i=2; i<nIns(); i++ )
- if( in(1).getClass() != in(i).getClass() )
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
+ for( int i=1; i<nIns(); i++ )
+ if( op.getClass()!=in(i).getClass() && !(op instanceof AddNode && doubled(in(i))) )
return false;
return true;
}
diff --git a/chapter07/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter07/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index d6c91a4a..282215f1 100644
--- a/chapter07/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter07/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -222,4 +222,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter08/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter08/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 14622140..5f8b0251 100644
--- a/chapter08/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter08/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
public class PhiNode extends Node {
@@ -49,14 +50,14 @@ public class PhiNode extends Node {
// Phi, but Phis do not make code.
// Phi(op(A,B),op(Q,R),op(X,Y)) becomes
// op(Phi(A,Q,X), Phi(B,R,Y)).
- Node op = in(1);
- if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op() ) {
+ Node op = factoringOp();
+ if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op(op) ) {
Node[] lhss = new Node[nIns()];
Node[] rhss = new Node[nIns()];
lhss[0] = rhss[0] = in(0); // Set Region
for( int i=1; i<nIns(); i++ ) {
- lhss[i] = in(i).in(1);
- rhss[i] = in(i).in(2);
+ lhss[i] = factoringInput(op,in(i),1);
+ rhss[i] = factoringInput(op,in(i),2);
}
Node phi_lhs = new PhiNode(_label,lhss).peephole();
Node phi_rhs = new PhiNode(_label,rhss).peephole();
@@ -66,9 +67,28 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
- for( int i=2; i<nIns(); i++ )
- if( in(1).getClass() != in(i).getClass() )
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
+ for( int i=1; i<nIns(); i++ )
+ if( op.getClass()!=in(i).getClass() && !(op instanceof AddNode && doubled(in(i))) )
return false;
return true;
}
diff --git a/chapter08/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter08/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index fa9a5e37..5fbffd41 100644
--- a/chapter08/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter08/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -224,4 +224,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter09/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter09/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index fe6231fa..1612b860 100644
--- a/chapter09/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter09/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
public class PhiNode extends Node {
@@ -55,14 +56,14 @@ public class PhiNode extends Node {
// Phi, but Phis do not make code.
// Phi(op(A,B),op(Q,R),op(X,Y)) becomes
// op(Phi(A,Q,X), Phi(B,R,Y)).
- Node op = in(1);
- if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op() ) {
+ Node op = factoringOp();
+ if( op.nIns()==3 && op.in(0)==null && !op.isCFG() && same_op(op) ) {
Node[] lhss = new Node[nIns()];
Node[] rhss = new Node[nIns()];
lhss[0] = rhss[0] = in(0); // Set Region
for( int i=1; i<nIns(); i++ ) {
- lhss[i] = in(i).in(1);
- rhss[i] = in(i).in(2);
+ lhss[i] = factoringInput(op,in(i),1);
+ rhss[i] = factoringInput(op,in(i),2);
}
Node phi_lhs = new PhiNode(_label,lhss).peephole();
Node phi_rhs = new PhiNode(_label,rhss).peephole();
@@ -72,9 +73,28 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
- for( int i=2; i<nIns(); i++ )
- if( in(1).getClass() != in(i).getClass() )
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
+ for( int i=1; i<nIns(); i++ )
+ if( op.getClass()!=in(i).getClass() && !(op instanceof AddNode && doubled(in(i))) )
return false;
return true;
}
diff --git a/chapter09/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter09/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 2c869033..a0037792 100644
--- a/chapter09/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter09/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter10/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter10/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 24a72aa4..fafedcef 100644
--- a/chapter10/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter10/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -63,7 +64,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -92,15 +94,34 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op.isCFG() || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode ) return false;
Node busy = null;
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -118,21 +139,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = new PhiNode(_label,t.glb(),ins);
diff --git a/chapter10/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter10/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index cf7bd6cf..55eb08d6 100644
--- a/chapter10/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter10/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter11/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter11/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 6995cc2f..952faf68 100644
--- a/chapter11/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter11/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -67,7 +68,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -96,8 +98,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op.isCFG() || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -115,7 +135,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -133,21 +154,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter11/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter11/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index cf7bd6cf..55eb08d6 100644
--- a/chapter11/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter11/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter12/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter12/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 6995cc2f..952faf68 100644
--- a/chapter12/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter12/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -67,7 +68,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -96,8 +98,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op.isCFG() || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -115,7 +135,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -133,21 +154,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter12/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter12/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 97cd9940..466cd119 100644
--- a/chapter12/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter12/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new ProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter13/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter13/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 8dfa04cf..29de3536 100644
--- a/chapter13/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter13/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -66,7 +67,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -95,8 +97,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof MulNode &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==2;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op.isCFG() || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -114,7 +134,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -132,21 +153,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter13/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter13/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index cd646126..42c22ee2 100644
--- a/chapter13/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter13/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new CProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter14/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter14/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 309cd8b5..2a481c52 100644
--- a/chapter14/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter14/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -66,7 +67,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -95,8 +97,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 and x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return (n instanceof MulNode || n instanceof ShlNode) &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==(n instanceof MulNode ? 2 : 1);
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op.isCFG() || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -114,7 +134,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -132,21 +153,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter14/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter14/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index cd646126..42c22ee2 100644
--- a/chapter14/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter14/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new CProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter15/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter15/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index ea5eeb89..815847fe 100644
--- a/chapter15/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter15/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -66,7 +67,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -95,8 +97,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 and x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return (n instanceof MulNode || n instanceof ShlNode) &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==(n instanceof MulNode ? 2 : 1);
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -114,7 +134,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -132,21 +153,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter15/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter15/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index cd646126..42c22ee2 100644
--- a/chapter15/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter15/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new CProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter16/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter16/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 8479b4dc..17fe6cef 100644
--- a/chapter16/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter16/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -66,7 +67,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -95,8 +97,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 and x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return (n instanceof MulNode || n instanceof ShlNode) &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==(n instanceof MulNode ? 2 : 1);
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -114,7 +134,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -132,21 +153,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter16/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter16/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index cd646126..42c22ee2 100644
--- a/chapter16/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter16/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -225,4 +225,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new CProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter17a/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter17a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 942748e7..836722d8 100644
--- a/chapter17a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter17a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -66,7 +67,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -95,8 +97,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 and x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return (n instanceof MulNode || n instanceof ShlNode) &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==(n instanceof MulNode ? 2 : 1);
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -114,7 +134,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -132,21 +153,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter17a/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter17a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 7ea75f49..f0b37a53 100644
--- a/chapter17a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter17a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -224,4 +224,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new CProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter17b/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter17b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 942748e7..836722d8 100644
--- a/chapter17b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter17b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -3,6 +3,7 @@ package com.seaofnodes.simple.node;
import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.Utils;
@@ -66,7 +67,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -95,8 +97,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 and x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return (n instanceof MulNode || n instanceof ShlNode) &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==(n instanceof MulNode ? 2 : 1);
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -114,7 +134,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -132,21 +153,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter17b/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter17b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 7ea75f49..f0b37a53 100644
--- a/chapter17b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter17b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -224,4 +224,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ new Parser("");
+ Node ctrl = init(new CProjNode(Parser.START,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 9b5e1c26..012b6498 100644
--- a/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter18/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -72,7 +72,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -103,8 +104,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x*2 and x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return (n instanceof MulNode || n instanceof ShlNode) &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==(n instanceof MulNode ? 2 : 1);
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -122,7 +141,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -140,21 +160,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter18/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter18/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index e88474a4..03604584 100644
--- a/chapter18/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter18/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -1,6 +1,7 @@
package com.seaofnodes.simple;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -225,4 +226,27 @@ return a;
}
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("return 0;").parse();
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(new Node[]{null,ctrl,ctrl}));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new MulNode(p,init(new ConstantNode(TypeInteger.constant(2))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter18/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter18/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index d6ced4e0..8b8f8156 100644
--- a/chapter18/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter18/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -40,7 +40,7 @@ else {
return x;
""");
code.parse().iter();
- assertEquals("return Phi(Region,(arg*2),(Mul+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg*2)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter19/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter19/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 6fb315b4..e8a37a4d 100644
--- a/chapter19/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter19/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -74,7 +74,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -105,8 +106,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -124,7 +143,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -142,21 +162,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter19/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter19/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 09e7f7c7..338b26dc 100644
--- a/chapter19/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter19/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -1,6 +1,7 @@
package com.seaofnodes.simple;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -197,4 +198,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter19/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter19/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 5672d566..a5620e13 100644
--- a/chapter19/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter19/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -40,7 +40,7 @@ else {
return x;
""");
code.parse().iter();
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter20/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter20/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index a752977b..e858a21c 100644
--- a/chapter20/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter20/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -78,7 +78,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -109,8 +110,26 @@ public class PhiNode extends Node {
return null;
}
- private boolean same_op() {
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ n.in(2).addDep(this)._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -128,7 +147,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( region().in(i).addDep(this)._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -146,21 +166,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter20/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter20/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 44493d87..8a771349 100644
--- a/chapter20/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter20/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter20/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter20/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 0a3049e6..be8e125a 100644
--- a/chapter20/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter20/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.parse().iter();
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter21/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter21/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index e075ea5c..45d5f1ae 100644
--- a/chapter21/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter21/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -78,7 +78,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -109,10 +110,28 @@ public class PhiNode extends Node {
return null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -130,7 +149,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -148,21 +168,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter21/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter21/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index c809f72f..47690beb 100644
--- a/chapter21/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter21/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter21/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter21/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 0a3049e6..be8e125a 100644
--- a/chapter21/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter21/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.parse().iter();
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter21/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter21/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index b19d1bb5..bba96016 100644
--- a/chapter21/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter21/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -380,7 +380,8 @@ public class Chapter21Test {
// Evaluate on RISC5 emulator; expect return of an array of primes in
// the simulated heap.
- EvalRisc5 R5 = TestRisc5.build("sieve", 100, 92, false);
+ // Phi factoring changes split placement in this chapter's allocator.
+ EvalRisc5 R5 = TestRisc5.build("sieve", 100, 164, false);
int trap = R5.step(10000);
assertEquals(0,trap);
// Return register A0 holds sieve(100)
diff --git a/chapter22/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter22/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 8aa123f7..7438f417 100644
--- a/chapter22/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter22/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -78,7 +78,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -109,10 +110,28 @@ public class PhiNode extends Node {
return null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -130,7 +149,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -148,21 +168,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
PhiNode phi = j==1 && op instanceof MemOpNode mem
diff --git a/chapter22/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter22/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 8168594a..31e77b49 100644
--- a/chapter22/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter22/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter22/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter22/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index df590448..85529d63 100644
--- a/chapter22/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter22/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.parse().iter().finalizeIR();
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter23/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter23/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index af5d900b..424f9d20 100644
--- a/chapter23/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter23/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -106,7 +106,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -137,10 +138,28 @@ public class PhiNode extends Node {
return null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -158,7 +177,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -176,21 +196,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Not accepts both pointers and integers, but a Phi cannot mix them.
diff --git a/chapter23/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter23/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 8168594a..31e77b49 100644
--- a/chapter23/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter23/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter23/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter23/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 3a4415d9..b60e2462 100644
--- a/chapter23/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter23/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.parse().iter().finalizeIR();
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter24a/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter24a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 953e009e..f63efa24 100644
--- a/chapter24a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter24a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -129,7 +129,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -161,10 +162,28 @@ public class PhiNode extends Node {
return null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -182,7 +201,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -200,21 +220,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Not accepts both pointers and integers, but a Phi cannot mix them.
diff --git a/chapter24a/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter24a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index b234209f..5c6bdf85 100644
--- a/chapter24a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter24a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter24a/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter24a/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index f24d96eb..bfa4d776 100644
--- a/chapter24a/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter24a/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter24b/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter24b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 7f2bb1f4..70bb5877 100644
--- a/chapter24b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter24b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -130,7 +130,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
// If merging Phi(N, cast(N)) - we are losing the cast JOIN effects, so just remove.
if( nIns()==3 ) {
@@ -162,10 +163,28 @@ public class PhiNode extends Node {
return null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -183,7 +202,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -201,21 +221,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Not accepts both pointers and integers, but a Phi cannot mix them.
diff --git a/chapter24b/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter24b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index b234209f..5c6bdf85 100644
--- a/chapter24b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter24b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p));
+ Node sum = init(new AddNode(i,p));
+ PhiNode phi = init(new PhiNode("sum",TypeInteger.BOT,region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter24b/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter24b/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index f24d96eb..bfa4d776 100644
--- a/chapter24b/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter24b/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter25/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter25/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 064852e4..9f800e2f 100644
--- a/chapter25/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter25/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -107,7 +107,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
if( nIns()==3 ) {
Node merge = matchingGuardMerge(r,1);
@@ -165,10 +166,28 @@ public class PhiNode extends Node {
return tested!=null && ScopeNode.availableAt(n,r,new java.util.BitSet()) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -186,7 +205,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -204,21 +224,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Not accepts both pointers and integers, but a Phi cannot mix them.
diff --git a/chapter25/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter25/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index b234209f..460db1b1 100644
--- a/chapter25/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter25/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter25/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter25/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 50410618..6e167d9e 100644
--- a/chapter25/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter25/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter26/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter26/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 064852e4..9f800e2f 100644
--- a/chapter26/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter26/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -107,7 +107,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
if( nIns()==3 ) {
Node merge = matchingGuardMerge(r,1);
@@ -165,10 +166,28 @@ public class PhiNode extends Node {
return tested!=null && ScopeNode.availableAt(n,r,new java.util.BitSet()) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -186,7 +205,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -204,21 +224,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Not accepts both pointers and integers, but a Phi cannot mix them.
diff --git a/chapter26/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter26/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index b234209f..460db1b1 100644
--- a/chapter26/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter26/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter26/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter26/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index f24d96eb..bfa4d776 100644
--- a/chapter26/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter26/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter27/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter27/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 064852e4..9f800e2f 100644
--- a/chapter27/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter27/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -107,7 +107,8 @@ public class PhiNode extends Node {
// Phi(op(a,b,...),op(c,d,...)) -> op(Phi(a,c),Phi(b,d),...).
Node down;
- if( same_op() && (down=drop_same_op())!=null ) return down;
+ Node op = factoringOp();
+ if( same_op(op) && (down=drop_same_op(op))!=null ) return down;
if( nIns()==3 ) {
Node merge = matchingGuardMerge(r,1);
@@ -165,10 +166,28 @@ public class PhiNode extends Node {
return tested!=null && ScopeNode.availableAt(n,r,new java.util.BitSet()) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -186,7 +205,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -204,21 +224,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Not accepts both pointers and integers, but a Phi cannot mix them.
diff --git a/chapter27/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter27/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index b234209f..460db1b1 100644
--- a/chapter27/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter27/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -198,4 +199,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = init(new ConstantNode(TypeInteger.BOT));
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,init(new ConstantNode(TypeInteger.constant(1))))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter27/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter27/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index f24d96eb..bfa4d776 100644
--- a/chapter27/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter27/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter28a/README.md b/chapter28a/README.md
index 2f127e19..d61d642c 100644
--- a/chapter28a/README.md
+++ b/chapter28a/README.md
@@ -23,6 +23,52 @@ This chapter adds file and class semantics to the escape analysis we already
have. All required Simple source is available in one compilation.
+## Globals use the same receiver as fields
+
+Every function has a source-visible `self`. An instance method receives its
+instance; a global function receives its defining file's class singleton.
+For example:
+
+```simple
+int f0=7;
+int f1=0;
+val touch={int n -> f1=n; return f0+f1;};
+```
+
+The function body means `self.f1=n; return self.f0+self.f1;`. Once the class is
+initialized, `touch(5)` returns 12. Bare reads, assignments, and compound updates
+all resolve the field's receiver and use the same field-access path. A bare
+assignment must emit a Store, rather than updating only a lexical Scope slot.
+Locals and explicit parameters still shadow fields; an explicitly declared
+parameter named `self` shadows the implicit receiver.
+
+The [parser](src/main/java/com/seaofnodes/simple/Parser.java) supplies a receiver
+parameter instead of manufacturing a class constant for each global read.
+Normal constant folding removes that parameter for class functions. Its function
+signature retains `TypePtr.PTR`, the marker for a hidden receiver with no native
+argument slot, so ordinary C callers and callbacks retain their ABI.
+[CallNode](src/main/java/com/seaofnodes/simple/node/CallNode.java) binds that slot
+to the callee's declared class view even when another class forwards the callback
+or an instance stores its function pointer. An instance method can also name its
+enclosing class's fields through that declaration's receiver. This does not add
+closures or bound method values.
+
+The class view keeps fields discovered so far and remains open until SCCP
+installs the completed shape. This matters for forward functions and for globals
+declared after a struct. Class declarations still accumulate Scope values until
+initializer exit; this chapter also retains its existing Scope-based instance
+constructor handling. Active field uses retain their class-initialization checks.
+Passing the hidden class receiver does not itself publish the caller's class to
+unknown code; actual escaping fields are tracked normally.
+
+[GlobalAssignmentTest](src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java)
+checks assignments, branches, chained updates, RHS effects, local shadowing,
+conversions, constructors, and rejected stores.
+[ReceiverTest](src/test/java/com/seaofnodes/simple/ReceiverTest.java) checks explicit
+class `self`, nested functions, instance/global name collisions, forward fields,
+and native argument/callback ABI behavior. Chapter 28b extends this to imported
+functions and summaries.
+
## Example: Lazy class initialization, or Pay-As-You-Go
Suppose an application sometimes needs a `Table` but not often; many runs may
diff --git a/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java b/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java
index 3b5a8ce7..fd9d9753 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/Parser.java
@@ -290,8 +290,16 @@ public class Parser {
// All args, "as-if" called externally
for( int i=0; i<ids.length; i++ ) {
Type t = sig.arg(i);
+ // The body sees its owning class receiver. PTR remains in the
+ // signature as the ABI marker for a receiver with no machine slot.
+ if( i==0 && t==TypePtr.PTR ) {
+ TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj;
+ // A file can add globals after its struct declaration closes.
+ // Keep this view open until SCCP installs the completed class.
+ t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true);
+ }
// Args take a default input if called from Start/external-world
- _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole(), loc);
+ _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(i==0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i)).peephole()).peephole(), loc);
}
if( isCtor && !isInit ) {
@@ -1075,6 +1083,10 @@ public class Parser {
throw error("Cannot reassign final '"+name+"'");
checkSharedFunction(def);
+ // All fields use the same receiver-based lvalue path.
+ if( fieldSelf(def)!=null )
+ { pos(old); return parseExpression(); }
+
// Parse assignment expression
Node expr = parseAsgn();
@@ -1084,27 +1096,6 @@ public class Parser {
// Update
_scope.update(name,lift);
- // Check for storing into an instance field instead of a local var
- int kx = _scope.kindx(def); // Declaration scope
- int fx = _scope.enclosingFunction(); // Enclosing function scope
- Kind kk = _scope._kinds.at(kx);
- Kind fk = _scope._kinds.at(fx);
- // Access instance field from 'self'
- if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) &&
- fk instanceof Kind.Func method && !inExplicitConstructor() ) {
- // Named field offset on an unknown struct type
- TypeMemPtr self = (TypeMemPtr)_scope.var(fk._lexSize).type();
- TypeStruct sobj = (TypeStruct)TYPES.get(self._obj._name);
- Field fld = sobj.field(name);
- int alias = fld._alias;
- Node ptr = _scope.in(method._lexSize);
- Node off = fldoff(ptr,name);
- Node prior = mem().keep();
- Node st = new StoreNode(loc(), name, alias, decl, ctrl(), prior, ptr, off, lift, inExplicitConstructor()).peephole().keep();
- storeMem(st,alias,prior);
- st.unkeep();
- prior.unkeep();
- }
lift.unkill();
@@ -2099,35 +2090,12 @@ public class Parser {
if( inExplicitConstructor() && var._uninit && missingInit(rvalue,new BitSet()) )
throw error("Field '"+id+"' might not be initialized",var._loc);
- // Check for an instance field load
- int kx = _scope.kindx(var); // Declaration scope
- int fx = _scope.enclosingFunction(); // Enclosing function scope
- Kind kk = _scope._kinds.at(kx);
- Kind fk = _scope._kinds.at(fx);
- // Access instance field from 'self'
- if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) && fk instanceof Kind.Func method && !inExplicitConstructor() )
- return parsePostfixName(_scope.in(method._lexSize),id,pre);
-
- // Check for a function-escaping variable; these require true
- // closures. Final constants are OK; final vars require a hidden var
- // argument; not-final fields can just use an explicit struct arg.
- if( kx < fx && !inExplicitConstructor() && // Out of scope
- !(var._final && rvalue._type.isConstant()) ) { // Not a final constant
- if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke)
- throw error("Variable '"+var._name+"' is out of function scope and must be a final constant");
-
- // var.idx==2 is self argument, 3 is args, 4 or more are now static globals
- if( var._idx >= 4 ) {
- // Read from global scope.
- // Surely a nicer way to get the top-level scope compile name?
- Var clzptr = _scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parsePostfixName( con( clztmp ), id,pre );
- //return parsePostfixName(_scope.in(2),id);
- }
- }
+ Node self = fieldSelf(var);
+ if( self!=null ) return parsePostfixName(self,id,pre);
+ int kx = _scope.kindx(var), fx = _scope.enclosingFunction();
+ if( kx>0 && kx<fx && !inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw error("Variable '"+var._name+"' is out of function scope and must be a final constant");
// Check for assign-update, x += e0;
char ch = pre==0 ? _lexer.matchOperAssign() : (char)pre;
@@ -2372,6 +2340,31 @@ public class Parser {
return parsePostfixMethod(value,defaultSelf());
}
+ // Find the receiver for a field lvalue. Initializers retain Scope values;
+ // class declarations retain their Scope values until initializer exit.
+ private Node fieldSelf(Var var) {
+ int kx = _scope.kindx(var);
+ ScopeNode.Kind kind = _scope._kinds.at(kx);
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Instance constructors still accumulate their fields in Scope here.
+ if( FunNode.isInstance(owner._name) && (inExplicitConstructor() || _scope.enclosingFuncOrDecl()==kx) ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && _scope.enclosingFunction()==kx ) return null;
+ // Nested functions have their own receiver parameter. Resolve fields
+ // through it even across intervening function and block scopes.
+ Node self = defaultSelf();
+ Var receiver = _scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
+ ptr._obj._name.equals(declared._obj._name) ) return self;
+ // An instance method can also name fields of its enclosing class.
+ // Use that declaration's receiver; normal folding handles its identity.
+ if( !FunNode.isClz(owner._name) ) return null;
+ // The enclosing declaration may have discovered more fields since
+ // creating its receiver. View that same receiver with its current type.
+ return peep(new ConvertNode(receiver.type().upgradeType(TYPES),_scope.in(receiver)));
+ }
+
private void checkSharedFunction(Var v) {
if( _scope.canInit(v) && v._final && v.type() instanceof TypeFunPtr t && t.isConstant() )
throw error("Cannot reassign shared function '"+v._name+"'");
@@ -2563,7 +2556,7 @@ public class Parser {
java.util.BitSet finals = new java.util.BitSet();
Type self = implicitSelfType();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
_lexer.skipWhiteSpace();
@@ -2573,6 +2566,10 @@ public class Parser {
if( t==null ) break;
finals.set(ids.size(),bindingFinal(t));
String id = requireId();
+ // Older free functions may explicitly name a source argument
+ // "self". It shadows the implicit class receiver, not its ABI slot.
+ if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" )
+ ids.set(0,"#self");
ts .push(t ); // Push type/arg pairs
ids.push(id);
match(",");
diff --git a/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 1a8da215..e453387b 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -5,6 +5,7 @@ import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.type.TypeRPC;
@@ -73,13 +74,14 @@ public class CallNode extends CFGNode {
// A broad scalar target can refine to a function pointer during Iter.
// It cannot yet promise that the call exposes nothing.
if( _type!=Type.CONTROL ) return TypeMem.BOT;
- if( !(fptr()._type instanceof TypeFunPtr) )
+ if( !(fptr()._type instanceof TypeFunPtr tfp) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns()-1; i++ )
+ // A class receiver belongs to the callee; the caller does not expose its class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ )
escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs);
}
@@ -156,7 +158,10 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx);
+ // Match the callee's declared receiver view, including forward fields.
+ Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
+ : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
+ ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
CodeGen.CODE.add(parm).addDef(def);
// Linking can happen during post-SCCP inlining. Keep an RPC
// Parm's cached finite set synchronized with its newly added
diff --git a/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 61e4b468..afab6082 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -105,7 +105,8 @@ public class PhiNode extends Node {
// Generic "pull down op"
Node progress;
- if( same_op() && (progress = drop_same_op()) != null )
+ Node op = factoringOp();
+ if( same_op(op) && (progress = drop_same_op(op)) != null )
return progress;
// If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the
@@ -141,10 +142,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -162,7 +181,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -180,21 +200,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Do not introduce an operand Phi mixing incompatible type families.
diff --git a/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index 923773c4..e0860233 100644
--- a/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter28a/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -65,7 +65,7 @@ public class RegionNode extends CFGNode {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
for( int j=1; j<region.nIns(); j++ )
- phi.addDef(phi2==null ? phi.in(i) : phi2.in(j));
+ phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
}
}
diff --git a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index afdb1071..82a08dac 100644
--- a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -201,4 +202,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = code.con(TypeInteger.BOT);
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 7025b98a..85d4987f 100644
--- a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index 7eb1f255..19408f3b 100644
--- a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -257,9 +257,9 @@ val hashCode = { !String self ->
};
""";
// Return the public hashCode wrapper; keep its helper private.
- testCPU(src,"x86_64_v2", "SystemV",12,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"x86_64_v2", "SystemV",15,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test
diff --git a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index e15c2581..f3af31a2 100644
--- a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -384,9 +384,9 @@ val hashCode = { !String self ->
};
""";
// Return the public hashCode wrapper; keep its helper private.
- testCPU(src,"x86_64_v2", "SystemV",12,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"x86_64_v2", "SystemV",15,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test public void testStringExport() throws IOException {
@@ -423,7 +423,7 @@ val hashCode = { !String self ->
: (self._hashCode = _hashCodeString(self));
};
""";
- TestC.runC(src, "stringHash", "",12);
+ TestC.runC(src, "stringHash", "",15);
}
@Test public void testLoop2() {
diff --git a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter22Test.java
index 00d77f65..115ee1ca 100644
--- a/chapter28a/src/test/java/com/seaofnodes/simple/Chapter22Test.java
+++ b/chapter28a/src/test/java/com/seaofnodes/simple/Chapter22Test.java
@@ -301,17 +301,17 @@ val p = { u8[~] str ->
p("Hello, World!");
return 0;
""";
- TestC.runSF(src,"helloWorld", "Hello, World!",2);
+ TestC.runSF(src,"helloWorld", "Hello, World!",4);
// Evaluate on RISC5 emulator
- EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false);
+ EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false);
int trap = R5.step(100);
assertEquals(0,trap);
assertEquals(0,R5.regs[riscv.A0]);
assertEquals("Hello, World!",R5._stdout.toString());
// Evaluate on ARM emulator
- EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false);
+ EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false);
trap = arm.step(100);
assertEquals(0,trap);
assertEquals(0,arm.regs[0]);
diff --git a/chapter28a/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter28a/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
new file mode 100644
index 00000000..e24baee0
--- /dev/null
+++ b/chapter28a/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -0,0 +1,71 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class GlobalAssignmentTest {
+ private static final String SOURCE = """
+ int value=1;
+ int writes=0;
+ u8 small=0;
+ val set={int n -> value=n; return value;};
+ val set_noInline={int n ->
+ if( n<0 ) value=3;
+ else value=n;
+ return value;
+ };
+ val rhs_noInline={ -> writes=writes+1; return value+1;};
+ val shadow={int value -> value=42; return value;};
+ struct Writer {
+ int seen;
+ new Writer={int n -> value=n; seen=value;};
+ };
+ struct InitWriter { int seen=(value=17); };
+ val main={ ->
+ if( set(5)!=5 || value!=5 ) return 1;
+ if( set_noInline(-1)!=3 || value!=3 ) return 2;
+ if( set_noInline(8)!=8 || value!=8 ) return 3;
+ int result=(value=rhs_noInline());
+ if( result!=9 || value!=9 || writes!=1 ) return 4;
+ value=writes=11;
+ if( value!=11 || writes!=11 ) return 5;
+ if( shadow(0)!=42 || value!=11 ) return 6;
+ int wide=(small=257);
+ if( wide!=257 || small!=1 ) return 7;
+ val constructed=new Writer(13);
+ if( value!=13 || constructed.seen!=13 ) return 8;
+ val initialized=new InitWriter;
+ // Default expressions run at declaration time, not per instance.
+ if( value!=13 || initialized.seen!=17 ) return 9;
+ return 0;
+ };
+ return main();
+ """;
+
+ @Test public void storesGlobalMemory() throws Exception {
+ assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(SOURCE,"global_assignment","",-1);
+ }
+
+ @Test public void rejectsFinalGlobal() {
+ try {
+ new CodeGen("val value=1; val set={ -> value=2; }; return set();")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Assigned a final global");
+ } catch( Parser.ParseException e ) {
+ assertEquals("Cannot reassign final 'value'",e.getMessage());
+ }
+ }
+
+ @Test public void rejectsIncompatibleGlobalValue() {
+ try {
+ new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Stored an object in an integer global");
+ } catch( Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type"));
+ }
+ }
+}
diff --git a/chapter28a/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter28a/src/test/java/com/seaofnodes/simple/ReceiverTest.java
new file mode 100644
index 00000000..9384b42a
--- /dev/null
+++ b/chapter28a/src/test/java/com/seaofnodes/simple/ReceiverTest.java
@@ -0,0 +1,93 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ReceiverTest {
+ @Test public void classAndInstanceFields() throws Exception {
+ String source="""
+ int total=1;
+ val forward={ -> late(); };
+ val early={ -> total; };
+ val late={ -> early(); };
+ val add_noInline={int n -> self.total=self.total+n; return total;};
+ val read_noInline={ -> self.total; };
+ val nested={ ->
+ val inc={ -> self.total++; };
+ inc();
+ return total;
+ };
+ struct Counter {
+ int total=100;
+ val read=read_noInline;
+ };
+ struct Writer {
+ int count=2;
+ val step={ -> self.count++; total=count; return total; };
+ };
+ u16[] !table=new u16[2];
+ val lookup={u8 c -> c<2 ? table[c] : 0;};
+ val main={ ->
+ total=1;
+ table=new u16[2]; table[0]=7; table[1]=9;
+ if( forward()!=1 ) return 4;
+ if( lookup(1)!=9 || lookup(2)!=0 ) return 5;
+ if( add_noInline(5)!=6 || nested()!=7 ) return 1;
+ val counter=new Counter;
+ if( counter.read()!=7 || counter.total!=100 ) return 2;
+ val a=new Writer, b=new Writer;
+ if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3;
+ return 0;
+ };
+ return main();
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(source,"class_instance_receivers","",-1);
+ }
+
+ @Test public void sourceCallbackKeepsItsClass() throws Exception {
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path source=Files.createTempDirectory(build,"sources-");
+ Files.createDirectories(source.resolve("Root"));
+ Files.writeString(source.resolve("Root.smp"),"");
+ Files.writeString(source.resolve("Root/Owner.smp"),
+ "int value=7; val get_noInline={ -> self.value; };");
+ Files.writeString(source.resolve("Root/Forwarder.smp"),
+ "int value=99; val apply_noInline={ {int} action -> action()+self.value; };");
+ Files.writeString(source.resolve("Root/Main.smp"),
+ "return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;");
+ CodeGen code=new CodeGen(source.toString(),source.toString(),"Root/Main",null,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ }
+
+ @Test public void classReceiverHasNoNativeArgument() throws Exception {
+ String source="""
+ int base=10;
+ val calc={i64 a,i64 b,i64 c,i64 d,i64 e,i64 f,i64 g ->
+ self.base+a+2*b+3*c+4*d+5*e+6*f+7*g;
+ };
+ val callback_noInline={i64 n -> self.base+n;};
+ { {i64 -> i64} i64 -> i64 } invoke="C";
+ val viaC={i64 n -> invoke(callback_noInline,n);};
+ """;
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path driver=build.resolve("native_receiver.c");
+ Files.writeString(driver,"""
+ typedef long long (__attribute__((CALL_CONV)) *action_t)(long long);
+ __attribute__((CALL_CONV)) long long invoke(action_t action, long long n) { return action(n); }
+ __attribute__((CALL_CONV)) extern long long calc(long long,long long,long long,long long,long long,long long,long long);
+ __attribute__((CALL_CONV)) extern long long viaC(long long);
+ int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; }
+ """);
+ TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION,
+ TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1);
+ }
+}
diff --git a/chapter28b/README.md b/chapter28b/README.md
index 84e538ea..5d8cbdf9 100644
--- a/chapter28b/README.md
+++ b/chapter28b/README.md
@@ -120,7 +120,14 @@ those exclusions by owner and slot, then restores the complement. Treating
this set as FULL would expose private library functions. Unknown callback
arguments, results, and unloaded summaries use the evolving Start/Stop state;
no frozen public-function list supplies their bounds. Hidden class receivers
-default to the defining class singleton even after import. The
+default to the defining class singleton even after import, following
+[chapter 28a's receiver model](../chapter28a/README.md#globals-use-the-same-receiver-as-fields).
+`SummaryNode` excludes that hidden receiver from its conservative argument-escape
+scan: the caller supplies no class object through the ABI, and actual publication
+of the callee's class fields is already represented by the saved summary state.
+Instance receivers remain ordinary arguments and participate in that scan.
+[ReceiverTest](src/test/java/com/seaofnodes/simple/ReceiverTest.java) checks a
+callback forwarded by another compiled class with a different field value. The
[escape-flow implementation notes](../chapter29/docs/escape-flow.md) explain
the shared design and the identity-remapping checks in more detail.
diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java b/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java
index cef7091a..0e8eb5a9 100644
--- a/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java
+++ b/chapter28b/src/main/java/com/seaofnodes/simple/Parser.java
@@ -291,8 +291,16 @@ public class Parser {
// All args, "as-if" called externally
for( int i=0; i<ids.length; i++ ) {
Type t = sig.arg(i);
+ // The body sees its owning class receiver. PTR remains in the
+ // signature as the ABI marker for a receiver with no machine slot.
+ if( i==0 && t==TypePtr.PTR ) {
+ TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj;
+ // A file can add globals after its struct declaration closes.
+ // Keep this view open until SCCP installs the completed class.
+ t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true);
+ }
// Args take a default input if called from Start/external-world
- _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole(), loc);
+ _scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(i==0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i)).peephole()).peephole(), loc);
}
if( isCtor && !isInit ) {
@@ -1085,6 +1093,10 @@ public class Parser {
throw error("Cannot reassign final '"+name+"'");
checkSharedFunction(def);
+ // All fields use the same receiver-based lvalue path.
+ if( fieldSelf(def)!=null )
+ { pos(old); return parseExpression(); }
+
// Parse assignment expression
Node expr = parseAsgn();
@@ -1094,27 +1106,6 @@ public class Parser {
// Update
_scope.update(name,lift);
- // Check for storing into an instance field instead of a local var
- int kx = _scope.kindx(def); // Declaration scope
- int fx = _scope.enclosingFunction(); // Enclosing function scope
- Kind kk = _scope._kinds.at(kx);
- Kind fk = _scope._kinds.at(fx);
- // Access instance field from 'self'
- if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) &&
- fk instanceof Kind.Func method && !inExplicitConstructor() ) {
- // Named field offset on an unknown struct type
- TypeMemPtr self = (TypeMemPtr)_scope.var(fk._lexSize).type();
- TypeStruct sobj = (TypeStruct)TYPES.get(self._obj._name);
- Field fld = sobj.field(name);
- int alias = fld._alias;
- Node ptr = _scope.in(method._lexSize);
- Node off = fldoff(ptr,name);
- Node prior = mem().keep();
- Node st = new StoreNode(loc(), name, alias, decl, ctrl(), prior, ptr, off, lift, inExplicitConstructor()).peephole().keep();
- storeMem(st,alias,prior);
- st.unkeep();
- prior.unkeep();
- }
lift.unkill();
@@ -2109,35 +2100,12 @@ public class Parser {
if( inExplicitConstructor() && var._uninit && missingInit(rvalue,new BitSet()) )
throw error("Field '"+id+"' might not be initialized",var._loc);
- // Check for an instance field load
- int kx = _scope.kindx(var); // Declaration scope
- int fx = _scope.enclosingFunction(); // Enclosing function scope
- Kind kk = _scope._kinds.at(kx);
- Kind fk = _scope._kinds.at(fx);
- // Access instance field from 'self'
- if( kx+1 == fx && kk instanceof Kind.Func inst && FunNode.isInstance(inst._name) && fk instanceof Kind.Func method && !inExplicitConstructor() )
- return parsePostfixName(_scope.in(method._lexSize),id,pre);
-
- // Check for a function-escaping variable; these require true
- // closures. Final constants are OK; final vars require a hidden var
- // argument; not-final fields can just use an explicit struct arg.
- if( kx < fx && !inExplicitConstructor() && // Out of scope
- !(var._final && rvalue._type.isConstant()) ) { // Not a final constant
- if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke)
- throw error("Variable '"+var._name+"' is out of function scope and must be a final constant");
-
- // var.idx==2 is self argument, 3 is args, 4 or more are now static globals
- if( var._idx >= 4 ) {
- // Read from global scope.
- // Surely a nicer way to get the top-level scope compile name?
- Var clzptr = _scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parsePostfixName( con( clztmp ), id,pre );
- //return parsePostfixName(_scope.in(2),id);
- }
- }
+ Node self = fieldSelf(var);
+ if( self!=null ) return parsePostfixName(self,id,pre);
+ int kx = _scope.kindx(var), fx = _scope.enclosingFunction();
+ if( kx>0 && kx<fx && !inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw error("Variable '"+var._name+"' is out of function scope and must be a final constant");
// Check for assign-update, x += e0;
char ch = pre==0 ? _lexer.matchOperAssign() : (char)pre;
@@ -2382,6 +2350,31 @@ public class Parser {
return parsePostfixMethod(value,defaultSelf());
}
+ // Find the receiver for a field lvalue. Initializers retain Scope values;
+ // class declarations retain their Scope values until initializer exit.
+ private Node fieldSelf(Var var) {
+ int kx = _scope.kindx(var);
+ ScopeNode.Kind kind = _scope._kinds.at(kx);
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Instance constructors still accumulate their fields in Scope here.
+ if( FunNode.isInstance(owner._name) && (inExplicitConstructor() || _scope.enclosingFuncOrDecl()==kx) ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && _scope.enclosingFunction()==kx ) return null;
+ // Nested functions have their own receiver parameter. Resolve fields
+ // through it even across intervening function and block scopes.
+ Node self = defaultSelf();
+ Var receiver = _scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
+ ptr._obj._name.equals(declared._obj._name) ) return self;
+ // An instance method can also name fields of its enclosing class.
+ // Use that declaration's receiver; normal folding handles its identity.
+ if( !FunNode.isClz(owner._name) ) return null;
+ // The enclosing declaration may have discovered more fields since
+ // creating its receiver. View that same receiver with its current type.
+ return peep(new ConvertNode(receiver.type().upgradeType(TYPES),_scope.in(receiver)));
+ }
+
private void checkSharedFunction(Var v) {
if( _scope.canInit(v) && v._final && v.type() instanceof TypeFunPtr t && t.isConstant() )
throw error("Cannot reassign shared function '"+v._name+"'");
@@ -2573,7 +2566,7 @@ public class Parser {
java.util.BitSet finals = new java.util.BitSet();
Type self = implicitSelfType();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
_lexer.skipWhiteSpace();
@@ -2583,6 +2576,10 @@ public class Parser {
if( t==null ) break;
finals.set(ids.size(),bindingFinal(t));
String id = requireId();
+ // Older free functions may explicitly name a source argument
+ // "self". It shadows the implicit class receiver, not its ABI slot.
+ if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" )
+ ids.set(0,"#self");
ts .push(t ); // Push type/arg pairs
ids.push(id);
match(",");
diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 23188e84..a69708c0 100644
--- a/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -6,6 +6,7 @@ import com.seaofnodes.simple.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.codegen.Iter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
import com.seaofnodes.simple.type.TypeRPC;
@@ -90,13 +91,14 @@ public class CallNode extends CFGNode {
// A broad scalar target can refine to a function pointer during Iter.
// It cannot yet promise that the call exposes nothing.
if( _type!=Type.CONTROL ) return TypeMem.BOT;
- if( !(fptr()._type instanceof TypeFunPtr) )
+ if( !(fptr()._type instanceof TypeFunPtr tfp) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns()-1; i++ )
+ // A class receiver belongs to the callee; the caller does not expose its class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ )
escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs);
}
@@ -173,7 +175,10 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx);
+ // Match the callee's declared receiver view, including forward fields.
+ Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
+ : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
+ ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
CodeGen.CODE.add(parm).addDef(def);
// Linking can happen during post-SCCP inlining. Keep an RPC
// Parm's cached finite set synchronized with its newly added
diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 3cf6f854..de255a97 100644
--- a/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -114,7 +114,8 @@ public class PhiNode extends Node {
// Generic "pull down op"
Node progress;
- if( same_op() && (progress = drop_same_op()) != null )
+ Node op = factoringOp();
+ if( same_op(op) && (progress = drop_same_op(op)) != null )
return progress;
// If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the
@@ -150,10 +151,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -171,7 +190,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -189,21 +209,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp.addDef(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Do not introduce an operand Phi mixing incompatible type families.
diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index 8883ba8e..55f635ae 100644
--- a/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -68,7 +68,7 @@ public class RegionNode extends CFGNode {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
for( int j=1; j<region.nIns(); j++ )
- phi.addDef(phi2==null ? phi.in(i) : phi2.in(j));
+ phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
}
}
diff --git a/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index 483aab89..d0da3250 100644
--- a/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter28b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -27,7 +27,7 @@ public class SummaryNode extends CFGNode implements MultiNode {
TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
mem = (TypeMem)mem.meet(_state.mem());
TypeMem outside = CodeGen.CODE._start.outside(this);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
return TypeTuple.make(_state.ctl(),mem,_state.ret());
}
@Override public Node idealize() { return null; }
@@ -36,9 +36,16 @@ public class SummaryNode extends CFGNode implements MultiNode {
if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START;
TypeMem mem = (TypeMem)_state.mem();
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs);
}
+ // A class receiver is supplied by the callee, not exposed by its caller.
+ // Actual uses which publish self are already represented in _state.
+ 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;
+ }
@Override boolean _upgradeType(HashMap<String,Type> types) {
TypeTuple state = (TypeTuple)_state.upgradeType(types);
if( state==_state ) return false;
diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index afdb1071..82a08dac 100644
--- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -201,4 +202,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = code.con(TypeInteger.BOT);
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 7025b98a..85d4987f 100644
--- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index 7eb1f255..19408f3b 100644
--- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -257,9 +257,9 @@ val hashCode = { !String self ->
};
""";
// Return the public hashCode wrapper; keep its helper private.
- testCPU(src,"x86_64_v2", "SystemV",12,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"x86_64_v2", "SystemV",15,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test
diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index e15c2581..f3af31a2 100644
--- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -384,9 +384,9 @@ val hashCode = { !String self ->
};
""";
// Return the public hashCode wrapper; keep its helper private.
- testCPU(src,"x86_64_v2", "SystemV",12,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"x86_64_v2", "SystemV",15,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test public void testStringExport() throws IOException {
@@ -423,7 +423,7 @@ val hashCode = { !String self ->
: (self._hashCode = _hashCodeString(self));
};
""";
- TestC.runC(src, "stringHash", "",12);
+ TestC.runC(src, "stringHash", "",15);
}
@Test public void testLoop2() {
diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java
index 00d77f65..115ee1ca 100644
--- a/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java
+++ b/chapter28b/src/test/java/com/seaofnodes/simple/Chapter22Test.java
@@ -301,17 +301,17 @@ val p = { u8[~] str ->
p("Hello, World!");
return 0;
""";
- TestC.runSF(src,"helloWorld", "Hello, World!",2);
+ TestC.runSF(src,"helloWorld", "Hello, World!",4);
// Evaluate on RISC5 emulator
- EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false);
+ EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false);
int trap = R5.step(100);
assertEquals(0,trap);
assertEquals(0,R5.regs[riscv.A0]);
assertEquals("Hello, World!",R5._stdout.toString());
// Evaluate on ARM emulator
- EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false);
+ EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false);
trap = arm.step(100);
assertEquals(0,trap);
assertEquals(0,arm.regs[0]);
diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter28b/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
new file mode 100644
index 00000000..e24baee0
--- /dev/null
+++ b/chapter28b/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -0,0 +1,71 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class GlobalAssignmentTest {
+ private static final String SOURCE = """
+ int value=1;
+ int writes=0;
+ u8 small=0;
+ val set={int n -> value=n; return value;};
+ val set_noInline={int n ->
+ if( n<0 ) value=3;
+ else value=n;
+ return value;
+ };
+ val rhs_noInline={ -> writes=writes+1; return value+1;};
+ val shadow={int value -> value=42; return value;};
+ struct Writer {
+ int seen;
+ new Writer={int n -> value=n; seen=value;};
+ };
+ struct InitWriter { int seen=(value=17); };
+ val main={ ->
+ if( set(5)!=5 || value!=5 ) return 1;
+ if( set_noInline(-1)!=3 || value!=3 ) return 2;
+ if( set_noInline(8)!=8 || value!=8 ) return 3;
+ int result=(value=rhs_noInline());
+ if( result!=9 || value!=9 || writes!=1 ) return 4;
+ value=writes=11;
+ if( value!=11 || writes!=11 ) return 5;
+ if( shadow(0)!=42 || value!=11 ) return 6;
+ int wide=(small=257);
+ if( wide!=257 || small!=1 ) return 7;
+ val constructed=new Writer(13);
+ if( value!=13 || constructed.seen!=13 ) return 8;
+ val initialized=new InitWriter;
+ // Default expressions run at declaration time, not per instance.
+ if( value!=13 || initialized.seen!=17 ) return 9;
+ return 0;
+ };
+ return main();
+ """;
+
+ @Test public void storesGlobalMemory() throws Exception {
+ assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(SOURCE,"global_assignment","",-1);
+ }
+
+ @Test public void rejectsFinalGlobal() {
+ try {
+ new CodeGen("val value=1; val set={ -> value=2; }; return set();")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Assigned a final global");
+ } catch( Parser.ParseException e ) {
+ assertEquals("Cannot reassign final 'value'",e.getMessage());
+ }
+ }
+
+ @Test public void rejectsIncompatibleGlobalValue() {
+ try {
+ new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Stored an object in an integer global");
+ } catch( Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type"));
+ }
+ }
+}
diff --git a/chapter28b/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter28b/src/test/java/com/seaofnodes/simple/ReceiverTest.java
new file mode 100644
index 00000000..0342d9a2
--- /dev/null
+++ b/chapter28b/src/test/java/com/seaofnodes/simple/ReceiverTest.java
@@ -0,0 +1,94 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ReceiverTest {
+ @Test public void classAndInstanceFields() throws Exception {
+ String source="""
+ int total=1;
+ val forward={ -> late(); };
+ val early={ -> total; };
+ val late={ -> early(); };
+ val add_noInline={int n -> self.total=self.total+n; return total;};
+ val read_noInline={ -> self.total; };
+ val nested={ ->
+ val inc={ -> self.total++; };
+ inc();
+ return total;
+ };
+ struct Counter {
+ int total=100;
+ val read=read_noInline;
+ };
+ struct Writer {
+ int count=2;
+ val step={ -> self.count++; total=count; return total; };
+ };
+ u16[] !table=new u16[2];
+ val lookup={u8 c -> c<2 ? table[c] : 0;};
+ val main={ ->
+ total=1;
+ table=new u16[2]; table[0]=7; table[1]=9;
+ if( forward()!=1 ) return 4;
+ if( lookup(1)!=9 || lookup(2)!=0 ) return 5;
+ if( add_noInline(5)!=6 || nested()!=7 ) return 1;
+ val counter=new Counter;
+ if( counter.read()!=7 || counter.total!=100 ) return 2;
+ val a=new Writer, b=new Writer;
+ if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3;
+ return 0;
+ };
+ return main();
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(source,"class_instance_receivers","",-1);
+ }
+
+ @Test public void importedCallbackKeepsItsClass() throws Exception {
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"classes-");
+ new CodeGen(null,lib.toString(),null,"Owner",
+ "int value=7; val get_noInline={ -> self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),null,"Forwarder",
+ "int value=99; val apply_noInline={ {int} action -> action()+self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ String source="return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;";
+ CodeGen code=new CodeGen(null,null,paths,"ReceiverClient",source,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ TestC.run(source,"imported_receivers",paths,TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void classReceiverHasNoNativeArgument() throws Exception {
+ String source="""
+ int base=10;
+ val calc={i64 a,i64 b,i64 c,i64 d,i64 e,i64 f,i64 g ->
+ self.base+a+2*b+3*c+4*d+5*e+6*f+7*g;
+ };
+ val callback_noInline={i64 n -> self.base+n;};
+ { {i64 -> i64} i64 -> i64 } invoke="C";
+ val viaC={i64 n -> invoke(callback_noInline,n);};
+ """;
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path driver=build.resolve("native_receiver.c");
+ Files.writeString(driver,"""
+ typedef long long (__attribute__((CALL_CONV)) *action_t)(long long);
+ __attribute__((CALL_CONV)) long long invoke(action_t action, long long n) { return action(n); }
+ __attribute__((CALL_CONV)) extern long long calc(long long,long long,long long,long long,long long,long long,long long);
+ __attribute__((CALL_CONV)) extern long long viaC(long long);
+ int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; }
+ """);
+ TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION,
+ TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1);
+ }
+}
diff --git a/chapter29/README.md b/chapter29/README.md
index ed39de98..03c9a116 100644
--- a/chapter29/README.md
+++ b/chapter29/README.md
@@ -14,6 +14,9 @@ backporting the cleanups, in part to show the normal progression of large
project development.
+This snapshot retains [chapter 28a's shared class receiver](../chapter28a/README.md#globals-use-the-same-receiver-as-fields)
+and chapter 28b's imported-callback handling.
+
## Following the grammar
The old `Parser.java` had grown beyond 3,000 lines, mixing recursive descent,
diff --git a/chapter29/docs/29-grammar.md b/chapter29/docs/29-grammar.md
index cb231ce0..d580a28b 100644
--- a/chapter29/docs/29-grammar.md
+++ b/chapter29/docs/29-grammar.md
@@ -57,6 +57,7 @@ constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
+// Global functions use their owning class singleton as self.
// Function types and expressions both receive their implicit receiver here.
methodDeclaration : 'val' bindingModifier? IDENTIFIER '=' functionExpression ';' ;
@@ -220,10 +221,10 @@ one-pass IR builder:
- A statement beginning with `{` might be a block or a function-type binding.
`Declarations` and `Types` use speculative parsing and cursor restore;
qualified type lookup also stops before a suffix that belongs to an expression.
-- Bare assignment, field assignment, and compound updates share the grammar's
- precedence but use different IR paths. `References` decides between an SSA
- local, a constructor field's local value, and an actual memory access. A
- function-valued field may also supply an implicit receiver to a call.
+- Bare fields resolve through their receiver, so reads, assignments, and
+ updates share the field-access path. Locals use SSA; class declarations
+ retain Scope values until initializer exit. Global functions receive their
+ owning class singleton as `self`; instance methods receive their object.
- `for` updates are scanned first and parsed after the body, where their effects
belong. Explicit constructor bodies are scanned first and parsed after field
discovery, so later fields have local slots. Both use `Lexer.skipTo`, which
diff --git a/chapter29/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter29/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 91d27330..0a48e7aa 100644
--- a/chapter29/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter29/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -7,6 +7,7 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.codegen.Iter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeMemPtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
@@ -95,13 +96,14 @@ public class CallNode extends CFGNode {
// A broad scalar target can refine to a function pointer during Iter.
// It cannot yet promise that the call exposes nothing.
if( _type!=Type.CONTROL ) return TypeMem.BOT;
- if( !(fptr()._type instanceof TypeFunPtr) )
+ if( !(fptr()._type instanceof TypeFunPtr tfp) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns()-1; i++ )
+ // A class receiver belongs to the callee; the caller does not expose its class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ )
escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs);
}
@@ -179,7 +181,10 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx);
+ // Match the callee's declared receiver view, including forward fields.
+ Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
+ : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
+ ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
CodeGen.CODE.add(parm).addDef(def);
// Linking can happen during post-SCCP inlining. Keep an RPC
// Parm's cached finite set synchronized with its newly added
diff --git a/chapter29/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter29/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index f45c7325..af24a94b 100644
--- a/chapter29/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter29/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -122,7 +122,8 @@ public class PhiNode extends Node {
// Generic "pull down op"
Node progress;
- if( same_op() && (progress = drop_same_op()) != null )
+ Node op = factoringOp();
+ if( same_op(op) && (progress = drop_same_op(op)) != null )
return progress;
// If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the
@@ -158,10 +159,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -179,7 +198,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -197,21 +217,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp._inputs.add(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Do not introduce an operand Phi mixing incompatible type families.
diff --git a/chapter29/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter29/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index eee1c150..3ed63862 100644
--- a/chapter29/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter29/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -69,7 +69,7 @@ public class RegionNode extends CFGNode {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
for( int j=1; j<region.nIns(); j++ )
- phi.addDef(phi2==null ? phi.in(i) : phi2.in(j));
+ phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
}
}
diff --git a/chapter29/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter29/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index 483aab89..d0da3250 100644
--- a/chapter29/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter29/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -27,7 +27,7 @@ public class SummaryNode extends CFGNode implements MultiNode {
TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
mem = (TypeMem)mem.meet(_state.mem());
TypeMem outside = CodeGen.CODE._start.outside(this);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
return TypeTuple.make(_state.ctl(),mem,_state.ret());
}
@Override public Node idealize() { return null; }
@@ -36,9 +36,16 @@ public class SummaryNode extends CFGNode implements MultiNode {
if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START;
TypeMem mem = (TypeMem)_state.mem();
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs);
}
+ // A class receiver is supplied by the callee, not exposed by its caller.
+ // Actual uses which publish self are already represented in _state.
+ 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;
+ }
@Override boolean _upgradeType(HashMap<String,Type> types) {
TypeTuple state = (TypeTuple)_state.upgradeType(types);
if( state==_state ) return false;
diff --git a/chapter29/src/main/java/com/seaofnodes/simple/parser/Expressions.java b/chapter29/src/main/java/com/seaofnodes/simple/parser/Expressions.java
index 93c07d8a..806e5f7f 100644
--- a/chapter29/src/main/java/com/seaofnodes/simple/parser/Expressions.java
+++ b/chapter29/src/main/java/com/seaofnodes/simple/parser/Expressions.java
@@ -31,6 +31,9 @@ final class Expressions {
{ P.pos(old); return parseExpression(); }
P.references.checkAssignment(def);
+ // All fields use the same receiver-based lvalue path.
+ if( P.references.fieldSelf(def)!=null )
+ { P.pos(old); return parseExpression(); }
return P.references.assign(def,parseAssignment());
}
diff --git a/chapter29/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter29/src/main/java/com/seaofnodes/simple/parser/Functions.java
index 14dee33b..4d80b100 100644
--- a/chapter29/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter29/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -30,7 +30,7 @@ final class Functions {
BitSet finals = new BitSet();
Type self = P.types.implicitSelfType();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
P._lexer.skipWhiteSpace();
@@ -81,6 +81,10 @@ final class Functions {
}
finals.set(ids.size(),P.declarations.bindingFinal(t));
String id = P.requireId();
+ // Older free functions may explicitly name a source argument
+ // "self". It shadows the implicit class receiver, not its ABI slot.
+ if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" )
+ ids.set(0,"#self");
ts .push(t ); // Push type/arg pairs
ids.push(id);
P.match(",");
@@ -291,8 +295,16 @@ final class Functions {
// All args, "as-if" called externally
for( int i = 0; i<ids.length; i++ ) {
Type t = sig.arg(i);
+ // The body sees its owning class receiver. PTR remains in the
+ // signature as the ABI marker for a receiver with no machine slot.
+ if( i==0 && t==TypePtr.PTR ) {
+ TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj;
+ // A file can add globals after its struct declaration closes.
+ // Keep this view open until SCCP installs the completed class.
+ t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true);
+ }
// Args take a default input if called from Start/external-world
- Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole();
+ Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(i==0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i)).peephole()).peephole();
if( t instanceof TypeMemPtr ptr && ptr._partial ) parm = new ConstructNode(parm).peephole();
P._scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), parm, loc);
}
diff --git a/chapter29/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter29/src/main/java/com/seaofnodes/simple/parser/References.java
index 483bd7a8..eaf4ce65 100644
--- a/chapter29/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter29/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -70,23 +70,9 @@ final class References {
// Check for a function-escaping variable; these require true
// closures. Final constants are OK; final vars require a hidden var
// argument; not-final fields can just use an explicit struct arg.
- if( kx < fx && !P.structs.inExplicitConstructor() && // Out of scope
- !(var._final && rvalue._type.isConstant()) ) { // Not a final constant
- if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke)
- throw P.error("Variable '"+var._name+"' is out of function scope and must be a final constant");
-
- // var.idx==2 is self argument, 3 is args, 4 or more are now static globals
- if( var._idx >= 4 ) {
- // Read from global scope.
- // Surely a nicer way to get the top-level scope compile name?
- Var clzptr = P._scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) Parser.TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parseField( P.con( clztmp ), id,pre );
- //return parseField(_scope.in(2),id);
- }
- }
+ if( kx>0 && kx<fx && !P.structs.inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw P.error("Variable '"+var._name+"' is out of function scope and must be a final constant");
// Check for assign-update, x += e0;
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
@@ -119,19 +105,6 @@ final class References {
}
Node assign(Var def, Node expr) {
- Node self = fieldSelf(def);
- if( self!=null ) {
- TypeStruct ts = P.types.latestStruct(((TypeMemPtr)self._type)._obj);
- Field fld = ts.field(def._name);
- Node val = expr.keep();
- Node lift = P.conversions.convertExpr(val,def.type());
- Node mem = P.construction.storeMemory(self).keep();
- Node st = new StoreNode(P.loc(),fld._fname,fld._alias,fld._t,P.ctrl(),mem,self,
- ConFldOffNode.make(ts,fld._fname),lift,P.construction.own(self)).peephole();
- P.construction.store(self,fld._alias,st,mem);
- mem.unkeep();
- return val.unkeep();
- }
String name = def._name;
// Lift expression, based on type
Type decl = def.type(); // Declared type
@@ -280,14 +253,27 @@ final class References {
return P._scope.in(P._scope.update(P._scope.var(selfx),null));
}
- // Fields are lvalues in memory, including inside their initializer and
- // explicit constructor. Scope slots retain declaration metadata only.
- private Node fieldSelf(Var var) {
- int kx = P._scope.kindx(var), fx = P._scope.enclosingFuncOrDecl();
+ // Find the receiver for a field lvalue. Instance initializers use memory;
+ // class declarations retain their Scope values until initializer exit.
+ Node fieldSelf(Var var) {
+ int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
- if( !(kind instanceof Kind.Func inst) || !FunNode.isInstance(inst._name) || var._idx<inst._lexSize+2 ) return null;
- if( kx==fx || kx+1==fx ) return defaultSelf();
- return null;
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && P._scope.enclosingFunction()==kx ) return null;
+ // Nested functions have their own receiver parameter. Resolve fields
+ // through it even across intervening function and block scopes.
+ Node self = defaultSelf();
+ Var receiver = P._scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
+ ptr._obj._name.equals(declared._obj._name) ) return self;
+ // An instance method can also name fields of its enclosing class.
+ // Use that declaration's receiver; normal folding handles its identity.
+ if( !FunNode.isClz(owner._name) ) return null;
+ // The enclosing declaration may have discovered more fields since
+ // creating its receiver. View that same receiver with its current type.
+ return P.peep(new ConvertNode(receiver.type().upgradeType(Parser.TYPES),P._scope.in(receiver)));
}
private void checkSharedFunction(Var v) {
diff --git a/chapter29/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter29/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index afdb1071..82a08dac 100644
--- a/chapter29/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter29/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -201,4 +202,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = code.con(TypeInteger.BOT);
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter29/src/test/java/com/seaofnodes/simple/Chapter09Test.java b/chapter29/src/test/java/com/seaofnodes/simple/Chapter09Test.java
index 7025b98a..85d4987f 100644
--- a/chapter29/src/test/java/com/seaofnodes/simple/Chapter09Test.java
+++ b/chapter29/src/test/java/com/seaofnodes/simple/Chapter09Test.java
@@ -41,7 +41,7 @@ else {
return x;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Region,(arg<<1),(Shl+1));", code.print());
+ assertEquals("return (Phi(Region,arg,1)+Phi(Region,arg,(arg<<1)));", code.print());
Assert.assertEquals( "2", Eval2.eval(code, 1));
Assert.assertEquals("23", Eval2.eval(code, 11));
}
diff --git a/chapter29/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter29/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index f5eb2b36..a8f2a280 100644
--- a/chapter29/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter29/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -259,9 +259,9 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
- testCPU(src,"x86_64_v2", "SystemV",12,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"x86_64_v2", "SystemV",15,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test
diff --git a/chapter29/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter29/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index e15c2581..f3af31a2 100644
--- a/chapter29/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter29/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -384,9 +384,9 @@ val hashCode = { !String self ->
};
""";
// Return the public hashCode wrapper; keep its helper private.
- testCPU(src,"x86_64_v2", "SystemV",12,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"x86_64_v2", "SystemV",15,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test public void testStringExport() throws IOException {
@@ -423,7 +423,7 @@ val hashCode = { !String self ->
: (self._hashCode = _hashCodeString(self));
};
""";
- TestC.runC(src, "stringHash", "",12);
+ TestC.runC(src, "stringHash", "",15);
}
@Test public void testLoop2() {
diff --git a/chapter29/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter29/src/test/java/com/seaofnodes/simple/Chapter22Test.java
index e9a668a7..e81bd51d 100644
--- a/chapter29/src/test/java/com/seaofnodes/simple/Chapter22Test.java
+++ b/chapter29/src/test/java/com/seaofnodes/simple/Chapter22Test.java
@@ -302,17 +302,17 @@ val p = { u8[~] str ->
p("Hello, World!");
return 0;
""";
- TestC.runSF(src,"helloWorld", "Hello, World!",2);
+ TestC.runSF(src,"helloWorld", "Hello, World!",4);
// Evaluate on RISC5 emulator
- EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false);
+ EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false);
int trap = R5.step(100);
assertEquals(0,trap);
assertEquals(0,R5.regs[riscv.A0]);
assertEquals("Hello, World!",R5._stdout.toString());
// Evaluate on ARM emulator
- EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false);
+ EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false);
trap = arm.step(100);
assertEquals(0,trap);
assertEquals(0,arm.regs[0]);
diff --git a/chapter29/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter29/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
new file mode 100644
index 00000000..51ed10c6
--- /dev/null
+++ b/chapter29/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -0,0 +1,71 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.parser.Parser;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class GlobalAssignmentTest {
+ private static final String SOURCE = """
+ int value=1;
+ int writes=0;
+ u8 small=0;
+ val set={int n -> value=n; return value;};
+ val set_noInline={int n ->
+ if( n<0 ) value=3;
+ else value=n;
+ return value;
+ };
+ val rhs_noInline={ -> writes=writes+1; return value+1;};
+ val shadow={int value -> value=42; return value;};
+ struct Writer {
+ int seen;
+ new Writer={int n -> value=n; seen=value;};
+ };
+ struct InitWriter { int seen=(value=17); };
+ val main={ ->
+ if( set(5)!=5 || value!=5 ) return 1;
+ if( set_noInline(-1)!=3 || value!=3 ) return 2;
+ if( set_noInline(8)!=8 || value!=8 ) return 3;
+ int result=(value=rhs_noInline());
+ if( result!=9 || value!=9 || writes!=1 ) return 4;
+ value=writes=11;
+ if( value!=11 || writes!=11 ) return 5;
+ if( shadow(0)!=42 || value!=11 ) return 6;
+ int wide=(small=257);
+ if( wide!=257 || small!=1 ) return 7;
+ val constructed=new Writer(13);
+ if( value!=13 || constructed.seen!=13 ) return 8;
+ val initialized=new InitWriter;
+ // Default expressions run at declaration time, not per instance.
+ if( value!=13 || initialized.seen!=17 ) return 9;
+ return 0;
+ };
+ return main();
+ """;
+
+ @Test public void storesGlobalMemory() throws Exception {
+ assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(SOURCE,"global_assignment","",-1);
+ }
+
+ @Test public void rejectsFinalGlobal() {
+ try {
+ new CodeGen("val value=1; val set={ -> value=2; }; return set();")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Assigned a final global");
+ } catch( Parser.ParseException e ) {
+ assertEquals("Cannot reassign final 'value'",e.getMessage());
+ }
+ }
+
+ @Test public void rejectsIncompatibleGlobalValue() {
+ try {
+ new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Stored an object in an integer global");
+ } catch( Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type"));
+ }
+ }
+}
diff --git a/chapter29/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter29/src/test/java/com/seaofnodes/simple/ReceiverTest.java
new file mode 100644
index 00000000..0342d9a2
--- /dev/null
+++ b/chapter29/src/test/java/com/seaofnodes/simple/ReceiverTest.java
@@ -0,0 +1,94 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ReceiverTest {
+ @Test public void classAndInstanceFields() throws Exception {
+ String source="""
+ int total=1;
+ val forward={ -> late(); };
+ val early={ -> total; };
+ val late={ -> early(); };
+ val add_noInline={int n -> self.total=self.total+n; return total;};
+ val read_noInline={ -> self.total; };
+ val nested={ ->
+ val inc={ -> self.total++; };
+ inc();
+ return total;
+ };
+ struct Counter {
+ int total=100;
+ val read=read_noInline;
+ };
+ struct Writer {
+ int count=2;
+ val step={ -> self.count++; total=count; return total; };
+ };
+ u16[] !table=new u16[2];
+ val lookup={u8 c -> c<2 ? table[c] : 0;};
+ val main={ ->
+ total=1;
+ table=new u16[2]; table[0]=7; table[1]=9;
+ if( forward()!=1 ) return 4;
+ if( lookup(1)!=9 || lookup(2)!=0 ) return 5;
+ if( add_noInline(5)!=6 || nested()!=7 ) return 1;
+ val counter=new Counter;
+ if( counter.read()!=7 || counter.total!=100 ) return 2;
+ val a=new Writer, b=new Writer;
+ if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3;
+ return 0;
+ };
+ return main();
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(source,"class_instance_receivers","",-1);
+ }
+
+ @Test public void importedCallbackKeepsItsClass() throws Exception {
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"classes-");
+ new CodeGen(null,lib.toString(),null,"Owner",
+ "int value=7; val get_noInline={ -> self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),null,"Forwarder",
+ "int value=99; val apply_noInline={ {int} action -> action()+self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ String source="return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;";
+ CodeGen code=new CodeGen(null,null,paths,"ReceiverClient",source,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ TestC.run(source,"imported_receivers",paths,TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void classReceiverHasNoNativeArgument() throws Exception {
+ String source="""
+ int base=10;
+ val calc={i64 a,i64 b,i64 c,i64 d,i64 e,i64 f,i64 g ->
+ self.base+a+2*b+3*c+4*d+5*e+6*f+7*g;
+ };
+ val callback_noInline={i64 n -> self.base+n;};
+ { {i64 -> i64} i64 -> i64 } invoke="C";
+ val viaC={i64 n -> invoke(callback_noInline,n);};
+ """;
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path driver=build.resolve("native_receiver.c");
+ Files.writeString(driver,"""
+ typedef long long (__attribute__((CALL_CONV)) *action_t)(long long);
+ __attribute__((CALL_CONV)) long long invoke(action_t action, long long n) { return action(n); }
+ __attribute__((CALL_CONV)) extern long long calc(long long,long long,long long,long long,long long,long long,long long);
+ __attribute__((CALL_CONV)) extern long long viaC(long long);
+ int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; }
+ """);
+ TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION,
+ TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1);
+ }
+}
diff --git a/chapter30/README.md b/chapter30/README.md
index 2e172e33..d8e32f80 100644
--- a/chapter30/README.md
+++ b/chapter30/README.md
@@ -12,6 +12,9 @@ squares are rejected, and play ends with a win or draw.
Runnable programs, including sorting, file I/O, and shortest-path examples,
live in [`docs/examples`](docs/examples/).
+This snapshot retains [chapter 28a's shared class receiver](../chapter28a/README.md#globals-use-the-same-receiver-as-fields)
+and chapter 28b's imported-callback handling.
+
## Terminal input and diagnostics
[`sys.io.getch()`](src/main/smp/sys/io.smp) reads one byte without waiting for
diff --git a/chapter30/docs/30-grammar.md b/chapter30/docs/30-grammar.md
index 189a7c04..7ff7b024 100644
--- a/chapter30/docs/30-grammar.md
+++ b/chapter30/docs/30-grammar.md
@@ -60,6 +60,7 @@ constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
+// Global functions use their owning class singleton as self.
// Function types and expressions both receive their implicit receiver here.
methodDeclaration : 'val' bindingModifier? memberName '=' functionExpression ';' ;
memberName : IDENTIFIER | primitiveType ;
@@ -235,10 +236,10 @@ one-pass IR builder:
- A statement beginning with `{` might be a block or a function-type binding.
`Declarations` and `Types` use speculative parsing and cursor restore;
qualified type lookup also stops before a suffix that belongs to an expression.
-- Bare assignment, field assignment, and compound updates share the grammar's
- precedence but use different IR paths. `References` decides between an SSA
- local, a constructor field's local value, and an actual memory access. A
- function-valued field may also supply an implicit receiver to a call.
+- Bare fields resolve through their receiver, so reads, assignments, and
+ updates share the field-access path. Locals use SSA; class declarations
+ retain Scope values until initializer exit. Global functions receive their
+ owning class singleton as `self`; instance methods receive their object.
- `for` updates are scanned first and parsed after the body, where their effects
belong. Explicit constructor bodies are scanned first and parsed after field
discovery, so later fields have local slots. Both use `Lexer.skipTo`, which
diff --git a/chapter30/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter30/src/main/java/com/seaofnodes/simple/node/CallNode.java
index ac5e4eee..be142889 100644
--- a/chapter30/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter30/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -7,6 +7,7 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.codegen.Iter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeMemPtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
@@ -95,13 +96,14 @@ public class CallNode extends CFGNode {
// A broad scalar target can refine to a function pointer during Iter.
// It cannot yet promise that the call exposes nothing.
if( _type!=Type.CONTROL ) return TypeMem.BOT;
- if( !(fptr()._type instanceof TypeFunPtr) )
+ if( !(fptr()._type instanceof TypeFunPtr tfp) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns()-1; i++ )
+ // A class receiver belongs to the callee; the caller does not expose its class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ )
escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs);
}
@@ -179,7 +181,10 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx);
+ // Match the callee's declared receiver view, including forward fields.
+ Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
+ : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
+ ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
CodeGen.CODE.add(parm).addDef(def);
// Linking can happen during post-SCCP inlining. Keep an RPC
// Parm's cached finite set synchronized with its newly added
diff --git a/chapter30/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter30/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index f45c7325..af24a94b 100644
--- a/chapter30/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter30/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -122,7 +122,8 @@ public class PhiNode extends Node {
// Generic "pull down op"
Node progress;
- if( same_op() && (progress = drop_same_op()) != null )
+ Node op = factoringOp();
+ if( same_op(op) && (progress = drop_same_op(op)) != null )
return progress;
// If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the
@@ -158,10 +159,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -179,7 +198,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -197,21 +217,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp._inputs.add(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Do not introduce an operand Phi mixing incompatible type families.
diff --git a/chapter30/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter30/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index eee1c150..3ed63862 100644
--- a/chapter30/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter30/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -69,7 +69,7 @@ public class RegionNode extends CFGNode {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
for( int j=1; j<region.nIns(); j++ )
- phi.addDef(phi2==null ? phi.in(i) : phi2.in(j));
+ phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
}
}
diff --git a/chapter30/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter30/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index 483aab89..d0da3250 100644
--- a/chapter30/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter30/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -27,7 +27,7 @@ public class SummaryNode extends CFGNode implements MultiNode {
TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
mem = (TypeMem)mem.meet(_state.mem());
TypeMem outside = CodeGen.CODE._start.outside(this);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
return TypeTuple.make(_state.ctl(),mem,_state.ret());
}
@Override public Node idealize() { return null; }
@@ -36,9 +36,16 @@ public class SummaryNode extends CFGNode implements MultiNode {
if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START;
TypeMem mem = (TypeMem)_state.mem();
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs);
}
+ // A class receiver is supplied by the callee, not exposed by its caller.
+ // Actual uses which publish self are already represented in _state.
+ 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;
+ }
@Override boolean _upgradeType(HashMap<String,Type> types) {
TypeTuple state = (TypeTuple)_state.upgradeType(types);
if( state==_state ) return false;
diff --git a/chapter30/src/main/java/com/seaofnodes/simple/parser/Expressions.java b/chapter30/src/main/java/com/seaofnodes/simple/parser/Expressions.java
index 247d974e..e664f16c 100644
--- a/chapter30/src/main/java/com/seaofnodes/simple/parser/Expressions.java
+++ b/chapter30/src/main/java/com/seaofnodes/simple/parser/Expressions.java
@@ -36,6 +36,9 @@ final class Expressions {
{ P.pos(old); return parseExpression(); }
P.references.checkAssignment(def,site);
+ // All fields use the same receiver-based lvalue path.
+ if( P.references.fieldSelf(def)!=null )
+ { P.pos(old); return parseExpression(); }
return P.references.assign(def,parseAssignment());
}
diff --git a/chapter30/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter30/src/main/java/com/seaofnodes/simple/parser/Functions.java
index 5175acc6..9a7ed396 100644
--- a/chapter30/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter30/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -30,7 +30,7 @@ final class Functions {
BitSet finals = new BitSet();
Type self = P.types.implicitSelfType();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
P._lexer.skipWhiteSpace();
@@ -85,6 +85,10 @@ final class Functions {
P._lexer.skipWhiteSpace();
Lexer nameLoc=P.loc();
String id = P.requireId();
+ // Older free functions may explicitly name a source argument
+ // "self". It shadows the implicit class receiver, not its ABI slot.
+ if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" )
+ ids.set(0,"#self");
if( ids.find(id)!=-1 ) throw Parser.error("Duplicate parameter '"+id+"'",nameLoc);
ts .push(t ); // Push type/arg pairs
ids.push(id);
@@ -300,8 +304,16 @@ final class Functions {
// All args, "as-if" called externally
for( int i = 0; i<ids.length; i++ ) {
Type t = sig.arg(i);
+ // The body sees its owning class receiver. PTR remains in the
+ // signature as the ABI marker for a receiver with no machine slot.
+ if( i==0 && t==TypePtr.PTR ) {
+ TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj;
+ // A file can add globals after its struct declaration closes.
+ // Keep this view open until SCCP installs the completed class.
+ t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true);
+ }
// Args take a default input if called from Start/external-world
- Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(fun.defaultArg(i)).peephole()).peephole();
+ Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(i==0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i)).peephole()).peephole();
if( t instanceof TypeMemPtr ptr && ptr._partial ) parm = new ConstructNode(parm).peephole();
P._scope.define(ids[i], t, (i==0 && ids[0]=="self") || (finals!=null && finals.get(i)), parm, loc);
}
diff --git a/chapter30/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter30/src/main/java/com/seaofnodes/simple/parser/References.java
index 6335bad2..134fee90 100644
--- a/chapter30/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter30/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -93,23 +93,9 @@ final class References {
// Check for a function-escaping variable; these require true
// closures. Final constants are OK; final vars require a hidden var
// argument; not-final fields can just use an explicit struct arg.
- if( kx < fx && !P.structs.inExplicitConstructor() && // Out of scope
- !(var._final && rvalue._type.isConstant()) ) { // Not a final constant
- if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke)
- throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
-
- // var.idx==2 is self argument, 3 is args, 4 or more are now static globals
- if( var._idx >= 4 ) {
- // Read from global scope.
- // Surely a nicer way to get the top-level scope compile name?
- Var clzptr = P._scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) Parser.TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parseField( P.con( clztmp ), id,pre );
- //return parseField(_scope.in(2),id);
- }
- }
+ if( kx>0 && kx<fx && !P.structs.inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
// Check for assign-update, x += e0;
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
@@ -142,19 +128,6 @@ final class References {
}
Node assign(Var def, Node expr) {
- Node self = fieldSelf(def);
- if( self!=null ) {
- TypeStruct ts = P.types.latestStruct(((TypeMemPtr)self._type)._obj);
- Field fld = ts.field(def._name);
- Node val = expr.keep();
- Node lift = P.conversions.convertExpr(val,def.type());
- Node mem = P.construction.storeMemory(self).keep();
- Node st = new StoreNode(P.loc(),fld._fname,fld._alias,fld._t,P.ctrl(),mem,self,
- ConFldOffNode.make(ts,fld._fname),lift,P.construction.own(self)).peephole();
- P.construction.store(self,fld._alias,st,mem);
- mem.unkeep();
- return val.unkeep();
- }
String name = def._name;
// Lift expression, based on type
Type decl = def.type(); // Declared type
@@ -303,14 +276,27 @@ final class References {
return P._scope.in(P._scope.update(P._scope.var(selfx),null));
}
- // Fields are lvalues in memory, including inside their initializer and
- // explicit constructor. Scope slots retain declaration metadata only.
- private Node fieldSelf(Var var) {
- int kx = P._scope.kindx(var), fx = P._scope.enclosingFuncOrDecl();
+ // Find the receiver for a field lvalue. Instance initializers use memory;
+ // class declarations retain their Scope values until initializer exit.
+ Node fieldSelf(Var var) {
+ int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
- if( !(kind instanceof Kind.Func inst) || !FunNode.isInstance(inst._name) || var._idx<inst._lexSize+2 ) return null;
- if( kx==fx || kx+1==fx ) return defaultSelf();
- return null;
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && P._scope.enclosingFunction()==kx ) return null;
+ // Nested functions have their own receiver parameter. Resolve fields
+ // through it even across intervening function and block scopes.
+ Node self = defaultSelf();
+ Var receiver = P._scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
+ ptr._obj._name.equals(declared._obj._name) ) return self;
+ // An instance method can also name fields of its enclosing class.
+ // Use that declaration's receiver; normal folding handles its identity.
+ if( !FunNode.isClz(owner._name) ) return null;
+ // The enclosing declaration may have discovered more fields since
+ // creating its receiver. View that same receiver with its current type.
+ return P.peep(new ConvertNode(receiver.type().upgradeType(Parser.TYPES),P._scope.in(receiver)));
}
private void checkSharedFunction(Var v) {
diff --git a/chapter30/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter30/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 43057c00..ed4a54bd 100644
--- a/chapter30/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter30/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -201,4 +202,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = code.con(TypeInteger.BOT);
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter30/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter30/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index 273d76ba..226425ca 100644
--- a/chapter30/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter30/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -262,8 +262,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test
diff --git a/chapter30/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter30/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index c6d558eb..9106a212 100644
--- a/chapter30/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter30/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -386,8 +386,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test public void testStringExport() throws IOException {
@@ -531,7 +531,7 @@ val sieve = { int N ->
String sprimes = sb.p("]").toString();
// Compile, link against native C; expect the above string of primes to be printed out by C
- TestC.runC(src, "sieve", sprimes,344);
+ TestC.runC(src, "sieve", sprimes,216);
// Evaluate on RISC5 emulator; expect return of an array of primes in
// the simulated heap.
diff --git a/chapter30/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter30/src/test/java/com/seaofnodes/simple/Chapter22Test.java
index 9bebee23..305ebf98 100644
--- a/chapter30/src/test/java/com/seaofnodes/simple/Chapter22Test.java
+++ b/chapter30/src/test/java/com/seaofnodes/simple/Chapter22Test.java
@@ -302,17 +302,17 @@ val p = { u8[~] str ->
p("Hello, World!");
return 0;
""";
- TestC.runSF(src,"helloWorld", "Hello, World!",2);
+ TestC.runSF(src,"helloWorld", "Hello, World!",4);
// Evaluate on RISC5 emulator
- EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false);
+ EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false);
int trap = R5.step(100);
assertEquals(0,trap);
assertEquals(0,R5.regs[riscv.A0]);
assertEquals("Hello, World!",R5._stdout.toString());
// Evaluate on ARM emulator
- EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false);
+ EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false);
trap = arm.step(100);
assertEquals(0,trap);
assertEquals(0,arm.regs[0]);
diff --git a/chapter30/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter30/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
new file mode 100644
index 00000000..51ed10c6
--- /dev/null
+++ b/chapter30/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -0,0 +1,71 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.parser.Parser;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class GlobalAssignmentTest {
+ private static final String SOURCE = """
+ int value=1;
+ int writes=0;
+ u8 small=0;
+ val set={int n -> value=n; return value;};
+ val set_noInline={int n ->
+ if( n<0 ) value=3;
+ else value=n;
+ return value;
+ };
+ val rhs_noInline={ -> writes=writes+1; return value+1;};
+ val shadow={int value -> value=42; return value;};
+ struct Writer {
+ int seen;
+ new Writer={int n -> value=n; seen=value;};
+ };
+ struct InitWriter { int seen=(value=17); };
+ val main={ ->
+ if( set(5)!=5 || value!=5 ) return 1;
+ if( set_noInline(-1)!=3 || value!=3 ) return 2;
+ if( set_noInline(8)!=8 || value!=8 ) return 3;
+ int result=(value=rhs_noInline());
+ if( result!=9 || value!=9 || writes!=1 ) return 4;
+ value=writes=11;
+ if( value!=11 || writes!=11 ) return 5;
+ if( shadow(0)!=42 || value!=11 ) return 6;
+ int wide=(small=257);
+ if( wide!=257 || small!=1 ) return 7;
+ val constructed=new Writer(13);
+ if( value!=13 || constructed.seen!=13 ) return 8;
+ val initialized=new InitWriter;
+ // Default expressions run at declaration time, not per instance.
+ if( value!=13 || initialized.seen!=17 ) return 9;
+ return 0;
+ };
+ return main();
+ """;
+
+ @Test public void storesGlobalMemory() throws Exception {
+ assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(SOURCE,"global_assignment","",-1);
+ }
+
+ @Test public void rejectsFinalGlobal() {
+ try {
+ new CodeGen("val value=1; val set={ -> value=2; }; return set();")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Assigned a final global");
+ } catch( Parser.ParseException e ) {
+ assertEquals("Cannot reassign final 'value'",e.getMessage());
+ }
+ }
+
+ @Test public void rejectsIncompatibleGlobalValue() {
+ try {
+ new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Stored an object in an integer global");
+ } catch( Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type"));
+ }
+ }
+}
diff --git a/chapter30/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter30/src/test/java/com/seaofnodes/simple/ReceiverTest.java
new file mode 100644
index 00000000..d50ee28a
--- /dev/null
+++ b/chapter30/src/test/java/com/seaofnodes/simple/ReceiverTest.java
@@ -0,0 +1,94 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ReceiverTest {
+ @Test public void classAndInstanceFields() throws Exception {
+ String source="""
+ int total=1;
+ val forward={ -> late(); };
+ val early={ -> total; };
+ val late={ -> early(); };
+ val add_noInline={int n -> self.total=self.total+n; return total;};
+ val read_noInline={ -> self.total; };
+ val nested={ ->
+ val inc={ -> self.total++; };
+ inc();
+ return total;
+ };
+ struct Counter {
+ int total=100;
+ val read=read_noInline;
+ };
+ struct Writer {
+ int count=2;
+ val step={ -> self.count++; total=count; return total; };
+ };
+ u16[] !table=new u16[2];
+ val lookup={u8 c -> c<2 ? table[c] : 0;};
+ val main={ ->
+ total=1;
+ table=new u16[2]; table[0]=7; table[1]=9;
+ if( forward()!=1 ) return 4;
+ if( lookup(1)!=9 || lookup(2)!=0 ) return 5;
+ if( add_noInline(5)!=6 || nested()!=7 ) return 1;
+ val counter=new Counter;
+ if( counter.read()!=7 || counter.total!=100 ) return 2;
+ val a=new Writer, b=new Writer;
+ if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3;
+ return 0;
+ };
+ return main();
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(source,"class_instance_receivers","",-1);
+ }
+
+ @Test public void importedCallbackKeepsItsClass() throws Exception {
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"classes-");
+ new CodeGen(null,lib.toString(),null,"Owner",
+ "int value=7; val get_noInline={ -> self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),null,"Forwarder",
+ "int value=99; val apply_noInline={ {int} action -> action()+self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ String source="return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;";
+ CodeGen code=new CodeGen(null,null,paths,"ReceiverClient",source,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ TestC.run(source,"imported_receivers",paths,TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void classReceiverHasNoNativeArgument() throws Exception {
+ String source="""
+ int base=10;
+ val calc={int a,int b,int c,int d,int e,int f,int g ->
+ self.base+a+2*b+3*c+4*d+5*e+6*f+7*g;
+ };
+ val callback_noInline={int n -> self.base+n;};
+ { {int -> i64} int -> i64 } invoke="C";
+ val viaC={int n -> invoke(callback_noInline,n);};
+ """;
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path driver=build.resolve("native_receiver.c");
+ Files.writeString(driver,"""
+ typedef long long (__attribute__((CALL_CONV)) *action_t)(int);
+ __attribute__((CALL_CONV)) long long invoke(action_t action, int n) { return action(n); }
+ __attribute__((CALL_CONV)) extern long long calc(int,int,int,int,int,int,int);
+ __attribute__((CALL_CONV)) extern long long viaC(int);
+ int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; }
+ """);
+ TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION,
+ TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1);
+ }
+}
diff --git a/chapter31/Makefile b/chapter31/Makefile
index c9a398e8..6dba57fa 100644
--- a/chapter31/Makefile
+++ b/chapter31/Makefile
@@ -15,7 +15,9 @@ test_raw_sys := 25
# Convert chapter numbers to test files
test_raw0 := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_nums0))
test_raw1 := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_nums1))
-test_sys := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_sys) )
+# TimeTest uses sys and compiles a wide library. Keep it out of the catch-all
+# JVM, whose accumulated pooled types can exhaust this snapshot's 16-bit IDs.
+test_sys := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_sys) ) com.seaofnodes.simple.TimeTest
# All the 'src/test/java' files ending in 'Test'
test_cp0 := $(patsubst $(TST)/$(SIMPLE)/%.java,com.seaofnodes.simple.%,$(wildcard $(TST)/$(SIMPLE)/*Test.java))
# Minus raw0, raw1, alone tests
diff --git a/chapter31/README.md b/chapter31/README.md
index 57f5557c..7a758f77 100644
--- a/chapter31/README.md
+++ b/chapter31/README.md
@@ -10,6 +10,9 @@ octal parsing, move constant arrays into the ELF constant pool. We then write
a few games, with the drawing and game logic written in Simple.
+This snapshot retains [chapter 28a's shared class receiver](../chapter28a/README.md#globals-use-the-same-receiver-as-fields)
+and chapter 28b's imported-callback handling.
+
## Games and demos
All graphical demos support resizing. Canvas scales their base layouts and
diff --git a/chapter31/docs/31-grammar.md b/chapter31/docs/31-grammar.md
index 37300c46..ee8490a5 100644
--- a/chapter31/docs/31-grammar.md
+++ b/chapter31/docs/31-grammar.md
@@ -68,6 +68,7 @@ constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
+// Global functions use their owning class singleton as self.
// Function types and expressions both receive their implicit receiver here.
methodDeclaration : 'val' bindingModifier? memberName '=' functionExpression ';' ;
memberName : IDENTIFIER | primitiveType ;
@@ -254,10 +255,10 @@ one-pass IR builder:
- A statement beginning with `{` might be a block or a function-type binding.
`Declarations` and `Types` use speculative parsing and cursor restore;
qualified type lookup also stops before a suffix that belongs to an expression.
-- Bare assignment, field assignment, and compound updates share the grammar's
- precedence but use different IR paths. `References` decides between an SSA
- local, a constructor field's local value, and an actual memory access. A
- function-valued field may also supply an implicit receiver to a call.
+- Bare fields resolve through their receiver, so reads, assignments, and
+ updates share the field-access path. Locals use SSA; class declarations
+ retain Scope values until initializer exit. Global functions receive their
+ owning class singleton as `self`; instance methods receive their object.
- `for` updates are scanned first and parsed after the body, where their effects
belong. Explicit constructor bodies are scanned first and parsed after field
discovery, so later fields have local slots. Both use `Lexer.skipTo`, which
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 9e9c5224..9030d43d 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -7,6 +7,7 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.codegen.Iter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeMemPtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
@@ -95,14 +96,15 @@ public class CallNode extends CFGNode {
// A broad scalar target can refine to a function pointer during Iter.
// It cannot yet promise that the call exposes nothing.
if( _type!=Type.CONTROL ) return TypeMem.BOT;
- if( !(fptr()._type instanceof TypeFunPtr) )
+ if( !(fptr()._type instanceof TypeFunPtr tfp) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
if( Intrinsic.pure(this) ) return TypeMem.START;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns()-1; i++ )
+ // A class receiver belongs to the callee; the caller does not expose its class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ )
escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs);
}
@@ -180,7 +182,10 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx);
+ // Match the callee's declared receiver view, including forward fields.
+ Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
+ : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
+ ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
CodeGen.CODE.add(parm).addDef(def);
// Linking can happen during post-SCCP inlining. Keep an RPC
// Parm's cached finite set synchronized with its newly added
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index f45c7325..af24a94b 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -122,7 +122,8 @@ public class PhiNode extends Node {
// Generic "pull down op"
Node progress;
- if( same_op() && (progress = drop_same_op()) != null )
+ Node op = factoringOp();
+ if( same_op(op) && (progress = drop_same_op(op)) != null )
return progress;
// If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the
@@ -158,10 +159,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x only while matching mixed Phi arms. Do not
+ // expand the graph into Adds that would immediately strength-reduce again.
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode &&
+ addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -179,7 +198,8 @@ public class PhiNode extends Node {
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
+ n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -197,21 +217,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp._inputs.add(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Do not introduce an operand Phi mixing incompatible type families.
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index eee1c150..3ed63862 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -69,7 +69,7 @@ public class RegionNode extends CFGNode {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
for( int j=1; j<region.nIns(); j++ )
- phi.addDef(phi2==null ? phi.in(i) : phi2.in(j));
+ phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
}
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter31/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index 483aab89..d0da3250 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -27,7 +27,7 @@ public class SummaryNode extends CFGNode implements MultiNode {
TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
mem = (TypeMem)mem.meet(_state.mem());
TypeMem outside = CodeGen.CODE._start.outside(this);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
return TypeTuple.make(_state.ctl(),mem,_state.ret());
}
@Override public Node idealize() { return null; }
@@ -36,9 +36,16 @@ public class SummaryNode extends CFGNode implements MultiNode {
if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START;
TypeMem mem = (TypeMem)_state.mem();
TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = 2; i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs);
}
+ // A class receiver is supplied by the callee, not exposed by its caller.
+ // Actual uses which publish self are already represented in _state.
+ 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;
+ }
@Override boolean _upgradeType(HashMap<String,Type> types) {
TypeTuple state = (TypeTuple)_state.upgradeType(types);
if( state==_state ) return false;
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java
index ffc96f57..f791a34c 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Expressions.java
@@ -36,6 +36,9 @@ final class Expressions {
{ P.pos(old); return parseExpression(); }
P.references.checkAssignment(def,site);
+ // All fields use the same receiver-based lvalue path.
+ if( P.references.fieldSelf(def)!=null )
+ { P.pos(old); return parseExpression(); }
return P.references.assign(def,parseAssignment());
}
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
index 84bd509e..a7726521 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -36,7 +36,7 @@ final class Functions {
Type self = P.types.implicitSelfType();
if( P.structs.inStructDeclaration() ) self = self.makeRO();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
P._lexer.skipWhiteSpace();
@@ -130,6 +130,10 @@ final class Functions {
P._lexer.skipWhiteSpace();
Lexer nameLoc=P.loc();
String id = P.requireId();
+ // Older free functions may explicitly name a source argument
+ // "self". It shadows the implicit class receiver, not its ABI slot.
+ if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" )
+ ids.set(0,"#self");
if( ids.find(id)!=-1 ) throw Parser.error("Duplicate parameter '"+id+"'",nameLoc);
ts .push(t ); // Push type/arg pairs
ids.push(id);
@@ -359,6 +363,14 @@ final class Functions {
if( i == 0 && ids[0].equals("self") && !FunNode.isInit(funName) &&
!(sig.ret() instanceof TypeMem) && t instanceof TypeMemPtr ptr )
t = ptr.withAccess(false);
+ // The body sees its owning class receiver. PTR remains in the
+ // signature as the ABI marker for a receiver with no machine slot.
+ if( i==0 && t==TypePtr.PTR ) {
+ TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj;
+ // A file can add globals after its struct declaration closes.
+ // Keep this view open until SCCP installs the completed class.
+ t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true);
+ }
// Args take a default input if called from Start/external-world
Type seed = i == 0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i);
Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(seed).peephole()).peephole();
diff --git a/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
index 7724103e..91cf6859 100644
--- a/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter31/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -93,23 +93,9 @@ final class References {
// Check for a function-escaping variable; these require true
// closures. Final constants are OK; final vars require a hidden var
// argument; not-final fields can just use an explicit struct arg.
- if( kx < fx && !P.structs.inExplicitConstructor() && // Out of scope
- !(var._final && rvalue._type.isConstant()) ) { // Not a final constant
- if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke)
- throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
-
- // var.idx==2 is self argument, 3 is args, 4 or more are now static globals
- if( var._idx >= 4 ) {
- // Read from global scope.
- // Surely a nicer way to get the top-level scope compile name?
- Var clzptr = P._scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) Parser.TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parseField( P.con( clztmp ), id,pre );
- //return parseField(_scope.in(2),id);
- }
- }
+ if( kx>0 && kx<fx && !P.structs.inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
// Check for assign-update, x += e0;
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
@@ -144,19 +130,6 @@ final class References {
}
Node assign(Var def, Node expr) {
- Node self = fieldSelf(def);
- if( self!=null ) {
- TypeStruct ts = P.types.latestStruct(((TypeMemPtr)self._type)._obj);
- Field fld = ts.field(def._name);
- Node val = expr.keep();
- Node lift = P.conversions.convertExpr(val,def.type());
- Node mem = P.construction.storeMemory(self).keep();
- Node st = new StoreNode(P.loc(),fld._fname,fld._alias,fld._t,P.ctrl(),mem,self,
- ConFldOffNode.make(ts,fld._fname),lift,P.construction.own(self)).peephole();
- P.construction.store(self,fld._alias,st,mem);
- mem.unkeep();
- return val.unkeep();
- }
String name = def._name;
// Lift expression, based on type
Type decl = def.type(); // Declared type
@@ -305,19 +278,27 @@ final class References {
return P._scope.in(P._scope.update(P._scope.var(selfx),null));
}
- // Fields are lvalues in memory, including inside their initializer and
- // explicit constructor. Scope slots retain declaration metadata only.
- private Node fieldSelf(Var var) {
+ // Find the receiver for a field lvalue. Instance initializers use memory;
+ // class declarations retain their Scope values until initializer exit.
+ Node fieldSelf(Var var) {
int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
- if( !(kind instanceof Kind.Func inst) || !FunNode.isInstance(inst._name) || var._idx<inst._lexSize+2 ) return null;
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && P._scope.enclosingFunction()==kx ) return null;
// Nested functions have their own receiver parameter. Resolve fields
// through it even across intervening function and block scopes.
Node self = defaultSelf();
- Type owner = P._scope.var(inst._lexSize).type();
- if( self._type instanceof TypeMemPtr ptr && owner instanceof TypeMemPtr declared &&
+ Var receiver = P._scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
ptr._obj._name.equals(declared._obj._name) ) return self;
- return null;
+ // An instance method can also name fields of its enclosing class.
+ // Use that declaration's receiver; normal folding handles its identity.
+ if( !FunNode.isClz(owner._name) ) return null;
+ // The enclosing declaration may have discovered more fields since
+ // creating its receiver. View that same receiver with its current type.
+ return P.peep(new ConvertNode(receiver.type().upgradeType(Parser.TYPES),P._scope.in(receiver)));
}
private void checkSharedFunction(Var v) {
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter31/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 43057c00..ed4a54bd 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -201,4 +202,27 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
+
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean reduced : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
+ RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
+ Node p = code.con(TypeInteger.BOT);
+ Node i = init(new MinusNode(p));
+ Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1));
+ Node sum = init(new AddNode(i,p,(byte)1));
+ PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter31/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index 273d76ba..226425ca 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -262,8 +262,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter31/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index 14a091ac..bd2a453a 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -386,8 +386,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test public void testStringExport() throws IOException {
@@ -472,7 +472,8 @@ val test_sqrt = { flt x ->
}
};
""";
- TestC.runC(src, "newtonFloat", result, TestC.CALL_CONVENTION.equals("win64") ? 42 : 34);
+ // With the zero-input guard, both SystemV and win64 score 42.
+ TestC.runC(src, "newtonFloat", result, 42);
EvalRisc5 R5 = TestRisc5.build( src, "test_sqrt", 0, 10, false);
R5.fregs[riscv.FA0 - riscv.F_OFFSET] = 3.0;
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter31/src/test/java/com/seaofnodes/simple/Chapter22Test.java
index c9791de4..f9146ae6 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/Chapter22Test.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/Chapter22Test.java
@@ -302,17 +302,17 @@ val p = { u8[~] str ->
p("Hello, World!");
return 0;
""";
- TestC.runSF(src,"helloWorld", "Hello, World!",2);
+ TestC.runSF(src,"helloWorld", "Hello, World!",4);
// Evaluate on RISC5 emulator
- EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false);
+ EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false);
int trap = R5.step(100);
assertEquals(0,trap);
assertEquals(0,R5.regs[riscv.A0]);
assertEquals("Hello, World!",R5._stdout.toString());
// Evaluate on ARM emulator
- EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false);
+ EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false);
trap = arm.step(100);
assertEquals(0,trap);
assertEquals(0,arm.regs[0]);
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/Chapter23Test.java b/chapter31/src/test/java/com/seaofnodes/simple/Chapter23Test.java
index 8667c0bd..f1ad4898 100644
--- a/chapter31/src/test/java/com/seaofnodes/simple/Chapter23Test.java
+++ b/chapter31/src/test/java/com/seaofnodes/simple/Chapter23Test.java
@@ -279,7 +279,7 @@ return _s.peek('q');
CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck);
assertEquals("return Phi(Region,0,1);", code.print());
assertEquals("1", Eval2.eval(code, 0));
- testCPU(src,"x86_64_v2", "win64",23,null);
+ testCPU(src,"x86_64_v2", "win64",31,null);
};
@Test
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter31/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
new file mode 100644
index 00000000..51ed10c6
--- /dev/null
+++ b/chapter31/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -0,0 +1,71 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.parser.Parser;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class GlobalAssignmentTest {
+ private static final String SOURCE = """
+ int value=1;
+ int writes=0;
+ u8 small=0;
+ val set={int n -> value=n; return value;};
+ val set_noInline={int n ->
+ if( n<0 ) value=3;
+ else value=n;
+ return value;
+ };
+ val rhs_noInline={ -> writes=writes+1; return value+1;};
+ val shadow={int value -> value=42; return value;};
+ struct Writer {
+ int seen;
+ new Writer={int n -> value=n; seen=value;};
+ };
+ struct InitWriter { int seen=(value=17); };
+ val main={ ->
+ if( set(5)!=5 || value!=5 ) return 1;
+ if( set_noInline(-1)!=3 || value!=3 ) return 2;
+ if( set_noInline(8)!=8 || value!=8 ) return 3;
+ int result=(value=rhs_noInline());
+ if( result!=9 || value!=9 || writes!=1 ) return 4;
+ value=writes=11;
+ if( value!=11 || writes!=11 ) return 5;
+ if( shadow(0)!=42 || value!=11 ) return 6;
+ int wide=(small=257);
+ if( wide!=257 || small!=1 ) return 7;
+ val constructed=new Writer(13);
+ if( value!=13 || constructed.seen!=13 ) return 8;
+ val initialized=new InitWriter;
+ // Default expressions run at declaration time, not per instance.
+ if( value!=13 || initialized.seen!=17 ) return 9;
+ return 0;
+ };
+ return main();
+ """;
+
+ @Test public void storesGlobalMemory() throws Exception {
+ assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(SOURCE,"global_assignment","",-1);
+ }
+
+ @Test public void rejectsFinalGlobal() {
+ try {
+ new CodeGen("val value=1; val set={ -> value=2; }; return set();")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Assigned a final global");
+ } catch( Parser.ParseException e ) {
+ assertEquals("Cannot reassign final 'value'",e.getMessage());
+ }
+ }
+
+ @Test public void rejectsIncompatibleGlobalValue() {
+ try {
+ new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Stored an object in an integer global");
+ } catch( Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type"));
+ }
+ }
+}
diff --git a/chapter31/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter31/src/test/java/com/seaofnodes/simple/ReceiverTest.java
new file mode 100644
index 00000000..83bf6768
--- /dev/null
+++ b/chapter31/src/test/java/com/seaofnodes/simple/ReceiverTest.java
@@ -0,0 +1,93 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ReceiverTest {
+ @Test public void classAndInstanceFields() throws Exception {
+ String source="""
+ int total=1;
+ val forward={ -> late(); };
+ val early={ -> total; };
+ val late={ -> early(); };
+ val add_noInline={int n -> self.total=self.total+n; return total;};
+ val read_noInline={ -> self.total; };
+ val nested={ ->
+ val inc={ -> self.total++; };
+ inc();
+ return total;
+ };
+ struct Counter {
+ int total=100;
+ val read=read_noInline;
+ };
+ struct Writer {
+ int count=2;
+ val step={ -> self.count++; total=count; return total; };
+ };
+ val table=new u16[~2]{7,9};
+ val lookup={u8 c -> c<2 ? table[c] : 0;};
+ val main={ ->
+ total=1;
+ if( forward()!=1 ) return 4;
+ if( lookup(1)!=9 || lookup(2)!=0 ) return 5;
+ if( add_noInline(5)!=6 || nested()!=7 ) return 1;
+ val counter=new Counter;
+ if( counter.read()!=7 || counter.total!=100 ) return 2;
+ val a=new Writer, b=new Writer;
+ if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3;
+ return 0;
+ };
+ return main();
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(source,"class_instance_receivers","",-1);
+ }
+
+ @Test public void importedCallbackKeepsItsClass() throws Exception {
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"classes-");
+ new CodeGen(null,lib.toString(),null,"Owner",
+ "int value=7; val get_noInline={ -> self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),null,"Forwarder",
+ "int value=99; val apply_noInline={ {int} action -> action()+self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ String source="return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;";
+ CodeGen code=new CodeGen(null,null,paths,"ReceiverClient",source,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ TestC.run(source,"imported_receivers",paths,TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void classReceiverHasNoNativeArgument() throws Exception {
+ String source="""
+ int base=10;
+ val calc={int a,int b,int c,int d,int e,int f,int g ->
+ self.base+a+2*b+3*c+4*d+5*e+6*f+7*g;
+ };
+ val callback_noInline={int n -> self.base+n;};
+ { {int -> i64} int -> i64 } invoke="C";
+ val viaC={int n -> invoke(callback_noInline,n);};
+ """;
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path driver=build.resolve("native_receiver.c");
+ Files.writeString(driver,"""
+ typedef long long (__attribute__((CALL_CONV)) *action_t)(int);
+ __attribute__((CALL_CONV)) long long invoke(action_t action, int n) { return action(n); }
+ __attribute__((CALL_CONV)) extern long long calc(int,int,int,int,int,int,int);
+ __attribute__((CALL_CONV)) extern long long viaC(int);
+ int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; }
+ """);
+ TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION,
+ TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1);
+ }
+}
diff --git a/chapter32/Makefile b/chapter32/Makefile
index af6da154..d91f59e0 100644
--- a/chapter32/Makefile
+++ b/chapter32/Makefile
@@ -30,13 +30,23 @@ test_cp := $(filter-out $(test_sys) ,$(test_cp4))
test_group0 := com.seaofnodes.simple.DrawTest
test_group1 := com.seaofnodes.simple.GraphicsTest
test_group2 := $(addprefix com.seaofnodes.simple.,TimeTest MemoryEncodingTest ChainedComparisonTest ParserTest Chapter28bTest)
-test_group3 := $(addprefix com.seaofnodes.simple.,StringFormatTest FinalConstructionTest PartialReadTest EscapeFlowTest CallEndTest BulkMemPhiTest)
-test_group4 := $(addprefix com.seaofnodes.simple.,BreakoutTest ArithNodeTest PhaseTest MethodAccessTest Int32Test MinusNodeTest ConstructorCompletionTest)
-test_group5 := $(addprefix com.seaofnodes.simple.,TerminalInputTest ParserDiagnosticTest StaticDataTest ArrayInitTest MethodFieldsTest ConstantArrayTest BoundaryTest IntegerLiteralTest ConstructionRequirementsTest)
-test_group6 := $(addprefix com.seaofnodes.simple.,AssemblyDumpTest AudioTest MathTest TicTacToeTest SelectiveLoadingTest FloatComparisonNativeTest SchedulingTest SeparateCompilationTest ConstructionGroupTest CompoundAssignmentTest)
+test_group3 := $(addprefix com.seaofnodes.simple.,StringFormatTest StaticDataTest PhaseTest FinalConstructionTest PartialReadTest EscapeFlowTest CallEndTest BulkMemPhiTest)
+test_group4 := $(addprefix com.seaofnodes.simple.,BreakoutTest ConvertNodeTest ArithNodeTest MethodAccessTest Int32Test MinusNodeTest ConstructorCompletionTest)
+test_group5 := $(addprefix com.seaofnodes.simple.,TerminalInputTest ParserDiagnosticTest ArrayInitTest MethodFieldsTest ConstantArrayTest BoundaryTest IntegerLiteralTest ConstructionRequirementsTest)
+test_group6 := $(addprefix com.seaofnodes.simple.,AssemblyDumpTest AudioTest MathTest TicTacToeTest ModTest SelectiveLoadingTest FloatComparisonNativeTest SchedulingTest SeparateCompilationTest ConstructionGroupTest CompoundAssignmentTest)
test_group7 := $(filter-out $(test_group0) $(test_group1) $(test_group2) $(test_group3) $(test_group4) $(test_group5) $(test_group6),$(test_cp))
test_groups := $(addprefix tests_group,0 1 2 3 4 5 6 7)
+# Fast compiler checks retain the full lattice, chapter/backend regressions,
+# fuzzer regression seeds, and focused compiler tests. Library/application and
+# CLI integration remains in `tests`. New compiler tests join sanity group 2.
+sanity_omit := $(addprefix com.seaofnodes.simple.,DrawTest GraphicsTest TimeTest StringFormatTest BreakoutTest TerminalInputTest AudioTest MathTest TicTacToeTest StreamIOTest RuntimeArgsTest NativeExecutionTest ParserDiagnosticTest)
+sanity_cp := $(filter-out $(sanity_omit),$(test_cp))
+sanity_group0 := $(addprefix com.seaofnodes.simple.,ClassInitDependenciesTest ConvertNodeTest ArithNodeTest MemoryEncodingTest ModTest IntrinsicTest AssemblyDumpTest)
+sanity_group1 := $(addprefix com.seaofnodes.simple.,StaticDataTest FloatComparisonNativeTest ArrayInitTest ConstantArrayTest BoundaryTest Int32Test ReceiverTest GlobalAssignmentTest IncrementalBuildTest SeparateCompilationTest)
+sanity_group2 := $(filter-out $(sanity_group0) $(sanity_group1),$(sanity_cp))
+sanity_groups := $(addprefix sanity_group,0 1 2)
+
# Size each test JVM for a share of the machine, instead of giving every JVM
# JIT and GC pools sized for all cores. Absolute paths also serve child JVMs
# launched from a group's private working directory (native Java on Windows).
@@ -158,6 +168,15 @@ $(test_groups): tests_group%: $(test_classes) $(TEST_SYS) $(RELEASE_SYS) $(RELEA
@echo "testing $@: $(test_group$*)"
@cd build/tests/$@ && $(TEST_JVM) org.junit.runner.JUnitCore $(test_group$*)
+.PHONY: sanity $(sanity_groups)
+$(sanity_groups): sanity_group%: $(test_classes) $(TEST_SYS) $(RELEASE_SYS) $(RELEASE_CRT)
+ @$(TEST_JVM) com.seaofnodes.simple.TestWorkspace $@ $(CPU_ABI)
+ @echo "testing $@: $(sanity_group$*)"
+ @cd build/tests/$@ && $(TEST_JVM) org.junit.runner.JUnitCore $(sanity_group$*)
+
+sanity: $(sanity_groups) tests_raw0 tests_raw1 fuzzer tests_lattice0 tests_lattice1 tests_lattice2 tests_lattice3
+ @echo "All sanity checks passed"
+
# One test method (or the whole class when METHOD is omitted).
CLASS ?= Chapter25Test
METHOD ?=
@@ -165,7 +184,9 @@ METHOD ?=
test: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
@$(TEST_JVM) com.seaofnodes.simple.TestRunner "$(CLASS)" "$(METHOD)"
-tests: $(test_groups) tests_sys fuzzer tests_alone tests_raw1 tests_raw0
+# At -j8, start the remaining chapter cohorts before the short lattice parts
+# so their native links overlap the earlier groups instead of forming a tail.
+tests: $(test_groups) tests_sys fuzzer tests_raw1 tests_raw0 tests_alone
@echo "All tests passed"
diff --git a/chapter32/README.ja.md b/chapter32/README.ja.md
index ac57b417..30d3c26c 100644
--- a/chapter32/README.ja.md
+++ b/chapter32/README.ja.md
@@ -15,6 +15,12 @@
- 高価な検証の既定値を log 8 から log 10 に変更し、インライン化の各途中段階で繰り返していたスケジュール検証を削減します。
- 外部状態を読む依存関係を不透明な引数に限定し、定数引数の削除による無関係な利用側への通知を減らします。
呼び出しの切り離しで変更したパラメータは明示的に再処理します。
+- IFG の live-out マップと作業領域を関数ごとに持ち、スピルによる再試行の間だけ再利用します。
+ 過去のコンパイルの基本ブロックを保持し続けることがなくなります。
+ スピル候補の評価に使う関数の大きさも、彩色の試行ごとに一度だけ計算します。
+- ロードを命令に組み込めるか調べる走査では、訪問済みノードを ID の BitSet で管理します。
+ パック値のヒストグラムはコメントアウトし、通常のコンパイルでは収集しません。
+ ELF の `.simple` セクションのサイズと内訳も測定し、今後の形式改善の基準にします。
測定ではワークリストからの peephole 呼び出しが約446万回から370万回へ、17.2%減少しました。
詳細な測定条件、実装の説明、残る調査対象は[英語版](README.md)を参照してください。
diff --git a/chapter32/README.md b/chapter32/README.md
index d7ca40db..6883d65f 100644
--- a/chapter32/README.md
+++ b/chapter32/README.md
@@ -4,9 +4,9 @@ English | [日本語](README.ja.md)
[Previous: Chapter 31 — Software Drawing, Time, and Graphical Games](../chapter31/README.md)
-Chapter 31 completes the graphics, games, and library work. This chapter keeps
+Chapter 31 completes the graphics, games, and library work. This chapter keeps
that language and those programs, then investigates the cost of compiling and
-testing them. Larger programs have made repeated graph walks, unnecessary
+testing them. Larger programs have made repeated graph walks, unnecessary
worklist visits, and uneven test parallelism visible in the test runtime.
The starting changes address four costs: test JVM scheduling, scratch-state
@@ -56,6 +56,89 @@ pair and triple. Separate processes also isolate the mutable type interning
and traversal state. A direct JUnit or IDE invocation still runs the complete
lattice test in one JVM; part zero of the Make run also runs the other type tests.
+## Reduce test overhead before reducing coverage
+
+The November 16 follow-up uses `make -j8 tests` as the normal run. On the same
+Windows/JDK 21 host, warm runs took 25.4–26.0 seconds; four workers took 30.5
+seconds and sixteen took 33.1. More concurrent JVMs did not help. Keep the
+two-processor JVM sizing and distinguish warm testing from rebuilding the
+compiler and released library.
+
+The serial attribution run spent 29.8 seconds in 153 GCC calls, mostly linking,
+and 29.7 seconds in compiler phases. These are summed serial costs, not portions
+of the parallel elapsed time. Four changes reduce work while retaining the
+existing test methods and their value checks:
+
+* [TypeTest](src/test/java/com/seaofnodes/simple/TypeTest.java) constructs lattice
+ assertion messages only when the identity comparison fails. Formatting types
+ inside every successful triple was more expensive than the comparison. The
+ standalone lattice fell from 10.6 to 4.5 seconds, with all pairs and triples
+ still checked.
+* [ModTest](src/test/java/com/seaofnodes/simple/ModTest.java) puts its native
+ division/remainder matrix into constant arrays and loops. All 200 checks,
+ including zero divisors and signed overflow, remain. This avoids compiling a
+ long chain of calls and conditional returns; the isolated test fell from
+ 2.75 to 0.62 seconds.
+* [StringFormatTest](src/test/java/com/seaofnodes/simple/StringFormatTest.java)
+ shares three small native programs between compatible cases. Each original
+ test checks its own output, including embedded NULs and UTF-8 bytes. Separate
+ import, forward-reference, evaluator, and error tests remain. The class now
+ makes seven GCC calls instead of nineteen.
+* [AssemblyDumpTest](src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java)
+ compiles two small modules containing the real Canvas font declaration. It
+ still checks unit headings, all 96 glyphs, exported data aliases, and repeated
+ dumps without changing the active encoding. Drawing integration remains in
+ DrawTest; inspecting assembly no longer requires recompiling all of `sys`.
+
+The Make groups redistribute the now-cheaper formatting and assembly work and
+the tests accumulated in the fallback group. Remaining chapter cohorts start
+before the short lattice partitions so their native links can overlap earlier
+work. Rebalanced warm runs took 22.1 and 24.3 seconds and passed the same 819
+executions, including the three additional lattice partitions. Their mean is
+about 10% below the earlier baseline; individual parallel runs vary. Compiler
+verification remains enabled.
+
+## Keep the lattice in the fast checks
+
+`make -j8 sanity` retains the entire lattice, chapters 1–24's existing test
+cohorts, saved fuzzer regression seeds, and the focused compiler tests. Its
+three compiler groups have private native-output directories just like the
+full suite. New compiler test classes enter the last sanity group automatically.
+Warm runs on the same host took 8.77 and 8.85 seconds and passed 680 executions.
+`make -j8 tests` still runs all 819 executions.
+
+The fast set leaves graphics, audio, time, math-library, formatting, game, terminal, stream,
+runtime-argument, CLI-diagnostic, and native-harness integration in the full
+suite, along with Chapter25Test and the larger BrainFuck/MergeSort programs.
+It retains native execution for arithmetic, memory encoding, static data,
+receivers, separate compilation, incremental rebuilds, and the chapter backend
+tests. This selects a cheaper set of checks; it does not replace native
+execution with evaluator-only coverage. Full tests remain necessary when
+changing the omitted libraries, interfaces, or programs.
+
+The lattice itself now does less redundant work. It caches each pair's meet
+and join, computing both operand orders before checking commutativity. For
+associativity it visits `i <= j <= k`: `n(n+1)(n+2)/6` triples instead of `n^3`.
+For each triple it checks all six intermediate results:
+
+```
+(a & b) & c c & (a & b)
+(a & c) & b b & (a & c)
+(b & c) & a a & (b & c)
+```
+
+Once the original pairs commute, the six original associativity equalities
+connect these results in a cycle. Comparing all six to one common result
+checks the same property. Both operand orders involving an intermediate meet
+remain explicit: that intermediate type need not belong to the gathered set.
+Repeated operands are included, and all comparable-pair monotonicity checks
+remain. No random sampling or smaller type collection is used.
+
+The unpartitioned TypeTest now takes about 0.7 seconds, following the earlier
+reduction to roughly four seconds from lazy assertion messages. The existing
+four process partitions remain; in the warm sanity run each took 0.3–0.4
+seconds. Reducing duplicate operations made additional JVMs unnecessary.
+
## Shallow type queries need no recursive scratch state
[Type.isConstant and Type.isFinal](src/main/java/com/seaofnodes/simple/type/Type.java)
@@ -269,6 +352,300 @@ with every-step verification. Raw measurements, saved compiler classes, and
reproduction commands are in `build/memmerge-dense/`; verification logs are in
`build/test-profile/dense-final-*.log`.
+## Match interference scratch lifetime to function allocation
+
+[RegAlloc](src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java) already
+allocates one function at a time, retrying after spills before moving to the
+next function. But [IFG](src/main/java/com/seaofnodes/simple/codegen/IFG.java)'s
+static `BBOUTS` retained basic-block keys from every previous allocation, even
+across compilations. Each interference build cleared all their live-out maps.
+Repeated sys compiles added 2,558 keys apiece, making later compiles slower.
+
+Each function now creates an IFG instance. Its live-out maps, temporary live
+set, and worklist survive that function's spill retries and become unreachable
+when allocation returns. The shared interference bitsets still reuse capacity:
+they contain live-range numbers, with no references to compiler graphs.
+
+Risky spill scoring also repeatedly walked the function's scheduled blocks to
+compute the same area. Coloring now computes that area once, after coalescing,
+and passes the integer to the scoring routines. A later spill retry recomputes
+it because splitting can change the schedule. An assertion checks that the
+live ranges being colored belong to the current function.
+
+Compared with `b8bcd9c0`, median compile times through object export were:
+
+| Workload | Before | After | RegAlloc before / after |
+| --- | ---: | ---: | ---: |
+| sys library | 1,290 ms | 913 ms | 494 / 91 ms |
+| Clock | 537 ms | 279 ms | 274 / 27 ms |
+| Breakout | 1,007 ms | 609 ms | 428 / 51 ms |
+| Graphical tic-tac-toe | 1,362 ms | 292 ms | 1,113 / 40 ms |
+
+These are repeated compilations: six measured rounds after three warmups,
+alternating isolated baseline and changed compiler class loaders. Each workload
+starts with fresh loaders. The old implementation accumulates block keys even
+during warmup, so these gains depend on compilation history; they are not
+single-shot CLI startup measurements. Java 21 uses two active processors,
+assertions at log10, and a 256 MiB initial / 2 GiB maximum heap. Both compilers
+read the same sys objects; gcc, linking, and native execution are excluded.
+HelloWorld remains about 69 ms, within measurement noise.
+
+Peephole counts, code sizes, and spill counts match in every benchmark pair.
+The final 26 objects, including sys submodules, have identical `.text` bytes.
+The full non-graphical suite passes all 805 test executions at log8, including
+the native allocator checks. Benchmark sources, saved baseline classes, raw
+timings, and follow-up JFR recordings are in `build/ifg-profile/`; the suite log
+is `build/test-profile/ifg-full.log`.
+
+## Reduce allocation in load folding and packed writes
+
+The x86 [load-fold legality check](src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java)
+walks the other operand's inputs to ensure that combining it with a load cannot
+move the read across a conflicting write. Its visited set now uses node IDs in
+a local BitSet. The traversal, including control dependencies, is unchanged;
+the check avoids growing arrays of identity-map keys and values.
+
+[BAOS](src/main/java/com/seaofnodes/simple/util/BAOS.java)'s packed-value
+histogram was exploratory instrumentation for choosing smaller encodings.
+Its map and updates are commented out, ready to restore for another packing
+study. Normal compilation no longer boxes histogram keys and counts. Packed
+bytes and their readers are unchanged.
+
+Against `6643e8fd`, an interleaved comparison measured sys compiler-thread
+allocation falling from 119.6 to 69.4 MiB and median compile time from 1,017 to
+942 ms. Breakout fell from 54.5 to 43.6 MiB and 652 to 617 ms. The smaller timing
+differences were mixed: Clock measured 315 to 318 ms, graphical tic-tac-toe
+292 to 291 ms, and HelloWorld 65 to 64 ms. All five allocate less. These use the
+same three-warmup, six-measurement method and JVM settings as the IFG comparison.
+All 26 resulting objects have byte-identical `.text` and `.simple` sections.
+The Windows suite at log8 and the Linux suite at the default log10 each pass
+all 805 test executions, including native scheduling and import coverage.
+
+## Measure serialized IR size before changing its packing
+
+The ELF `.simple` section stores reloadable ideal IR, declarations, and import
+metadata. It can be much larger than the native code. For the same x86-64/win64
+objects, including all 22 sys modules:
+
+| Workload | Whole ELF bytes | `.simple` bytes | Share of ELF |
+| --- | ---: | ---: | ---: |
+| sys library, all modules | 597,399 | 469,881 | 78.7% |
+| Clock | 64,317 | 43,854 | 68.2% |
+| Breakout | 118,163 | 80,950 | 68.5% |
+| Graphical tic-tac-toe | 64,605 | 44,353 | 68.7% |
+| HelloWorld | 16,355 | 14,635 | 89.5% |
+
+Temporary byte-offset counters around [Serialize](src/main/java/com/seaofnodes/simple/codegen/Serialize.java)'s
+existing write stages divide sys's payload into 67,844 bytes of strings and
+unit metadata, 73,564 of identity mappings, 180,456 of types, 2,447 of function
+summaries, and 145,482 of node records and input references, plus 88 header
+bytes. HelloWorld's strings, mappings, and types alone take 14,161 of its 14,635
+bytes; its graph records and inputs take only 447 bytes.
+
+The broad metadata footprint warrants a separate investigation. The current
+writer emits the full compilation's alias, function, and
+return-PC mappings into each object, along with their names. Restricting them
+to identities needed by that object's declarations, summaries, and graph may
+save space, but requires coordinated remapping in the writer and reader.
+Those measurements made no packing or format changes. Profiling helpers,
+saved baseline classes, per-object sizes, byte breakdowns, and timings are in
+`build/packing-profile/`.
+
+### Which packed fields have avoidable overhead?
+
+A deeper byte-count pass on `c21026c5` found three localized candidates:
+
+| Candidate | Modeled saving across sys | Clock | Breakout |
+| --- | ---: | ---: | ---: |
+| Unsigned varints for type-child IDs | 40,137 bytes | 2,757 | 3,561 |
+| Sparse serialized MemMerge inputs | 34,280 bytes | 7,133 | 12,683 |
+| Extend singleton function-ID encoding beyond ID 63 | 23,441 bytes | 1,140 | 1,409 |
+
+At that baseline, type-child IDs used `packed4`: IDs 128 through 16,383 took five bytes
+where an unsigned varint would take two. [MemMerge](src/main/java/com/seaofnodes/simple/node/MemMergeNode.java)
+was dense in memory, but its serialized representation retained the old alias
+slot space; sys's MemMerge input data contained 36,138 zero bytes for default
+slots. The sparse model keeps the first two inputs and encodes a non-default
+count plus `(alias, node ID)` pairs, including the extra count/pair cost.
+[TypeFunPtr](src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java) had a
+compact singleton form for non-null functions with fewer than six arguments,
+but only below function ID 64. Larger singleton IDs became mostly-zero bitsets.
+
+These estimates concern disjoint fields and together amount to about 21% of
+sys's `.simple` payload, 25% of Clock's, and 22% of Breakout's. The implementation
+and actual measurements follow below. A generic signed-varint substitution is not equivalent:
+zigzag encoding would make ordinary ASCII characters 64 through 127 larger.
+
+The metadata scan also explains HelloWorld's size. One constant pointing to
+`class:sys` reaches 672 of its 700 serialized types, including unrelated
+namespace members. Consequently, 363 of its 364 alias-map rows are referenced
+by the current type representation. Dropping those rows alone is insufficient;
+imported-type references or more selective namespace types need investigation.
+Return-PC tables are a clearer candidate: only 214 of 7,788 RPC rows written
+across sys objects are referenced by the serialized types, nodes, and summaries.
+
+Adding a general XInt dictionary is less promising: storing unique existing
+encodings plus references is already slightly larger across sys, before table
+headers. The singleton encoding addresses the common case more directly.
+Detailed field counts, size models, and reproduction helpers are in
+`build/simple-size/`. The instrumented exports preserve `.text` and `.simple`
+bytes in all 27 measured objects; that investigation changed no format.
+
+## Pack the serialized IR more tightly
+
+[BAOS.packed4](src/main/java/com/seaofnodes/simple/util/BAOS.java) now uses
+signed zigzag varints: -64 through 63 fit in one byte, -8192 through 8191 in
+two, and the full signed int range takes at most five bytes. Each byte carries
+seven payload bits and a continuation bit. Strings use a packed byte length
+followed by raw UTF-8, keeping ordinary ASCII at one byte per character.
+
+MemMerge writes its control/default inputs and explicit `(alias, node ID)`
+pairs, omitting default holes. It retains the old alias extent separately
+because that value still affects folding eligibility. The reader remaps each
+explicit alias into the importing compilation. Non-null singleton function
+types with fewer than six arguments now use the compact form through function
+ID 65535, with the matching `packed2` reader.
+
+Actual `.simple` sizes against `c21026c5`, including all 22 sys objects:
+
+| Workload | Before, bytes | After, bytes | Reduction |
+| --- | ---: | ---: | ---: |
+| sys library | 469,881 | 368,694 | 21.5% |
+| Clock | 43,854 | 31,906 | 27.2% |
+| Breakout | 80,950 | 62,139 | 23.2% |
+| Graphical tic-tac-toe | 44,353 | 35,961 | 18.9% |
+| HelloWorld | 14,635 | 11,523 | 21.3% |
+
+Across these 26 objects, the payload falls from 653,673 to 510,223 bytes,
+saving 143,450 bytes (21.9%). Sys's type records and child IDs shrink from
+180,456 to 116,948 bytes; node inputs shrink from 85,189 to 50,635. Together
+those two chunks account for 96.9% of sys's saving. Identity mappings remain
+73,564 bytes, leaving the metadata questions above for another pass.
+
+Compile timings are mixed. Baseline/new median milliseconds were sys
+1,056/1,065, Clock 335/352, Breakout 689/674, graphical tic-tac-toe 282/283,
+and HelloWorld 69/68. There is no consistent speed win in this run. The
+comparison alternates two isolated compiler class loaders, with three warmups
+and six measured rounds per workload, Java 21, two active processors, log10
+assertions, and a 256 MiB initial / 2 GiB maximum heap. Each compiler reads
+its own freshly generated sys objects. Linking and execution are excluded.
+
+Every pair has matching peephole/no-progress counts, code sizes, and spill
+metrics. All 26 `.text` sections are byte-identical. New tests cover signed
+integer boundaries and overflow, Unicode strings, singleton function IDs,
+sparse memory imports beyond alias 255, and rejection of the old format.
+The Windows suite at log8 and Linux suite at log10 each pass 811 test executions.
+Raw measurements, byte breakdowns, helpers, and saved baseline classes are in
+`build/format-profile/`.
+
+The object header changes from `C0DE` to `C0D2`. Existing `.simple` objects
+must be rebuilt; an old header produces an explicit rebuild error. For an
+existing chapter32 build, `make clean` followed by `make -j 8 release` rebuilds
+the generated artifacts. Rebuild any separately maintained Simple libraries too.
+
+## Receiver backport and spill investigation
+
+The shared class receiver is taught in
+[chapter 28a](../chapter28a/README.md#globals-use-the-same-receiver-as-fields),
+with imported summaries in [chapter 28b](../chapter28b/README.md).
+Those fixes are carried through the later snapshots. Phi factoring after
+strength reduction starts in
+[chapter 5](../chapter05/README.md#factoring-after-strength-reduction), using
+multiply-by-two there and shift-by-one where that representation is introduced.
+
+The receiver investigation also exposed a missed notification in
+[RegionNode](src/main/java/com/seaofnodes/simple/node/RegionNode.java): flattening
+regions adds Phi inputs, so their definitions must be queued too. A newly added
+precise memory user can require its bulk-memory input to split immediately.
+That prerequisite accompanies the receiver backport.
+
+The following measurements describe the chapter32 investigation before backporting.
+
+Validation: all 817 test executions pass on Windows with log8 verification and
+Linux with the default log10. A focused 62-test run passes with log1, checking
+every progress step. Native callbacks, imported receivers, FileIO, and ARM/RISC-V
+execution remain covered.
+
+There is a compilation/code-size cost to review. The following Windows comparison
+uses the preceding uncommitted assignment fix as its baseline, assertions enabled,
+two JVM processors, seed 456, and each compiler's freshly built libraries. Times
+are medians of four warm rounds after discarding the first round; this is a small
+local sample, not a timing guarantee. Sys sizes sum its 22 object files.
+
+| Compile | Time, ms (before → after) | Peepholes (before → after) | `.text` bytes (before → after) |
+| --- | ---: | ---: | ---: |
+| sys | 961 → 977 | 185,960 → 208,552 | 37,725 → 40,355 |
+| Clock | 256 → 381 | 86,873 → 106,615 | 6,717 → 7,053 |
+| Breakout | 553 → 593 | 158,712 → 174,500 | 14,868 → 15,031 |
+| TicTacToe | 161 → 177 | 56,222 → 63,774 | 4,251 → 4,411 |
+
+The small String and HelloWorld examples also retain additional initialization
+checks, and their spill expectations have been updated. The receiver-only change
+exposed an existing ordering sensitivity in Sieve: across seeds 120–127, both
+compilers produced seven 28-split/343-weight results and one 26-split/215-weight
+result, with the smaller result moving from seed 126 to 121.
+
+The spill investigation separates compile time from generated moves: Clock's
+weighted split score improves from 785 to 762. These scores count all retained
+SplitNodes, including register copies, with weight `8^loopDepth`; they are not
+counts of stack spills. Sieve's 215-to-343 change is two extra register copies
+inside its depth-two loop. Early `p+p` strength reduction in
+[AddNode](src/main/java/com/seaofnodes/simple/node/AddNode.java) turns the entry
+value into `p<<1` before [PhiNode](src/main/java/com/seaofnodes/simple/node/PhiNode.java)
+can factor `Phi(p+p,i+p)` into `Phi(p,i)+p`.
+
+Phi factoring now views `x<<1` as `x+x` when matching mixed Add/Shl arms. It uses
+the existing factoring checks and trial graph, without expanding a shift into
+an Add that would immediately strength-reduce again. Pure shift arms retain
+ordinary shift factoring. Multiply-by-two already reduces to this shift, so it
+is covered too. This is a local canonicalization: peeling one `x` from `k*x` for
+arbitrary k would require a new `(k-1)*x` expression, with less clear cost and
+rewrite-order benefits. The implementation stops at doubling.
+
+All eight Sieve seeds now produce 26 splits and score 215, with every-step
+verification; the spill expectation is 215. Direct graph tests check factoring
+before and after strength reduction, either arm order, and rejection of a
+different shift count. The 819-test Windows sweep passes with log8 verification
+(the Sieve group rerun after updating its expectation), and 64 focused tests
+pass with log1. Native and emulator Sieve results are checked too.
+
+The largest individual sys increase in the receiver-only comparison was
+`Canvas._circle`, from 455 to 517.
+Allocation keeps the loop-invariant boolean in a general register and the pixel
+pointer in an XMM register; recovering the pointer adds a transfer at each pixel
+store. The baseline makes the opposite choice. Both ranges receive the default
+score 1000 in [IFG.pickRiskyScore](src/main/java/com/seaofnodes/simple/codegen/IFG.java),
+leaving their selection sensitive to ordering. An isolated trial giving SetX86
+candidates one extra priority point brings `_circle` to 454 and total sys to
+8869, versus baseline 8719 and current 8932. Other sys functions' weighted scores
+are unchanged by that trial. This identifies an allocator sensitivity; the
+opcode-specific preference is diagnostic, not an adopted heuristic.
+
+With Phi factoring fixed, sys's weighted score is 8850 and `_circle` returns to
+455 through another ordering change. Clock stays at 762, Breakout changes from
+3387 to 3393, and TicTacToe stays at 1468. A bounded allocator follow-up tried
+three cheap refinements of the default score: breaking ties toward fewer excess
+neighbors (degree minus available colors), toward more excess neighbors, and a
+bonus for cheap single-def/single-use splits based on loop depth. Sys scored
+9039, 8844, and 8850 respectively; the three games were unchanged. The tiny
+six-point gain does not justify adopting the degree tie-break on this evidence.
+The production allocator remains unchanged; no additional graph walks or
+searches were added.
+
+Backporting retains each chapter's allocator. Code-quality expectations are
+therefore checked locally: chapter21's RISC-V Sieve score changes from 92 to
+164, despite the chapter32 improvement above, and chapter31's forward-field
+scanner test changes from 23 to 31 on x86-64/Win64. Execution checks remain in
+place; these earlier snapshots do not inherit the later allocator experiments.
+Chapter31 also groups `TimeTest` with its sys tests: its wide-library compile
+passes in a fresh JVM, but following the large catch-all suite exhausted that
+snapshot's existing 16-bit type IDs. This keeps the checks and the older type
+implementation intact; it does not remove the compiler's type-ID limit.
+
+The saved baseline, comparison drivers, measurements, and verification logs are
+under `build/receiver-profile/`. Proving initialization checks redundant is the
+main follow-up suggested by these measurements.
+
## Build and test
From `chapter32`, using the existing offline dependency caches:
diff --git a/chapter32/docs/32-grammar.md b/chapter32/docs/32-grammar.md
index 2628f566..4a794341 100644
--- a/chapter32/docs/32-grammar.md
+++ b/chapter32/docs/32-grammar.md
@@ -69,6 +69,7 @@ constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
// A method is an ordinary fixed function binding in a struct definition.
// The compiler supplies self; it is not written in parameterList.
// Function types and expressions both receive their implicit receiver here.
+// Global functions use their owning class singleton as self.
methodDeclaration : 'val' bindingModifier? memberName '=' functionExpression ';' ;
memberName : IDENTIFIER | primitiveType ;
@@ -254,10 +255,11 @@ one-pass IR builder:
- A statement beginning with `{` might be a block or a function-type binding.
`Declarations` and `Types` use speculative parsing and cursor restore;
qualified type lookup also stops before a suffix that belongs to an expression.
-- Bare assignment, field assignment, and compound updates share the grammar's
- precedence but use different IR paths. `References` decides between an SSA
- local, a constructor field's local value, and an actual memory access. A
- function-valued field may also supply an implicit receiver to a call.
+- `References` resolves bare fields through their receiver, so assignments,
+ reads, and updates share the field-access path. Locals use SSA; class
+ initializer declarations retain their Scope values until initializer exit.
+ Global functions receive their owning class singleton as `self`, including
+ when invoked through a callback. Instance methods receive their object.
- `for` updates are scanned first and parsed after the body, where their effects
belong. Explicit constructor bodies are scanned first and parsed after field
discovery, so later fields have local slots. Both use `Lexer.skipTo`, which
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/codegen/IFG.java b/chapter32/src/main/java/com/seaofnodes/simple/codegen/IFG.java
index 6ad7c0ad..a027263f 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/codegen/IFG.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/codegen/IFG.java
@@ -8,18 +8,20 @@ import java.util.BitSet;
import java.util.IdentityHashMap;
// Interference Graph
-abstract public class IFG {
+public class IFG {
// Interference Graph Support
+ // Scratch for one function, reused across its spill retries.
// Map from a Basic Block to Live-Out: {a map from a Live Range to a Def}
- private static final IdentityHashMap<CFGNode,IdentityHashMap<LRG,Node>> BBOUTS = new IdentityHashMap<>();
- static void resetBBLiveOut() {
- for( IdentityHashMap<LRG,Node> bbout : BBOUTS.values() )
+ private final IdentityHashMap<CFGNode,IdentityHashMap<LRG,Node>> _bbouts = new IdentityHashMap<>();
+ private void resetBBLiveOut() {
+ for( IdentityHashMap<LRG,Node> bbout : _bbouts.values() )
bbout.clear();
}
- static final IdentityHashMap<LRG,Node> TMP = new IdentityHashMap<>();
+ private final IdentityHashMap<LRG,Node> _tmp = new IdentityHashMap<>();
- // Inteference Graph: Array of Bitsets
+ // Interference Graph: Array of Bitsets. Reuse capacity across functions;
+ // these contain only live-range numbers, not references to the graph.
static final Ary<BitSet> IFG = new Ary<>(BitSet.class);
static void resetIFG() {
for( BitSet bs : IFG )
@@ -42,10 +44,10 @@ abstract public class IFG {
}
- private static final Ary<CFGNode> WORK = new Ary<>(CFGNode.class);
- static void pushWork(CFGNode bb) {
- if( WORK.find(bb) == -1 )
- WORK.push(bb);
+ private final Ary<CFGNode> _work = new Ary<>(CFGNode.class);
+ private void pushWork(CFGNode bb) {
+ if( _work.find(bb) == -1 )
+ _work.push(bb);
}
// ------------------------------------------------------------------------
@@ -65,20 +67,20 @@ abstract public class IFG {
// - At block head, "push" the new live-out to prior blocks.
// - - If they pick up new live-outs, put them on the worklist.
- public static boolean build( int round, RegAlloc alloc ) {
+ public boolean build( int round, RegAlloc alloc ) {
// Reset all to empty
resetBBLiveOut();
resetIFG();
- WORK.clear();
+ _work.clear();
// Last block has nothing live out
for( CFGNode bb : alloc._cfg )
if( bb.blockHead())
- WORK.push( bb );
+ _work.push( bb );
// Process blocks until no more changes
- while( !WORK.isEmpty() )
- do_block(round,alloc,WORK.pop());
+ while( !_work.isEmpty() )
+ do_block(round,alloc,_work.pop());
if( alloc.success() )
convert2DAdjacency(alloc);
@@ -86,12 +88,12 @@ abstract public class IFG {
}
// Walk one block backwards, compute live-in from live-out, and build IFG
- static void do_block( int round, RegAlloc alloc, CFGNode bb ) {
+ private void do_block( int round, RegAlloc alloc, CFGNode bb ) {
assert bb.blockHead();
- IdentityHashMap<LRG,Node> live_out = BBOUTS.get(bb);
- TMP.clear();
+ IdentityHashMap<LRG,Node> live_out = _bbouts.get(bb);
+ _tmp.clear();
if( live_out != null )
- TMP.putAll(live_out); // Copy bits to temp
+ _tmp.putAll(live_out); // Copy bits to temp
// A backwards walk over instructions in the basic block
for( int inum = bb.nOuts()-1; inum >= 0; inum-- ) {
@@ -118,14 +120,14 @@ abstract public class IFG {
mergeLiveOut(alloc,bb,0);
}
- private static void do_node(RegAlloc alloc, Node n) {
+ private void do_node(RegAlloc alloc, Node n) {
// Defining means killing live LRG
LRG lrg = alloc.lrg(n);
if( lrg != null ) {
// Check for def-side self-conflict live ranges. These must split,
// and only happens during the first round a particular LRG splits.
selfConflict(alloc,n,lrg);
- TMP.remove(lrg); // Kill def
+ _tmp.remove(lrg); // Kill def
}
// Phis use and define the same live range, i.e. these LRGs already
@@ -141,7 +143,7 @@ abstract public class IFG {
// Interfere n with all live
if( lrg!=null ) {
// Interfere n with all live
- for( LRG tlrg : TMP.keySet() ) {
+ for( LRG tlrg : _tmp.keySet() ) {
assert tlrg.leader();
// Skip self
if( lrg != tlrg &&
@@ -177,7 +179,7 @@ abstract public class IFG {
selfConflict(alloc,def,lrg1);
// All operands are live together, regardless of their input order.
- TMP.put(lrg1,def);
+ _tmp.put(lrg1,def);
}
// Check fixed-register uses after gathering every operand. An indirect
@@ -191,9 +193,9 @@ abstract public class IFG {
RegMask ni_mask = m.regmap(i);
if( ni_mask!=null && ni_mask.size1() ) { // Must-use single register
// Search all current live
- for( LRG tlrg : TMP.keySet() ) {
+ for( LRG tlrg : _tmp.keySet() ) {
assert tlrg.leader();
- Node live = TMP.get(tlrg);
+ Node live = _tmp.get(tlrg);
if( live != def && live instanceof MachNode lmach && lmach.outregmap().overlap(ni_mask) ) {
// Deny the register, since it absolutely must be used here
if( !tlrg.clr(ni_mask.firstReg()) )
@@ -210,15 +212,15 @@ abstract public class IFG {
// Single-register defines *must* have their register; other live ranges
// *must* avoid this register, so instead of interfering we remove the
// single register from the other rmask.
- private static void kills( RegAlloc alloc, MachNode m ) {
+ private void kills( RegAlloc alloc, MachNode m ) {
RegMask killMask = m.killmap();
if( killMask==null ) return;
// Kill registers with all live
- for( LRG tlrg : TMP.keySet() ) {
+ for( LRG tlrg : _tmp.keySet() ) {
assert tlrg.leader();
// Always, tlrg cannot use kills
if( tlrg._mask.overlap(killMask) ) {
- Node live = TMP.get(tlrg);
+ Node live = _tmp.get(tlrg);
// Disallow clone-ables from living across killed registers.
// Fail them and let splitting re-clone closer to the target use.
if( live instanceof MachNode mach && mach.isClone() )
@@ -231,8 +233,8 @@ abstract public class IFG {
// Check for self-conflict live ranges. These must split, and only happens
// during the first round a particular LRG splits.
- private static void selfConflict(RegAlloc alloc, Node n, LRG lrg) {
- selfConflict(alloc,n,lrg,TMP.get(lrg));
+ private void selfConflict(RegAlloc alloc, Node n, LRG lrg) {
+ selfConflict(alloc,n,lrg,_tmp.get(lrg));
}
private static void selfConflict(RegAlloc alloc, Node n, LRG lrg, Node prior) {
if( prior!=null && prior != n ) {
@@ -242,17 +244,17 @@ abstract public class IFG {
}
}
- // Merge TMP into bb's live-out set; if changes put bb on WORK
- private static void mergeLiveOut( RegAlloc alloc, CFGNode priorbb, int i ) {
+ // Merge _tmp into bb's live-out set; if changes put bb on _work
+ private void mergeLiveOut( RegAlloc alloc, CFGNode priorbb, int i ) {
CFGNode bb = priorbb.cfg(i);
if( bb == null ) return; // Start has no prior
while( !bb.blockHead() ) bb = bb.cfg0();
// Lazy get live-out set for bb
- IdentityHashMap<LRG, Node> lrgs = BBOUTS.computeIfAbsent( bb, k -> new IdentityHashMap<>() );
+ IdentityHashMap<LRG, Node> lrgs = _bbouts.computeIfAbsent( bb, k -> new IdentityHashMap<>() );
- for( LRG lrg : TMP.keySet() ) {
- Node def = TMP.get(lrg);
+ for( LRG lrg : _tmp.keySet() ) {
+ Node def = _tmp.get(lrg);
// Effective def comes from phi input from prior block
if( def instanceof PhiNode phi && phi.cfg0()==priorbb ) {
assert i!=0;
@@ -306,6 +308,9 @@ abstract public class IFG {
// If there's no spare color we'll have to spill this at-risk live range.
public static boolean color(int round, RegAlloc alloc) {
+ // Coalescing is finished; splitting may change this area next round.
+ FunNode fun = alloc._cfg.at(0).fun();
+ int functionArea = functionArea(fun,alloc);
int maxlrg = alloc._LRGS.length, nlrgs=0;
for( int i=1; i<maxlrg; i++ )
if( alloc._LRGS[i] != null )
@@ -325,6 +330,7 @@ abstract public class IFG {
for( int i=0, j=0; i<maxlrg; i++ ) {
LRG lrg = alloc._LRGS[i];
if( lrg==null ) continue; // Unified lrgs are null here
+ assert lrg._fun==fun;
color_stack[j++] = lrg;
if( lrg.lowDegree() ) swap(color_stack, swork++, j-1);
}
@@ -332,7 +338,7 @@ abstract public class IFG {
// Pull all lrgs from IFG, in trivial order if possible
while( sptr < color_stack.length ) {
// Swap best color up front
- pickColor(color_stack,sptr,swork,alloc);
+ pickColor(color_stack,sptr,swork,functionArea);
// Pick a trivial lrg, and (temporarily) remove from the IFG.
LRG lrg = color_stack[sptr++];
@@ -388,10 +394,10 @@ abstract public class IFG {
}
// Pick LRG from color stack
- private static void pickColor(LRG[] color_stack, int sptr, int swork, RegAlloc alloc) {
+ private static void pickColor(LRG[] color_stack, int sptr, int swork, int functionArea) {
// Out of trivial colorable, pick an at-risk to pull
if( sptr==swork )
- swap(color_stack,sptr,pickRisky(color_stack,sptr,alloc));
+ swap(color_stack,sptr,pickRisky(color_stack,sptr,functionArea));
// When coloring, we'd like to give more choices; so when coloring we'd
// like to see the single-def first (since no choices anyway), then
// non-split related (so more live ranges get colored), then
@@ -426,12 +432,12 @@ abstract public class IFG {
// Pick a live range that hasn't already spilled, or has a single-def-
// single-use that are not adjacent.
- private static int pickRisky( LRG[] color_stack, int sptr, RegAlloc alloc ) {
+ private static int pickRisky( LRG[] color_stack, int sptr, int functionArea ) {
int best=sptr;
- int bestScore = pickRiskyScore(color_stack[best],alloc);
+ int bestScore = pickRiskyScore(color_stack[best],functionArea);
for( int i=sptr+1; i<color_stack.length; i++ ) {
if( bestScore == 1000000 ) return best; // Already max score
- int iScore = pickRiskyScore(color_stack[i],alloc);
+ int iScore = pickRiskyScore(color_stack[i],functionArea);
if( iScore > bestScore )
{ best = i; bestScore = iScore; }
}
@@ -446,16 +452,16 @@ abstract public class IFG {
//
// Picking a live range that is very close to coloring might allow it to
// color despite being risky.
- private static int pickRiskyScore( LRG lrg, RegAlloc alloc ) {
+ private static int pickRiskyScore( LRG lrg, int functionArea ) {
// Callee-save live ranges cover the whole function and are cheap to
// split. Rank scheduled area recovered against the loop-scaled cost
// of the def- and use-side moves.
if( lrg._machDef instanceof CalleeSaveNode )
- return areaScore(functionArea(lrg._fun,alloc),
+ return areaScore(functionArea,
splitCost((Node)lrg._machDef,(Node)lrg._machUse));
if( lrg._splitDef != null && lrg._splitDef. in(1) instanceof CalleeSaveNode &&
lrg._splitUse != null && lrg._splitUse.out(0) instanceof ReturnNode )
- return areaScore(functionArea(lrg._fun,alloc),
+ return areaScore(functionArea,
splitCost(lrg._splitDef,lrg._splitUse));
// Pick single-def clonables that are not right next to their single-use.
@@ -465,7 +471,7 @@ abstract public class IFG {
Node use = ((Node)lrg._machUse);
CFGNode cfg = def.cfg0();
int area = cfg != use.cfg0()
- ? functionArea(lrg._fun,alloc)
+ ? functionArea
: cfg._outputs.find(use)-cfg._outputs.find(def)-1;
// A single-use function address can move next to its use without
// adding an instruction. Prefer that to saving a callee-save
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/chapter32/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
index 303fd355..c3be4b71 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
@@ -213,8 +213,9 @@ public class RegAlloc {
}
private void allocateFunction() {
+ IFG ifg = new IFG();
_deferredLoopSelf.clear();
- for( byte round=0; !graphColor(round); round++ ) {
+ for( byte round=0; !graphColor(round,ifg); round++ ) {
split(round);
if( round >= 10 ) {
FunNode fun = _cfg.at(0).fun();
@@ -281,7 +282,7 @@ public class RegAlloc {
return cfg==null ? null : cfg.fun();
}
- private boolean graphColor(byte round) {
+ private boolean graphColor(byte round, IFG ifg) {
_failed.clear();
_lrgs.clear();
_lrg_num = 1;
@@ -291,7 +292,7 @@ public class RegAlloc {
// Build Live Ranges
BuildLRG.run(round,this) && // if no hard register conflicts
// Build Interference Graph
- IFG.build(round,this) && // If no self conflicts or uncolorable
+ ifg.build(round,this) && // If no self conflicts or uncolorable
// Conservative coalesce copies
Coalesce.coalesce(round,this) &&
// Color attempt
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/chapter32/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
index e1aee9aa..9c43e029 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
@@ -103,8 +103,10 @@ public class Serialize {
Type startType = TypeTuple.make(Type.CONTROL,stopType.mem(),((StartNode)nodes.at(0)).arg());
BAOS baos = new BAOS();
- // A - Print the C0DE header. The format is not versioned yet.
- baos.write('C').write('0').write('D').write('E');
+ // 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');
// Count unique Types
var types = new HashMap<Type,Integer>();
@@ -265,10 +267,12 @@ public class Serialize {
}
// Write out the input indices packed.
for( Node n : nodes ) {
- int count = n instanceof MemMergeNode mem ? mem.packedSize() : n.nIns();
+ int count = n.nIns();
for( int j=0; j<count; j++ ) {
if( !writeInput(n,j,anodes) ) continue;
- Node def = n instanceof MemMergeNode mem ? mem.packedInput(j) : n.in(j);
+ if( n instanceof MemMergeNode mem && j>=2 )
+ baos.packed2(mem.aliasAt(j));
+ Node def = n.in(j);
Integer idx = def==null ? Integer.valueOf(0) : anodes.get(def);
// Imported function constants retain their symbol, not a body.
if( idx==null && n instanceof FunPtrNode && j==1 ) idx=0;
@@ -331,7 +335,7 @@ public class Serialize {
Type.TAGOFFS();
// A - Read a header
- if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='E' )
+ if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='2' )
throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file");
// B - Packed read of #strings, then strings
@@ -364,7 +368,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() != 'E' )
+ if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != '2' )
throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" );
// B - Packed read of #strings, then strings
@@ -503,14 +507,13 @@ public class Serialize {
for( Node n : nodes ) {
int len = n instanceof MemMergeNode mem ? mem.readSize() : n.nIns();
for( int i = 0; i<len; i++ ) {
+ int fileAlias = n instanceof MemMergeNode && i>=2 ? bais.packed2() : 0;
int idx = bais.packed2();
Node def = idx==0 ? null : nodes.at(idx-1);
- // MemMerge precise aliases are encoded by their input slot.
- // Remap populated file-local slots into this compilation's
- // local alias numbering; null holes carry no identity.
+ // Remap only explicit slices; omitted aliases use the default.
if( n instanceof MemMergeNode mem && i>=2 ) {
if( def==null ) continue;
- int alias = i>=GlobalBits.RESERVED ? aliases.map(fileAliases,i) : i;
+ int alias = aliases.map(fileAliases,fileAlias);
mem.alias(alias,def);
} else n.setDefX(i,def);
// Call's output[0] is always the CallEnd
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 3b2dc75b..5506621b 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -7,6 +7,7 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.codegen.Iter;
import com.seaofnodes.simple.type.Type;
+import com.seaofnodes.simple.type.TypePtr;
import com.seaofnodes.simple.type.TypeMemPtr;
import com.seaofnodes.simple.type.TypeFunPtr;
import com.seaofnodes.simple.type.TypeMem;
@@ -95,13 +96,15 @@ public class CallNode extends CFGNode {
// A broad scalar target can refine to a function pointer during Iter.
// It cannot yet promise that the call exposes nothing.
if( _type!=Type.CONTROL ) return TypeMem.BOT;
- if( !(fptr()._type instanceof TypeFunPtr) )
+ if( !(fptr()._type instanceof TypeFunPtr tfp) )
return fptr()._type.isHigh() ? TypeMem.START : TypeMem.BOT;
if( Intrinsic.pure(this) ) return TypeMem.START;
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
- for( int i = 2; i<nIns()-1; i++ ) {
+ // The class-receiver slot is absent from the ABI. The callee supplies
+ // its own singleton, so passing a callback does not expose our class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ ) {
Type arg = dep.addDepForwards(arg(i))._type;
TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(dep) : TypeMem.BOT;
escaped = escaped.escapesFrom(arg,outside);
@@ -182,7 +185,13 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole() : arg(parm._idx);
+ // A class function's receiver belongs to the callee, even
+ // when a different class or an instance forwards its callback.
+ // Match its declared view: before SCCP, forward fields can
+ // still differ from the completed class layout.
+ Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
+ : parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
+ ? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
CodeGen.CODE.add(parm).addDef(def);
// Linking can happen during post-SCCP inlining. Keep an RPC
// Parm's cached finite set synchronized with its newly added
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
index d5eaa743..a077e14b 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
@@ -24,7 +24,7 @@ public class MemMergeNode extends Node {
private AryInt _aliases;
private IntHashMap _aliasToInput;
private int _readSize;
- // Retain the old sparse extent for encoding and fold eligibility, without its holes.
+ // Retain the old sparse extent for fold eligibility, without its holes.
private int _aliasLimit=2;
public MemMergeNode(MemMergeNode mem) { super(mem); copyAliases(mem); _aliasLimit=mem._aliasLimit; }
@@ -50,10 +50,8 @@ public class MemMergeNode extends Node {
return input==0 ? null : in(input);
}
- // Preserve the existing sparse object encoding; input indices on disk are aliases.
- public int packedSize() { return _aliasLimit; }
+ // The reader has not wired the dense inputs yet.
public int readSize() { return _readSize; }
- public Node packedInput(int alias) { return alias<2 ? in(alias) : explicitAlias(alias); }
private void reindex() {
_aliasToInput.clear();
@@ -68,18 +66,17 @@ public class MemMergeNode extends Node {
}
@Override public Tag serialTag() { return Tag.MemMerge; }
public void packed( BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node, Integer> anodes ) {
- // A memory merge always has inputs. Zero escapes a wide alias table,
- // preserving every existing nonzero single-byte count.
- assert nIns()>0;
- baos.packed1(packedSize()<=255 ? packedSize() : 0);
- if( packedSize()>255 ) baos.packed4(packedSize());
+ // Keep the extent even if its last precise slice was removed. Edges
+ // are dense: control/default followed by explicit (alias,input) pairs.
+ baos.packed4(_aliasLimit);
+ baos.packed2(nIns());
}
static Node make( BAOS bais ) {
- int count=bais.packed1();
- if( count==0 ) count=bais.packed4();
+ int limit=bais.packed4(), count=bais.packed2();
+ assert 2<=count && count<=limit;
MemMergeNode mem=new MemMergeNode(null,null);
mem._readSize=count;
- mem._aliasLimit=count;
+ mem._aliasLimit=limit;
return mem;
}
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 7544962f..94376086 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -122,7 +122,8 @@ public class PhiNode extends Node {
// Generic "pull down op"
Node progress;
- if( same_op() && (progress = drop_same_op()) != null )
+ Node op = factoringOp();
+ if( same_op(op) && (progress = drop_same_op(op)) != null )
return progress;
// If merging Phi(ZERO, guardNZ(N)) at the matching `if(N)` join, the
@@ -161,10 +162,28 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
+ // View x<<1 as x+x when factoring mixed Add/Shl arms. Do not expand the
+ // graph: Add would immediately strength-reduce it again. If all arms are
+ // shifts, keep the ordinary shift factoring (including arbitrary counts).
+ private Node factoringOp() {
+ Node op = in(1);
+ if( doubled(op) )
+ for( int i=2; i<nIns(); i++ )
+ if( in(i) instanceof AddNode add && add._mode==1 ) return add;
+ return op;
+ }
+
+ private boolean doubled(Node n) {
+ return n instanceof ShlNode && addDep(n.in(2))._type==TypeInteger.TRUE;
+ }
+
+ private static Node factoringInput(Node op, Node n, int j) {
+ return n instanceof ShlNode && op instanceof AddNode ? n.in(1) : n.in(j);
+ }
+
// Same op on all Phi paths; all ops have only the Phi as a use.
// None have a control input.
- private boolean same_op() {
- Node op = in(1);
+ private boolean same_op(Node op) {
if( op instanceof EscapeNode || op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemMergeNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
@@ -181,8 +200,10 @@ public class PhiNode extends Node {
Node busy = null;
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
+ boolean same = op.getClass()==n.getClass() && op.eq(n);
+ if( !same && op instanceof AddNode add && add._mode==1 ) same = doubled(n);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- op.getClass()!=n.getClass() || n.nIns()!=op.nIns() || n.in(0)!=null || !op.eq(n) ) return false;
+ !same || n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
@@ -200,21 +221,21 @@ public class PhiNode extends Node {
return true;
}
- private Node drop_same_op() {
- Node op = in(1), cp = op.copyEmpty();
+ private Node drop_same_op(Node op) {
+ Node cp = op.copyEmpty();
cp._type = null;
cp._inputs.add(null);
for( int j=1; j<op.nIns(); j++ ) {
- Node x = op.in(j);
+ Node x = factoringInput(op,in(1),j);
boolean different = false;
for( int i=2; i<nIns(); i++ )
- if( in(i).in(j)!=x ) different=true;
+ if( factoringInput(op,in(i),j)!=x ) different=true;
if( different ) {
Node[] ins = new Node[nIns()];
ins[0] = region();
Type t = Type.TOP;
for( int i=1; i<nIns(); i++ ) {
- ins[i] = in(i).in(j);
+ ins[i] = factoringInput(op,in(i),j);
t = t.meet(ins[i]._type);
}
// Do not introduce an operand Phi mixing incompatible type families.
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index ca358b5a..17126f27 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -68,8 +68,9 @@ public class RegionNode extends CFGNode {
for( Node use : _outputs ) {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
+ // New users can require a bulk-memory input to split.
for( int j=1; j<region.nIns(); j++ )
- phi.addDef(phi2==null ? phi.in(i) : phi2.in(j));
+ phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
}
}
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index f73ba611..5b945457 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -26,7 +26,7 @@ public class SummaryNode extends CFGNode implements MultiNode {
// 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());
- for( int i = 2; i<nIns(); i++ ) {
+ for( int i = firstArgument(); i<nIns(); i++ ) {
Type arg = in(i)._type;
// Only opaque arguments can hide identities supplied by outside code.
TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(this) : TypeMem.BOT;
@@ -39,13 +39,20 @@ public class SummaryNode extends CFGNode implements MultiNode {
dep.addDepForwards(this);
if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START;
TypeMem mem = (TypeMem)_state.mem();
- for( int i = 2; i<nIns(); i++ ) {
+ for( int i = firstArgument(); i<nIns(); i++ ) {
Type arg = dep.addDepForwards(in(i))._type;
TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(dep) : TypeMem.BOT;
mem = mem.escapesFrom(arg,outside);
}
return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs);
}
+ // A class receiver is supplied by the callee, not exposed by its caller.
+ // Actual uses which publish self are already represented in _state.
+ 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;
+ }
@Override boolean _upgradeType(HashMap<String,Type> types) {
TypeTuple state = (TypeTuple)_state.upgradeType(types);
if( state==_state ) return false;
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java b/chapter32/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
index d4714953..9e0d864a 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
@@ -5,7 +5,7 @@ import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Utils;
import com.seaofnodes.simple.util.Ary;
-import java.util.IdentityHashMap;
+import java.util.BitSet;
public class x86_64_v2 extends Machine {
public x86_64_v2( CodeGen code ) {}
@@ -461,12 +461,13 @@ public class x86_64_v2 extends Machine {
if( load.nOuts()!=1 ) return false;
Ary<Node> writers=load.antiDeps(new Ary<>(Node.class));
if( writers.isEmpty() ) return true;
- var seen=new IdentityHashMap<Node,Boolean>();
+ var seen=new BitSet();
Ary<Node> work=new Ary<>(Node.class);
work.push(value);
while( !work.isEmpty() ) {
Node n=work.pop();
- if( seen.put(n,Boolean.TRUE)!=null ) continue;
+ if( seen.get(n._nid) ) continue;
+ seen.set(n._nid);
if( writers.find(n)!=-1 ) return false;
for( Node def : n._inputs ) if( def!=null ) work.push(def);
}
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java b/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java
index ffc96f57..f791a34c 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/parser/Expressions.java
@@ -36,6 +36,9 @@ final class Expressions {
{ P.pos(old); return parseExpression(); }
P.references.checkAssignment(def,site);
+ // All fields use the same receiver-based lvalue path.
+ if( P.references.fieldSelf(def)!=null )
+ { P.pos(old); return parseExpression(); }
return P.references.assign(def,parseAssignment());
}
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java
index 84bd509e..a7726521 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -36,7 +36,7 @@ final class Functions {
Type self = P.types.implicitSelfType();
if( P.structs.inStructDeclaration() ) self = self.makeRO();
ts.push(self);
- ids.push(self == TypePtr.PTR ? "#self" : "self");
+ ids.push("self");
// Parse other arguments
P._lexer.skipWhiteSpace();
@@ -130,6 +130,10 @@ final class Functions {
P._lexer.skipWhiteSpace();
Lexer nameLoc=P.loc();
String id = P.requireId();
+ // Older free functions may explicitly name a source argument
+ // "self". It shadows the implicit class receiver, not its ABI slot.
+ if( id=="self" && ts.at(0)==TypePtr.PTR && ids.at(0)=="self" )
+ ids.set(0,"#self");
if( ids.find(id)!=-1 ) throw Parser.error("Duplicate parameter '"+id+"'",nameLoc);
ts .push(t ); // Push type/arg pairs
ids.push(id);
@@ -359,6 +363,14 @@ final class Functions {
if( i == 0 && ids[0].equals("self") && !FunNode.isInit(funName) &&
!(sig.ret() instanceof TypeMem) && t instanceof TypeMemPtr ptr )
t = ptr.withAccess(false);
+ // The body sees its owning class receiver. PTR remains in the
+ // signature as the ABI marker for a receiver with no machine slot.
+ if( i==0 && t==TypePtr.PTR ) {
+ TypeStruct clz = ((TypeMemPtr)fun.defaultArg(i))._obj;
+ // A file can add globals after its struct declaration closes.
+ // Keep this view open until SCCP installs the completed class.
+ t = TypeMemPtr.make((byte)2,TypeStruct.make(clz._name,true,clz._fields),true);
+ }
// Args take a default input if called from Start/external-world
Type seed = i == 0 && t instanceof TypeMemPtr ? t : fun.defaultArg(i);
Node parm = new ParmNode(ids[i],i+2,t,fun,ConstantNode.seed(seed).peephole()).peephole();
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java
index 7724103e..91cf6859 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -93,23 +93,9 @@ final class References {
// Check for a function-escaping variable; these require true
// closures. Final constants are OK; final vars require a hidden var
// argument; not-final fields can just use an explicit struct arg.
- if( kx < fx && !P.structs.inExplicitConstructor() && // Out of scope
- !(var._final && rvalue._type.isConstant()) ) { // Not a final constant
- if( kx > 0 ) // Global scope is OK, only ever one of these (not one per function invoke)
- throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
-
- // var.idx==2 is self argument, 3 is args, 4 or more are now static globals
- if( var._idx >= 4 ) {
- // Read from global scope.
- // Surely a nicer way to get the top-level scope compile name?
- Var clzptr = P._scope.var( 2 );
- // Get the most recent sharpen global
- TypeStruct clz = (TypeStruct) Parser.TYPES.get( ((TypeMemPtr) clzptr.type())._obj._name );
- TypeMemPtr clztmp = TypeMemPtr.make( (byte) 2, clz, true );
- return parseField( P.con( clztmp ), id,pre );
- //return parseField(_scope.in(2),id);
- }
- }
+ if( kx>0 && kx<fx && !P.structs.inExplicitConstructor() &&
+ !(var._final && rvalue._type.isConstant()) )
+ throw Parser.error("Variable '"+var._name+"' is out of function scope and must be a final constant",site);
// Check for assign-update, x += e0;
char ch = pre==0 ? P._lexer.matchOperAssign() : (char)pre;
@@ -144,19 +130,6 @@ final class References {
}
Node assign(Var def, Node expr) {
- Node self = fieldSelf(def);
- if( self!=null ) {
- TypeStruct ts = P.types.latestStruct(((TypeMemPtr)self._type)._obj);
- Field fld = ts.field(def._name);
- Node val = expr.keep();
- Node lift = P.conversions.convertExpr(val,def.type());
- Node mem = P.construction.storeMemory(self).keep();
- Node st = new StoreNode(P.loc(),fld._fname,fld._alias,fld._t,P.ctrl(),mem,self,
- ConFldOffNode.make(ts,fld._fname),lift,P.construction.own(self)).peephole();
- P.construction.store(self,fld._alias,st,mem);
- mem.unkeep();
- return val.unkeep();
- }
String name = def._name;
// Lift expression, based on type
Type decl = def.type(); // Declared type
@@ -305,19 +278,27 @@ final class References {
return P._scope.in(P._scope.update(P._scope.var(selfx),null));
}
- // Fields are lvalues in memory, including inside their initializer and
- // explicit constructor. Scope slots retain declaration metadata only.
- private Node fieldSelf(Var var) {
+ // Find the receiver for a field lvalue. Instance initializers use memory;
+ // class declarations retain their Scope values until initializer exit.
+ Node fieldSelf(Var var) {
int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
- if( !(kind instanceof Kind.Func inst) || !FunNode.isInstance(inst._name) || var._idx<inst._lexSize+2 ) return null;
+ if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null;
+ // Class declarations still accumulate their initial values in Scope.
+ // This also preserves declaration-time struct default expressions.
+ if( FunNode.isClz(owner._name) && P._scope.enclosingFunction()==kx ) return null;
// Nested functions have their own receiver parameter. Resolve fields
// through it even across intervening function and block scopes.
Node self = defaultSelf();
- Type owner = P._scope.var(inst._lexSize).type();
- if( self._type instanceof TypeMemPtr ptr && owner instanceof TypeMemPtr declared &&
+ Var receiver = P._scope.var(owner._lexSize);
+ if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared &&
ptr._obj._name.equals(declared._obj._name) ) return self;
- return null;
+ // An instance method can also name fields of its enclosing class.
+ // Use that declaration's receiver; normal folding handles its identity.
+ if( !FunNode.isClz(owner._name) ) return null;
+ // The enclosing declaration may have discovered more fields since
+ // creating its receiver. View that same receiver with its current type.
+ return P.peep(new ConvertNode(receiver.type().upgradeType(Parser.TYPES),P._scope.in(receiver)));
}
private void checkSharedFunction(Var v) {
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java b/chapter32/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
index 19ec5019..c6f53022 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
@@ -248,7 +248,7 @@ public class TypeFunPtr extends TypeNil {
@Override int TAGOFF() { return 8; }
@Override public void packed( BAOS baos, HashMap<String,Integer> strs ) {
assert _open; // Open: Passing extra args is fine, and extras ignored.
- if( _nil==2 && nargs()<6 && nfcns() == 1 && fidx() < 64 ) {
+ if( _nil==2 && nargs()<6 && nfcns() == 1 && fidx()<=65535 ) {
baos.write(TAGOFFS[_type] + nargs());
baos.packed2(fidx());
} else {
@@ -259,8 +259,7 @@ public class TypeFunPtr extends TypeNil {
}
static TypeFunPtr packed( int tag, BAOS bais ) {
if( tag < 6 ) {
- int fidx = bais.read();
- assert fidx < 64; // Need a larger fidx space
+ int fidx = bais.packed2();
return malloc((byte)2,true,new Type[tag],null, XInt.make(fidx));
}
byte nil = (byte)(tag==6 ? 2 : 3);
diff --git a/chapter32/src/main/java/com/seaofnodes/simple/util/BAOS.java b/chapter32/src/main/java/com/seaofnodes/simple/util/BAOS.java
index 61ce7387..c47d386c 100644
--- a/chapter32/src/main/java/com/seaofnodes/simple/util/BAOS.java
+++ b/chapter32/src/main/java/com/seaofnodes/simple/util/BAOS.java
@@ -1,7 +1,8 @@
package com.seaofnodes.simple.util;
-import java.util.HashMap;
+//import java.util.HashMap;
import java.util.Arrays;
+import java.nio.charset.StandardCharsets;
// "ByteArrayOutputStream", and Input Stream and not synchronized and has
// matching pack/unpack strategies.
@@ -96,12 +97,12 @@ public class BAOS {
}
// -----------------------------------------------------------------------
- // Write a packed integer to the BAOS. Track a histogram to make more
- // intelligent choices in the future.
- private static final HashMap<Long,Integer> PACKED_HISTOGRAM = new HashMap<>();
+ // Optional profiling for choosing smaller packed representations. Leave
+ // disabled during normal compilation; re-enable when studying .simple size.
+ //private static final HashMap<Long,Integer> PACKED_HISTOGRAM = new HashMap<>();
private BAOS histo(long x) {
- Integer cnt = PACKED_HISTOGRAM.get(x);
- PACKED_HISTOGRAM.put(x,cnt==null ? 1 : cnt+1);
+ //Integer cnt = PACKED_HISTOGRAM.get(x);
+ //PACKED_HISTOGRAM.put(x,cnt==null ? 1 : cnt+1);
return this;
}
@@ -125,15 +126,29 @@ public class BAOS {
return x==0xFF ? read2() : x;
}
- // Write a packed i32
+ // Signed zigzag varint: -64..63 use one byte, -8192..8191 two,
+ // and the full int range needs at most five. Seven payload bits per byte.
public void packed4(int x) {
- ((-127 <= x && x <= 127 ) ? write(x) : write(-128).write4(x)).histo(x);
+ histo(x);
+ int bits = (x<<1) ^ (x>>31);
+ while( (bits & ~127)!=0 ) {
+ write((bits & 127) | 128);
+ bits >>>= 7;
+ }
+ write(bits);
}
// Read a packed i32
public int packed4() {
- int x = _buf[_len++]; // Signed byte read
- return x== -128 ? read4() : x;
+ int bits=0;
+ for( int shift=0; shift<32; shift+=7 ) {
+ int b = read();
+ if( shift==28 && (b & 0xF0)!=0 )
+ throw new IllegalArgumentException("Packed int overflow");
+ bits |= (b & 127)<<shift;
+ if( (b & 128)==0 ) return (bits>>>1) ^ -(bits & 1);
+ }
+ throw new IllegalArgumentException("Unterminated packed int");
}
// Write a packed i64
@@ -148,14 +163,16 @@ public class BAOS {
}
public void packedS(String s) {
- packed4(s.length());
- for( int i=0; i<s.length(); i++ )
- packed4(s.charAt(i));
+ // Strings are bytes, not signed packed integers. Keep ASCII at one
+ // byte per character and agree on the representation of non-ASCII.
+ byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
+ packed4(utf8.length);
+ write(utf8);
}
public String packedS() {
int len = packed4();
- String s = new String(_buf,_len,len).intern();
+ String s = new String(_buf,_len,len,StandardCharsets.UTF_8).intern();
_len += len;
return s;
}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java b/chapter32/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java
index 0e4c230a..5399aecf 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java
@@ -13,25 +13,39 @@ public class AssemblyDumpTest {
@Test public void libraryUnitsAndGlyphs() throws Exception {
Path root=Path.of("build/objs/assembly-dump");
Files.createDirectories(root);
- Path build=Files.createTempDirectory(root,"sys-");
- CodeGen code=new CodeGen("src/main/smp",build.toString(),null,"sys",null,123,true,TypeInteger.BOT)
+ Path fixture=Files.createTempDirectory(root,"font-");
+ Path source=Files.createDirectories(fixture.resolve("src"));
+ Path build=Files.createDirectories(fixture.resolve("obj"));
+ Files.createDirectories(source.resolve("Atlas"));
+ // Use the real font, but only two tiny modules: drawing integration is
+ // covered by DrawTest. This test needs multiple units and constant data.
+ String canvasSource=Files.readString(Path.of("src/main/smp/sys/draw/Canvas.smp"));
+ int fontStart=canvasSource.indexOf("val _glyphs =");
+ assertTrue("Font declaration",fontStart>=0);
+ int fontEnd=canvasSource.indexOf("};",fontStart);
+ assertTrue("Font initializer",fontEnd>=0);
+ Files.writeString(source.resolve("Atlas/Font.smp"),canvasSource.substring(fontStart,fontEnd+2)+
+ "\nval glyph={int i -> _glyphs[i];};\n");
+ Files.writeString(source.resolve("Atlas.smp"),"val glyph={int i -> Font.glyph(i);};\n");
+ CodeGen code=new CodeGen(source.toString(),build.toString(),null,"Atlas",null,123,true,TypeInteger.BOT)
.driver(CodeGen.Phase.Serialize,TestC.CPU_PORT,TestC.CALL_CONVENTION)
.driver(CodeGen.Phase.Encoding,TestC.CPU_PORT,TestC.CALL_CONVENTION);
var entry=code._encoding;
String before=code.asm();
assertSame("Dumping another unit must not change the active encoding",entry,code._encoding);
+ assertEquals(2,code._compunits.size());
for( var unit : code._compunits.values() )
if( unit._src!=null ) {
String heading="=== Compilation unit: "+unit._cname+" ===";
assertEquals("Exactly one heading for "+unit._cname,2,before.split(heading,-1).length);
}
- int start=before.indexOf("=== Compilation unit: sys.draw.Canvas ===");
+ int start=before.indexOf("=== Compilation unit: Atlas.Font ===");
assertTrue(start>=0);
int end=before.indexOf("=== Compilation unit:",start+1);
String canvas=before.substring(start,end<0 ? before.length() : end);
assertTrue(canvas.contains("Constant Pool"));
- assertTrue(canvas.contains("sys.draw.Canvas._glyphs: []u16"));
- TypeMemPtr ptr=(TypeMemPtr)code._compunits.get("sys/draw/Canvas")._clz.field("_glyphs")._t;
+ assertTrue(canvas.contains("Atlas.Font._glyphs: []u16"));
+ TypeMemPtr ptr=(TypeMemPtr)code._compunits.get("Atlas/Font")._clz.field("_glyphs")._t;
TypeConAry glyphs=(TypeConAry)ptr._obj.field("[]")._t;
assertEquals(96,glyphs.len());
BAOS bytes=new BAOS();
@@ -40,10 +54,10 @@ public class AssemblyDumpTest {
canvas.contains("60000000"+HexFormat.of().formatHex(bytes.toByteArray())));
code.exportELF(false,false);
com.seaofnodes.simple.codegen.PrintRegTestSupport.checkDataAliases(
- build.resolve("sys/draw/Canvas.o"),196,"sys.draw.Canvas._glyphs");
+ build.resolve("Atlas/Font.o"),196,"Atlas.Font._glyphs");
assertSame(entry,code._encoding);
assertEquals("Export must not truncate the dump to its entry unit",before,code.asm());
- Files.writeString(build.resolve("sys.asm"),before);
+ Files.writeString(build.resolve("Atlas.asm"),before);
}
@Test public void combinedEncodingAndEarlierPhase() {
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/BAOSTest.java b/chapter32/src/test/java/com/seaofnodes/simple/BAOSTest.java
new file mode 100644
index 00000000..03e53b6d
--- /dev/null
+++ b/chapter32/src/test/java/com/seaofnodes/simple/BAOSTest.java
@@ -0,0 +1,58 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.type.PackedTypeTestSupport;
+import com.seaofnodes.simple.util.BAOS;
+import java.util.Random;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class BAOSTest {
+ @Test public void packedIntBoundaries() {
+ int[] values={Integer.MIN_VALUE,-134217729,-134217728,-1048577,-1048576,
+ -8193,-8192,-65,-64,-1,0,1,63,64,8191,8192,1048575,1048576,
+ 134217727,134217728,Integer.MAX_VALUE};
+ int[] widths={5,5,4,4,3,3,2,2,1,1,1,1,1,2,2,3,3,4,4,5,5};
+ BAOS out=new BAOS();
+ for( int i=0; i<values.length; i++ ) {
+ int before=out.size();
+ out.packed4(values[i]);
+ assertEquals("width of "+values[i],widths[i],out.size()-before);
+ }
+ BAOS in=new BAOS(out.toByteArray());
+ for( int value : values ) assertEquals(value,in.packed4());
+ assertEquals(out.size(),in.size());
+ out.clear();
+ out.packed4(-65); out.packed4(64);
+ assertArrayEquals(new byte[]{(byte)0x81,1,(byte)0x80,1},out.toByteArray());
+ }
+
+ @Test public void packedIntsAndStrings() {
+ Random random=new Random(123);
+ int[] values=new int[10000];
+ BAOS out=new BAOS();
+ for( int i=0; i<values.length; i++ ) out.packed4(values[i]=random.nextInt());
+ String[] strings={"","ASCII stays compact", "\u0000", "caf\u00e9 \u65e5\u672c\u8a9e \uD83D\uDE00", "x".repeat(8192)};
+ for( String s : strings ) out.packedS(s);
+ out.packed8(Long.MIN_VALUE);
+ BAOS in=new BAOS(out.toByteArray());
+ for( int value : values ) assertEquals(value,in.packed4());
+ for( String s : strings ) assertEquals(s,in.packedS());
+ assertEquals(Long.MIN_VALUE,in.packed8());
+ assertEquals(out.size(),in.size());
+ }
+
+ @Test public void rejectPackedIntOverflow() {
+ for( byte last : new byte[]{0x10,(byte)0x80} ) {
+ BAOS in=new BAOS(new byte[]{(byte)0x80,(byte)0x80,(byte)0x80,(byte)0x80,last});
+ try { in.packed4(); fail("overflow accepted"); }
+ catch( IllegalArgumentException expected ) { assertTrue(expected.getMessage().contains("overflow")); }
+ }
+ }
+
+ @Test public void wideSingletonFunctionIds() {
+ new CodeGen("");
+ for( int id : new int[]{2,63,64,254,255,256,1024,65535} )
+ PackedTypeTestSupport.singleton(id);
+ }
+}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 43057c00..9f733da5 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -2,6 +2,7 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeInteger;
import org.junit.Test;
import static org.junit.Assert.*;
@@ -201,4 +202,38 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
+ @Test public void testDoublingBeforeAndAfterStrengthReduction() {
+ for( boolean shift : new boolean[]{false,true} )
+ for( boolean reverse : new boolean[]{false,true} ) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ RegionNode region = new RegionNode(null,null,ctrl,ctrl).init();
+ Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32);
+ Node twice = shift ? new ShlNode(null,p,code.con(1)).init()
+ : new AddNode(p,p,(byte)1).init();
+ Node sum = new AddNode(i,p,(byte)1).init();
+ PhiNode phi = new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum).init();
+ phi.keep();
+ Node factored = phi.idealize();
+ assertTrue(factored instanceof AddNode);
+ assertSame(p,factored.in(2));
+ assertTrue(factored.in(1) instanceof PhiNode);
+ assertSame(reverse ? i : p,factored.in(1).in(1));
+ assertSame(reverse ? p : i,factored.in(1).in(2));
+ phi.unkeep();
+ }
+ }
+
+ @Test public void testOtherShiftIsNotDoubling() {
+ CodeGen code = new CodeGen("");
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ RegionNode region = new RegionNode(null,null,ctrl,ctrl).init();
+ Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32);
+ Node shift = new ShlNode(null,p,code.con(2)).init();
+ Node sum = new AddNode(i,p,(byte)1).init();
+ PhiNode phi = new PhiNode("sum",region,shift,sum).init();
+ phi.keep();
+ assertNull(phi.idealize());
+ phi.unkeep();
+ }
}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index 273d76ba..226425ca 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -262,8 +262,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index 14a091ac..7a59adb0 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -386,8 +386,8 @@ val hashCode = { !String self ->
""";
// Return the public hashCode wrapper; keep its helper private.
testCPU(src,"x86_64_v2", "SystemV",28,null);
- testCPU(src,"riscv" , "SystemV",8,null);
- testCPU(src,"arm" , "SystemV",6,null);
+ testCPU(src,"riscv" , "SystemV",11,null);
+ testCPU(src,"arm" , "SystemV",11,null);
}
@Test public void testStringExport() throws IOException {
@@ -472,7 +472,8 @@ val test_sqrt = { flt x ->
}
};
""";
- TestC.runC(src, "newtonFloat", result, TestC.CALL_CONVENTION.equals("win64") ? 42 : 34);
+ // With the zero-input guard, both SystemV and win64 score 42.
+ TestC.runC(src, "newtonFloat", result, 42);
EvalRisc5 R5 = TestRisc5.build( src, "test_sqrt", 0, 10, false);
R5.fregs[riscv.FA0 - riscv.F_OFFSET] = 3.0;
@@ -532,8 +533,8 @@ val sieve = { int N ->
String sprimes = sb.p("]").toString();
// Compile, link against native C; expect the above string of primes to be printed out by C
- // Load/Phi hoisting now requires the pointer before the loop entry.
- TestC.runC(src, "sieve", sprimes,216);
+ // Phi factoring also recognizes p<<1 after p+p strength reduction.
+ TestC.runC(src, "sieve", sprimes,215);
// Evaluate on RISC5 emulator; expect return of an array of primes in
// the simulated heap.
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java b/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java
index c9791de4..f9146ae6 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/Chapter22Test.java
@@ -302,17 +302,17 @@ val p = { u8[~] str ->
p("Hello, World!");
return 0;
""";
- TestC.runSF(src,"helloWorld", "Hello, World!",2);
+ TestC.runSF(src,"helloWorld", "Hello, World!",4);
// Evaluate on RISC5 emulator
- EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 5, false);
+ EvalRisc5 R5 = TestRisc5.build( src, "helloWorld", 0, 8, false);
int trap = R5.step(100);
assertEquals(0,trap);
assertEquals(0,R5.regs[riscv.A0]);
assertEquals("Hello, World!",R5._stdout.toString());
// Evaluate on ARM emulator
- EvalArm64 arm = TestArm64.build("helloWorld", src,0, 5, false);
+ EvalArm64 arm = TestArm64.build("helloWorld", src,0, 8, false);
trap = arm.step(100);
assertEquals(0,trap);
assertEquals(0,arm.regs[0]);
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
new file mode 100644
index 00000000..51ed10c6
--- /dev/null
+++ b/chapter32/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -0,0 +1,71 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.parser.Parser;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class GlobalAssignmentTest {
+ private static final String SOURCE = """
+ int value=1;
+ int writes=0;
+ u8 small=0;
+ val set={int n -> value=n; return value;};
+ val set_noInline={int n ->
+ if( n<0 ) value=3;
+ else value=n;
+ return value;
+ };
+ val rhs_noInline={ -> writes=writes+1; return value+1;};
+ val shadow={int value -> value=42; return value;};
+ struct Writer {
+ int seen;
+ new Writer={int n -> value=n; seen=value;};
+ };
+ struct InitWriter { int seen=(value=17); };
+ val main={ ->
+ if( set(5)!=5 || value!=5 ) return 1;
+ if( set_noInline(-1)!=3 || value!=3 ) return 2;
+ if( set_noInline(8)!=8 || value!=8 ) return 3;
+ int result=(value=rhs_noInline());
+ if( result!=9 || value!=9 || writes!=1 ) return 4;
+ value=writes=11;
+ if( value!=11 || writes!=11 ) return 5;
+ if( shadow(0)!=42 || value!=11 ) return 6;
+ int wide=(small=257);
+ if( wide!=257 || small!=1 ) return 7;
+ val constructed=new Writer(13);
+ if( value!=13 || constructed.seen!=13 ) return 8;
+ val initialized=new InitWriter;
+ // Default expressions run at declaration time, not per instance.
+ if( value!=13 || initialized.seen!=17 ) return 9;
+ return 0;
+ };
+ return main();
+ """;
+
+ @Test public void storesGlobalMemory() throws Exception {
+ assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(SOURCE,"global_assignment","",-1);
+ }
+
+ @Test public void rejectsFinalGlobal() {
+ try {
+ new CodeGen("val value=1; val set={ -> value=2; }; return set();")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Assigned a final global");
+ } catch( Parser.ParseException e ) {
+ assertEquals("Cannot reassign final 'value'",e.getMessage());
+ }
+ }
+
+ @Test public void rejectsIncompatibleGlobalValue() {
+ try {
+ new CodeGen("struct S { int x; }; int value=1; val set={ -> value=new S; }; set(); return value;")
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Stored an object in an integer global");
+ } catch( Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("not of declared type"));
+ }
+ }
+}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/MemMergeTest.java b/chapter32/src/test/java/com/seaofnodes/simple/MemMergeTest.java
index cb17982e..253bce0b 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/MemMergeTest.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/MemMergeTest.java
@@ -20,9 +20,8 @@ public class MemMergeTest {
assertEquals(10000,mem.aliasAt(4));
assertSame(value,mem.alias(10000));
assertSame(defaults,mem.alias(512));
- assertEquals(10001,mem.packedSize());
- assertNull(mem.packedInput(9999));
- assertSame(value,mem.packedInput(10000));
+ assertNull(mem.explicitAlias(9999));
+ assertSame(value,mem.explicitAlias(10000));
mem.alias(513,null);
assertEquals(4,mem.nIns());
assertEquals(10000,mem.aliasAt(3));
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/ModTest.java b/chapter32/src/test/java/com/seaofnodes/simple/ModTest.java
index 7f79599d..c06e99f1 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/ModTest.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/ModTest.java
@@ -166,20 +166,31 @@ public class ModTest {
return integerEdges(new long[]{Long.MIN_VALUE,Long.MIN_VALUE+1,-17,-5,-1,0,1,5,17,Long.MAX_VALUE});
}
private static String integerEdges(long[] values) {
+ // Keep the full value matrix in data, rather than compiling a long
+ // chain of constant calls and conditional returns for every pair.
StringBuilder source=new StringBuilder("""
val rem_noInline={ i64 x,i64 y -> x%y; };
val div_noInline={ i64 x,i64 y -> x/y; };
val main={ ->
+ val values=new i64[~]{
""");
- int failure=1;
- for( long x : values )
- for( long y : values ) {
- source.append("if(rem_noInline(").append(literal(x)).append(',').append(literal(y))
- .append(")!=").append(literal(y==0 ? 0 : x%y)).append(") return ").append(failure++).append(';');
- source.append("if(div_noInline(").append(literal(x)).append(',').append(literal(y))
- .append(")!=").append(literal(y==0 ? 0 : x/y)).append(") return ").append(failure++).append(';');
+ for(int i=0;i<values.length;i++) source.append(i==0 ? "" : ",").append(literal(values[i]));
+ source.append("}; val expectedRem=new i64[~]{");
+ int n=0;
+ for(long x:values) for(long y:values) source.append(n++==0 ? "" : ",").append(literal(y==0 ? 0 : x%y));
+ source.append("}; val expectedDiv=new i64[~]{");
+ n=0;
+ for(long x:values) for(long y:values) source.append(n++==0 ? "" : ",").append(literal(y==0 ? 0 : x/y));
+ return source.append("""
+ };
+ int index=0;
+ for(int i=0;i<values#;i++) for(int j=0;j<values#;j++) {
+ if(rem_noInline(values[i],values[j])!=expectedRem[index]) return index*2+1;
+ if(div_noInline(values[i],values[j])!=expectedDiv[index]) return index*2+2;
+ index++;
}
- return source.append("return 0; };").toString();
+ return 0; };
+ """).toString();
}
@Test public void nativeFloatingEdges() throws Exception {
double[][] cases={{Double.MAX_VALUE,0.1},{-Double.MAX_VALUE,0.1},
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java b/chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java
new file mode 100644
index 00000000..83bf6768
--- /dev/null
+++ b/chapter32/src/test/java/com/seaofnodes/simple/ReceiverTest.java
@@ -0,0 +1,93 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.*;
+import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.util.Ary;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class ReceiverTest {
+ @Test public void classAndInstanceFields() throws Exception {
+ String source="""
+ int total=1;
+ val forward={ -> late(); };
+ val early={ -> total; };
+ val late={ -> early(); };
+ val add_noInline={int n -> self.total=self.total+n; return total;};
+ val read_noInline={ -> self.total; };
+ val nested={ ->
+ val inc={ -> self.total++; };
+ inc();
+ return total;
+ };
+ struct Counter {
+ int total=100;
+ val read=read_noInline;
+ };
+ struct Writer {
+ int count=2;
+ val step={ -> self.count++; total=count; return total; };
+ };
+ val table=new u16[~2]{7,9};
+ val lookup={u8 c -> c<2 ? table[c] : 0;};
+ val main={ ->
+ total=1;
+ if( forward()!=1 ) return 4;
+ if( lookup(1)!=9 || lookup(2)!=0 ) return 5;
+ if( add_noInline(5)!=6 || nested()!=7 ) return 1;
+ val counter=new Counter;
+ if( counter.read()!=7 || counter.total!=100 ) return 2;
+ val a=new Writer, b=new Writer;
+ if( a.step()!=3 || total!=3 || a.count!=3 || b.count!=2 ) return 3;
+ return 0;
+ };
+ return main();
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(source).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(source,"class_instance_receivers","",-1);
+ }
+
+ @Test public void importedCallbackKeepsItsClass() throws Exception {
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"classes-");
+ new CodeGen(null,lib.toString(),null,"Owner",
+ "int value=7; val get_noInline={ -> self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ new CodeGen(null,lib.toString(),null,"Forwarder",
+ "int value=99; val apply_noInline={ {int} action -> action()+self.value; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ String source="return Forwarder.apply_noInline(Owner.get_noInline)==106 ? 0 : 1;";
+ CodeGen code=new CodeGen(null,null,paths,"ReceiverClient",source,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ TestC.run(source,"imported_receivers",paths,TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void classReceiverHasNoNativeArgument() throws Exception {
+ String source="""
+ int base=10;
+ val calc={int a,int b,int c,int d,int e,int f,int g ->
+ self.base+a+2*b+3*c+4*d+5*e+6*f+7*g;
+ };
+ val callback_noInline={int n -> self.base+n;};
+ { {int -> i64} int -> i64 } invoke="C";
+ val viaC={int n -> invoke(callback_noInline,n);};
+ """;
+ Path build=Path.of("build/objs/receivers");
+ Files.createDirectories(build);
+ Path driver=build.resolve("native_receiver.c");
+ Files.writeString(driver,"""
+ typedef long long (__attribute__((CALL_CONV)) *action_t)(int);
+ __attribute__((CALL_CONV)) long long invoke(action_t action, int n) { return action(n); }
+ __attribute__((CALL_CONV)) extern long long calc(int,int,int,int,int,int,int);
+ __attribute__((CALL_CONV)) extern long long viaC(int);
+ int main(void) { return calc(1,2,3,4,5,6,7)!=150 || viaC(5)!=15; }
+ """);
+ TestC.run(source,"native_receiver",null,TestC.CALL_CONVENTION,
+ TestC.CALL_CONVENTION.equals("win64") ? "ms_abi" : "sysv_abi",driver.toString(),"",-1);
+ }
+}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java b/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
index 1c278791..cc4e552f 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
@@ -10,6 +10,42 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class SeparateCompilationTest {
+ @Test public void testSparseWideMemoryImport() throws Exception {
+ Path build=Path.of("build/objs/separate");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"wide-memory-");
+ StringBuilder source=new StringBuilder("int f0=7;\n");
+ for( int i=1; i<300; i++ ) source.append("int f").append(i).append("=0;\n");
+ source.append("val touch={int n -> f299=n; return f0+f299;};");
+ new CodeGen(null,lib.toString(),null,"Wide",source.toString(),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,"WideEval","return Wide.touch((arg<<32)>>32);",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("12",Eval2.eval(code,5));
+ TestC.run("return Wide.touch(5)==12 ? 0 : 1;","wide_memory_client",paths,
+ TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void testOldObjectFormatRequestsRebuild() throws Exception {
+ Path build=Path.of("build/objs/separate");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"old-format-");
+ new CodeGen(null,lib.toString(),null,"Old","val value=7;",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ Path file=lib.resolve("Old.o");
+ ElfReader elf=ElfReader.load(file.toFile(),null);
+ byte[] bytes=Files.readAllBytes(file);
+ bytes[elf._bais.size()+3]='E'; // Previous C0DE header, before format 2.
+ Files.write(file,bytes);
+ try {
+ ElfReader.load(file.toFile(),null).loadPublicTypes(new CodeGen(""));
+ fail("old format accepted");
+ } catch( IllegalArgumentException expected ) {
+ assertTrue(expected.getMessage().contains("rebuild the object file"));
+ }
+ }
+
@Test public void testImportedReadOnlyPrimitiveArray() throws Exception {
Path build=Path.of("build/objs/separate");
Files.createDirectories(build);
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/StringFormatTest.java b/chapter32/src/test/java/com/seaofnodes/simple/StringFormatTest.java
index 59b62709..d6783380 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/StringFormatTest.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/StringFormatTest.java
@@ -11,28 +11,88 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class StringFormatTest extends TestC {
- private static void prints(String body, String expected) throws Exception {
- runSYS("val main={ -> "+body+" return 0; };", "stringFormat",expected,-1);
+ // Share a few native programs, retaining a separately reported assertion
+ // for each case. Blocks isolate locals; the delimiter preserves embedded
+ // NULs and newlines in the expected output.
+ private enum Format {
+ DefaultsAndNestedStrings("sys.io.p(\"CPU plays %(2+3). %(\"nested %(7)\") %(true) %(1.5)\\n\");",
+ "CPU plays 5. nested 7 1 1.5\n"),
+ Formats("sys.io.p(\"%+06d(17)|%#08x(42)|%-5.3s(\"abcdef\")|%.2f(1.25)|%c(65)|%b(false)\\n\");",
+ "+00017|0x00002a|abc |1.25|A|false\n"),
+ RemainderInInterpolation("int mod=17; sys.io.p(\"%(mod%5)|%02d(mod%5)|%%|\\%|%(mod %= 5)|%(mod)\");",
+ "2|02|%|%|2|2"),
+ IntegerLimits("i64 lo=-9223372036854775807-1; sys.io.p(\"%(lo)|%(9223372036854775807)|%u(-1)|%X(-1)\");",
+ "-9223372036854775808|9223372036854775807|18446744073709551615|FFFFFFFFFFFFFFFF"),
+ IntegerPaddingRules("sys.io.p(\"%#.0o(0)|%#.3o(1)|%#x(0)|%-08d(17)|%08.4d(-17)|%+d(0)|% d(0)\");",
+ "0|001|0|17 | -0017|+0| 0"),
+ BuilderNumberUsesFormatter("val b=new sys.aryu8(); b.num(-9223372036854775807-1).add('|').num(9223372036854775807); sys.io.p(sys.text.end(b));",
+ "-9223372036854775808|9223372036854775807"),
+ EvaluationOrder("int x=0; val s=\"%(x++)%(x++)%(x++)\"; sys.io.p(\"%(s):%(s#):%(x)|%%|\\%\");",
+ "012:3:3|%|%"),
+ EvaluationMutatesBytes("val a=new u8[1]; a[0]='A'; sys.io.p(\"%(a)%(a[0]='B')%(a)\");", "A66B"),
+ Converters("sys.io.p(sys.text.int(17)); sys.io.p(sys.text.char(65)); sys.io.p(sys.text.bool(true)); sys.io.p(sys.text.flt(1.5));",
+ "17Atrue1.5"),
+ FieldNamedInt("struct S { int int=7; }; sys.io.p(\"%((new S).int)\");", "7"),
+ FloatAndAlternateFormats("f32 x=1.25f; sys.io.p(\"%(x)|%f(x)|%.2e(x)|%.2G(x)|%#o(9)|% d(7)|%.0d(0)|%a(1.5)\");",
+ "1.25|1.250000|1.25e+00|1.2|011| 7||0x1.8p+0"),
+ BufferGrowth("sys.io.p(\"%0100d(17)|%.100f(1.0)\");", "0".repeat(98)+"17|1."+"0".repeat(100)),
+ BytesAndEmptyStrings("val empty=\"%(\"\")\"; val bytes=\"a\\0b\"; sys.io.p(\"%(empty#):%s(bytes):%.2s(bytes):%c(0)\");",
+ "0:a\0b:a\0:\0"),
+ Utf8String("val s=\"π\"; sys.io.p(\"%(s):%(s#):%(s[0]):π\");", "π:2:207:π"),
+ DeferredParsing("""
+ struct S { u8[~] s; new S={ -> s="%("}) %(3)")"; }; };
+ val s=new S;
+ sys.io.p(s.s);
+ for(int i=0; i<2; sys.io.p("%(i++) %("(")")) { }
+ """, "}) 30 (1 (");
+
+ final String body, expected;
+ Format(String body, String expected) { this.body=body; this.expected=expected; }
+ }
+ private static final String END="\n--end-format-case--\n";
+ private static final int BATCH_SIZE=5;
+ private static final String[] OUTPUTS=new String[Format.values().length];
+
+ @org.junit.BeforeClass public static void resetNativeBatches() {
+ java.util.Arrays.fill(OUTPUTS,null);
+ }
+
+ private static void prints(Format test) throws Exception {
+ int index=test.ordinal();
+ if( OUTPUTS[index]==null ) {
+ Format[] cases=Format.values();
+ int first=index/BATCH_SIZE*BATCH_SIZE, limit=Math.min(first+BATCH_SIZE,cases.length);
+ StringBuilder source=new StringBuilder("val main={ -> ");
+ for( int i=first; i<limit; i++ ) {
+ assertFalse("Reserved batch delimiter",cases[i].expected.contains(END));
+ source.append('{').append(cases[i].body).append('}');
+ source.append("sys.io.p(\"\\n--end-format-case--\\n\");");
+ }
+ source.append("return 0; };");
+ String exe=compile(source.toString(),"stringFormat"+first,
+ new Ary<>(new String[]{RELEASE_SYS_DIR}),CALL_CONVENTION,null,null,-1);
+ String[] outputs=exec(TEST_TIMEOUT_SECONDS,exe).split(java.util.regex.Pattern.quote(END),-1);
+ assertEquals("Each format case must complete",limit-first+1,outputs.length);
+ assertEquals("No output after final case", "",outputs[outputs.length-1]);
+ for( int i=first; i<limit; i++ ) OUTPUTS[i]=outputs[i-first];
+ }
+ assertEquals(test.name(),test.expected,OUTPUTS[index]);
}
@Test public void testDefaultsAndNestedStrings() throws Exception {
- prints("sys.io.p(\"CPU plays %(2+3). %(\"nested %(7)\") %(true) %(1.5)\\n\");",
- "CPU plays 5. nested 7 1 1.5\n");
+ prints(Format.DefaultsAndNestedStrings);
}
@Test public void testFormats() throws Exception {
- prints("sys.io.p(\"%+06d(17)|%#08x(42)|%-5.3s(\"abcdef\")|%.2f(1.25)|%c(65)|%b(false)\\n\");",
- "+00017|0x00002a|abc |1.25|A|false\n");
+ prints(Format.Formats);
}
@Test public void testRemainderInInterpolation() throws Exception {
- prints("int mod=17; sys.io.p(\"%(mod%5)|%02d(mod%5)|%%|\\%|%(mod %= 5)|%(mod)\");",
- "2|02|%|%|2|2");
+ prints(Format.RemainderInInterpolation);
}
@Test public void testIntegerLimits() throws Exception {
- prints("i64 lo=-9223372036854775807-1; sys.io.p(\"%(lo)|%(9223372036854775807)|%u(-1)|%X(-1)\");",
- "-9223372036854775808|9223372036854775807|18446744073709551615|FFFFFFFFFFFFFFFF");
+ prints(Format.IntegerLimits);
}
@Test public void testSignedAndUnsignedRadices() throws Exception {
@@ -49,13 +109,11 @@ public class StringFormatTest extends TestC {
}
@Test public void testIntegerPaddingRules() throws Exception {
- prints("sys.io.p(\"%#.0o(0)|%#.3o(1)|%#x(0)|%-08d(17)|%08.4d(-17)|%+d(0)|% d(0)\");",
- "0|001|0|17 | -0017|+0| 0");
+ prints(Format.IntegerPaddingRules);
}
@Test public void testBuilderNumberUsesFormatter() throws Exception {
- prints("val b=new sys.aryu8(); b.num(-9223372036854775807-1).add('|').num(9223372036854775807); sys.io.p(sys.text.end(b));",
- "-9223372036854775808|9223372036854775807");
+ prints(Format.BuilderNumberUsesFormatter);
}
@Test public void testFormattingInEvaluatorFromSource() {
@@ -74,15 +132,13 @@ public class StringFormatTest extends TestC {
}
@Test public void testEvaluationOrderAndLength() throws Exception {
- prints("int x=0; val s=\"%(x++)%(x++)%(x++)\"; sys.io.p(\"%(s):%(s#):%(x)|%%|\\%\");",
- "012:3:3|%|%");
- prints("val a=new u8[1]; a[0]='A'; sys.io.p(\"%(a)%(a[0]='B')%(a)\");", "A66B");
+ prints(Format.EvaluationOrder);
+ prints(Format.EvaluationMutatesBytes);
}
@Test public void testConverters() throws Exception {
- prints("sys.io.p(sys.text.int(17)); sys.io.p(sys.text.char(65)); sys.io.p(sys.text.bool(true)); sys.io.p(sys.text.flt(1.5));",
- "17Atrue1.5");
- prints("struct S { int int=7; }; sys.io.p(\"%((new S).int)\");", "7");
+ prints(Format.Converters);
+ prints(Format.FieldNamedInt);
}
@Test public void testForwardReturnTypes() throws Exception {
@@ -91,14 +147,13 @@ public class StringFormatTest extends TestC {
}
@Test public void testFloatAndAlternateFormats() throws Exception {
- prints("f32 x=1.25f; sys.io.p(\"%(x)|%f(x)|%.2e(x)|%.2G(x)|%#o(9)|% d(7)|%.0d(0)|%a(1.5)\");",
- "1.25|1.250000|1.25e+00|1.2|011| 7||0x1.8p+0");
+ prints(Format.FloatAndAlternateFormats);
runSYS("val format_noInline={ f32 x -> \"%(x)|%f(x)\"; }; val main={ -> sys.io.p(format_noInline(1.25f)); return 0; };",
"stringFormatFloat","1.25|1.250000",-1);
}
@Test public void testBufferGrowth() throws Exception {
- prints("sys.io.p(\"%0100d(17)|%.100f(1.0)\");", "0".repeat(98)+"17|1."+"0".repeat(100));
+ prints(Format.BufferGrowth);
}
@Test public void testLiteralRemainsConstant() {
@@ -107,18 +162,12 @@ public class StringFormatTest extends TestC {
}
@Test public void testBytesAndEmptyStrings() throws Exception {
- prints("val empty=\"%(\"\")\"; val bytes=\"a\\0b\"; sys.io.p(\"%(empty#):%s(bytes):%.2s(bytes):%c(0)\");",
- "0:a\0b:a\0:\0");
- prints("val s=\"π\"; sys.io.p(\"%(s):%(s#):%(s[0]):π\");", "π:2:207:π");
+ prints(Format.BytesAndEmptyStrings);
+ prints(Format.Utf8String);
}
@Test public void testDeferredParsing() throws Exception {
- prints("""
- struct S { u8[~] s; new S={ -> s="%("}) %(3)")"; }; };
- val s=new S;
- sys.io.p(s.s);
- for(int i=0; i<2; sys.io.p("%(i++) %("(")")) { }
- """, "}) 30 (1 (");
+ prints(Format.DeferredParsing);
}
@Test public void testImportedFormatter() throws Exception {
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/TestWorkspace.java b/chapter32/src/test/java/com/seaofnodes/simple/TestWorkspace.java
index 30cff89f..d875c47a 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/TestWorkspace.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/TestWorkspace.java
@@ -7,7 +7,7 @@ import java.nio.file.attribute.BasicFileAttributes;
/** Prepare a Make test group's working directory without sharing native outputs. */
public class TestWorkspace {
public static void main(String[] args) throws IOException {
- if( args.length!=2 || !args[0].matches("tests_group[0-7]") || !args[1].matches("[A-Za-z0-9_]+") )
+ if( args.length!=2 || !args[0].matches("tests_group[0-7]|sanity_group[0-2]") || !args[1].matches("[A-Za-z0-9_]+") )
throw new IllegalArgumentException("Expected test group and CPU_ABI");
Path root = Path.of("").toAbsolutePath().normalize();
Path work = root.resolve("build/tests").resolve(args[0]).normalize();
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/TypeTest.java b/chapter32/src/test/java/com/seaofnodes/simple/TypeTest.java
index 8f212bda..adcc1b3a 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/TypeTest.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/TypeTest.java
@@ -276,74 +276,77 @@ public class TypeTest {
public void testLatticeTheory() {
Type[] ts = Type.gather();
// Make partitions the outer loop between independent JVMs. A direct
- // JUnit/IDE invocation retains the full Cartesian-product coverage.
+ // JUnit/IDE invocation retains the full coverage.
int parts = Integer.parseInt(System.getProperty("simple.lattice.parts","1"));
int part = Integer.parseInt(System.getProperty("simple.lattice.part" ,"0"));
Assert.assertTrue("Invalid lattice partition",parts > 0 && parts <= ts.length && part >= 0 && part < parts);
- // Confirm commutative & complete
- for( int i=part; i<ts.length; i+=parts ) {
- Type t0 = ts[i];
- for( Type t1 : ts ) {
- check_commute (t0,t1);
- check_symmetric(t0,t1);
+ // Every triple reuses these pairs. Compute both operand orders rather
+ // than assuming commutativity in the table we are about to check.
+ Type[][] meets = new Type[ts.length][ts.length];
+ Type[][] joins = new Type[ts.length][ts.length];
+ for( int i=0; i<ts.length; i++ )
+ for( int j=0; j<ts.length; j++ ) {
+ meets[i][j] = ts[i].meet(ts[j]);
+ joins[i][j] = ts[i].join(ts[j]);
}
- }
- // Confirm associative
+ // Confirm commutative & complete, once per unordered pair.
for( int i=part; i<ts.length; i+=parts ) {
- Type t0 = ts[i];
- for( Type t1 : ts )
- for( Type t2 : ts )
- assoc(t0,t1,t2);
+ assertSame(ts[i],meets[i][i]);
+ for( int j=i; j<ts.length; j++ ) {
+ assertSame(meets[i][j],meets[j][i]);
+ check_symmetric(ts[i],ts[j],meets[i][j]);
+ }
}
+ // Each unordered triple represents all six permutations. Check every
+ // intermediate result in both operand orders; a pair's meet need not
+ // itself be in ts, so its commutativity must not be assumed.
+ for( int i=part; i<ts.length; i+=parts )
+ for( int j=i; j<ts.length; j++ )
+ for( int k=j; k<ts.length; k++ )
+ assoc(ts[i],ts[j],ts[k],meets[i][j],meets[i][k],meets[j][k]);
+
// Confirm symmetry. If A isa B, then A.join(C) isa B.join(C)
for( int i=part; i<ts.length; i+=parts ) {
Type t0 = ts[i];
- for( Type t1 : ts )
- if( t0.isa(t1) )
- for( Type t2 : ts ) {
- Type t02 = t0.join(t2);
- Type t12 = t1.join(t2);
+ for( int j=0; j<ts.length; j++ )
+ if( meets[i][j]==ts[j] )
+ for( int k=0; k<ts.length; k++ ) {
+ Type t02 = joins[i][k];
+ Type t12 = joins[j][k];
Type mt = t02.meet(t12);
- assertSame(t0+" isa "+t1+" joined "+t2, mt,t12);
+ if( mt!=t12 ) assertSame(t0+" isa "+ts[j]+" joined "+ts[k], mt,t12);
}
}
}
- // By design in meet, args are already flipped to order _type, which forces
- // symmetry for things with badly ordered _type fields. The question is
- // still interesting for other orders.
- private static void check_commute( Type t0, Type t1 ) {
- if( t0==t1 ) return;
- if( t0.is_simple() && !t1.is_simple() ) return; // By design, flipped the only allowed order
- Type mta = t0.meet(t1);
- Type mtb = t1.meet(t0); // Reverse args and try again
- assertSame(mta,mtb);
- }
-
// A & B = MT
// Expect: ~A & ~MT == ~A
// Expect: ~B & ~MT == ~B
private static void check_symmetric( Type t0, Type t1 ) {
+ check_symmetric(t0,t1,t0.meet(t1));
+ }
+
+ private static void check_symmetric( Type t0, Type t1, Type mt ) {
if( t1==t0 ) return;
- Type mt = t0.meet(t1);
Type dm = mt.dual();
Type d0 = t0.dual();
Type d1 = t1.dual();
Type ta = dm.meet(d1);
Type tb = dm.meet(d0);
- assertSame(t0+" & "+t1+" mt="+mt, ta,d1);
- assertSame(t0+" & "+t1+" mt="+mt, tb,d0);
+ if( ta!=d1 ) assertSame(t0+" & "+t1+" mt="+mt, ta,d1);
+ if( tb!=d0 ) assertSame(t0+" & "+t1+" mt="+mt, tb,d0);
}
- private static void assoc( Type t0, Type t1, Type t2 ) {
- Type t01 = t0 .meet(t1 );
- Type t12 = t1 .meet(t2 );
- Type t01_2 = t01.meet(t2 );
- Type t0_12 = t0 .meet(t12);
- assertSame(t0+" & "+t1+" & "+t2, t01_2,t0_12);
+ private static void assoc( Type a, Type b, Type c, Type ab, Type ac, Type bc ) {
+ // The six original associativity equalities connect these six values
+ // in a cycle. Equality to one common result checks the same property.
+ Type result = ab.meet(c);
+ if( result!=c.meet(ab) || result!=ac.meet(b) || result!=b.meet(ac) ||
+ result!=bc.meet(a) || result!=a.meet(bc) )
+ Assert.fail("Associativity: "+a+" & "+b+" & "+c);
}
// Test cyclic types and meets
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java b/chapter32/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java
index edb2519c..ae935da0 100644
--- a/chapter32/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java
+++ b/chapter32/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java
@@ -85,7 +85,7 @@ public class RegAllocTestSupport {
new Op(null,A,null,false,code._start,def);
RegAlloc alloc = new RegAlloc(code);
assertTrue(BuildLRG.run(0,alloc));
- assertFalse("A live value cannot survive a register kill",IFG.build(0,alloc));
+ assertFalse("A live value cannot survive a register kill",new IFG().build(0,alloc));
}
public static void nullUseMask() {
@@ -95,7 +95,7 @@ public class RegAllocTestSupport {
new Op(null,null,null,false,code._start,def); // Scheduling dependency only.
RegAlloc alloc = new RegAlloc(code);
assertTrue(BuildLRG.run(0,alloc));
- assertTrue(IFG.build(0,alloc));
+ assertTrue(new IFG().build(0,alloc));
}
public static void independentFunctions() {
@@ -262,7 +262,7 @@ public class RegAllocTestSupport {
assertTrue(BuildLRG.run(0,alloc));
assertNull(alloc.lrg(top));
assertSame(alloc.lrg(def),alloc.lrg(phi));
- assertTrue(IFG.build(0,alloc));
+ assertTrue(new IFG().build(0,alloc));
alloc.insertBefore(phi,slot,"test",(byte)0,alloc.lrg(phi));
assertSame(top,phi.in(slot));
}
diff --git a/chapter32/src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java b/chapter32/src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java
new file mode 100644
index 00000000..c218e98b
--- /dev/null
+++ b/chapter32/src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java
@@ -0,0 +1,20 @@
+package com.seaofnodes.simple.type;
+
+import com.seaofnodes.simple.util.BAOS;
+import java.util.HashMap;
+import static org.junit.Assert.*;
+
+public class PackedTypeTestSupport {
+ public static void singleton(int id) {
+ Type.TAGOFFS();
+ TypeFunPtr fun=TypeFunPtr.make((byte)2,true,new Type[0],TypeInteger.BOT,XInt.make(id));
+ BAOS out=new BAOS();
+ fun.packed(out,new HashMap<>());
+ assertEquals(id<=254 ? 2 : 4,out.size());
+ BAOS in=new BAOS(out.toByteArray());
+ TypeFunPtr copy=(TypeFunPtr)Type.packed(in,new String[]{""});
+ assertEquals(id,copy.fidx());
+ assertEquals(0,copy.nargs());
+ assertEquals(out.size(),in.size());
+ }
+}
diff --git a/skills/chapter25-codex-notes.md b/skills/chapter25-codex-notes.md
index e7362c3b..b32fdd15 100644
--- a/skills/chapter25-codex-notes.md
+++ b/skills/chapter25-codex-notes.md
@@ -35,6 +35,31 @@ callers promise no initialized fields. No new passes or backward demand walks.
## Chapter 32: restart guidance (2026-11-15)
+Use `make -j8 tests` as the normal validation/timing command going forward.
+The November 16 sweep found both `-j4` and `-j16` slower on this Windows host;
+retain `ActiveProcessorCount=2`. Keep lattice checks in their own JVMs: combining
+them after compiler-heavy tests can exhaust the existing 16-bit type IDs.
+The full lattice is required even in fast checks. `make -j8 sanity` keeps its
+four partitions plus chapter/backend and focused compiler regressions; full
+`make -j8 tests` retains library/application/CLI integration. The lattice now
+caches pairs and checks all six intermediate results per unordered triple;
+do not reduce it to one associativity equality per unordered triple, which
+would assume commutativity for intermediate types outside the gathered set.
+
+On 2026-11-16, Cliff requested backporting the shared class receiver to chapter
+28a, imported-summary handling to 28b, and both through the later snapshots.
+The chapter28a README now owns that explanation. Preserve 28a/28b's monolithic
+parser and Scope-based instance construction when adapting this fix; do not
+copy chapter29's parser or construction machinery backward. Native fixtures
+must also respect the older chapters' 64-bit `int` ABI.
+
+The Phi factoring fix starts in chapter5: match `x*2` as `x+x` without expanding
+the graph. Chapter14 also recognizes `x<<1`; chapter19 and later use that shift
+as doubling's strength-reduced representation. Keep each snapshot's existing
+factoring guards, type checks, and dependency direction. The chapter5 README
+teaches the rule; chapter32 retains the investigation and measurements. No
+allocator scoring experiments were adopted or backported.
+
Continue in `chapter32/` on branch `ch32`. Chapter 31 is complete as the
graphics, games, and library snapshot; keep its compiler before the speedups.
The chapter32 README teaches the current performance work: parallel test JVMs