summaryrefslogtreecommitdiff
path: root/chapter33
diff options
context:
space:
mode:
Diffstat (limited to 'chapter33')
-rw-r--r--chapter33/README.md6
-rw-r--r--chapter33/docs/33-grammar.md13
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/README.md7
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java68
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Iter.java26
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java5
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java13
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java43
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java5
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java46
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java18
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java59
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java22
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java8
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java9
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java22
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java9
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java6
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java143
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java35
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java12
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java125
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java9
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/MemJoinNode.java368
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java239
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/MemOpNode.java14
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java8
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/Node.java7
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java8
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java1
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java30
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java41
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java5
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java3
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java3
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java19
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java7
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Construction.java11
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java9
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java15
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Parser.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/References.java26
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java4
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java48
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java3
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/print/IRPrinter.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java5
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/type/Field.java2
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java13
-rw-r--r--chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java4
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java77
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java27
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java14
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java6
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java4
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java10
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java6
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java5
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java48
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java5
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java18
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java6
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java21
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java16
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java65
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java47
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/Eval2.java16
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java29
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/MemJoinTest.java (renamed from chapter33/src/test/java/com/seaofnodes/simple/MemMergeTest.java)55
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/SchedulingTest.java2
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java73
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java75
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java4
-rw-r--r--chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java35
88 files changed, 1563 insertions, 741 deletions
diff --git a/chapter33/README.md b/chapter33/README.md
index 5f231240..2c995ca5 100644
--- a/chapter33/README.md
+++ b/chapter33/README.md
@@ -8,6 +8,12 @@ This chapter starts with the completed chapter 32 compiler. Automatic memory
management will be introduced in small steps, keeping the full test suite passing.
No new allocation analysis or reclamation is implemented yet.
+Unloaded function summaries retain their possible callees through function-pointer
+edges. These references keep a single default caller on each target without
+publishing its function pointer. Loading a body connects its concrete calls before
+releasing the summary references. Single-caller inlining therefore waits until
+both escaped callers and live summarized callers have been accounted for.
+
From this directory, run `make -j8 tests` for the full suite, including the type
lattice, compiler regressions, library tests, and native integration tests.
Run `make -j8 release` to build the compiler and runtime.
diff --git a/chapter33/docs/33-grammar.md b/chapter33/docs/33-grammar.md
index 7e9ef8cd..2de46bb9 100644
--- a/chapter33/docs/33-grammar.md
+++ b/chapter33/docs/33-grammar.md
@@ -256,8 +256,12 @@ one-pass IR builder:
`Declarations` and `Types` use speculative parsing and cursor restore;
qualified type lookup also stops before a suffix that belongs to an expression.
- `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.
+ reads, and updates share the field-access path, including inside the owning
+ initializer. Both class and instance declarations emit Stores in source
+ order; helper calls see the preceding writes and subsequent reads see the
+ helpers' effects. Instance defaults run once per instance. Class fields use
+ public alias memory; an instance under construction uses its private memory.
+ Lexically local bindings use SSA; file-level bindings are class fields.
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
@@ -265,8 +269,9 @@ one-pass IR builder:
discovery, so later fields have local slots. Both use `Lexer.skipTo`, which
ignores delimiters inside comments and quoted text.
- `Structs.parseInitializer` parses a file or struct body as a function while
- discovering fields. `Functions.parseBody` still owns function scope/return
- construction; moving it does not change constructor or memory semantics.
+ discovering fields. `declareField` emits both kinds of field initialization;
+ `finishInitializer` closes their types without emitting deferred Stores.
+ `Functions.parseBody` owns function scope/return construction.
The syntax chart does not describe all name/type restrictions. In particular,
prefix updates require an already-known non-pointer binding, and a private-class
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/README.md b/chapter33/src/main/java/com/seaofnodes/simple/README.md
index 6b321e8e..021dad22 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/README.md
+++ b/chapter33/src/main/java/com/seaofnodes/simple/README.md
@@ -13,3 +13,10 @@
The root package retains `sys.java`, which loads the default Simple namespace.
Java tests, the command-line driver, and the IR evaluator live under
`src/test/java`; the Simple standard library lives under `src/main/smp`.
+
+Loop normalization runs after `FinalizeIR` and before `TypeCheck`. It builds the
+loop tree and gives infinite loops structural exits through `NeverNode`, while
+preserving their actual return state for diagnostics and serialized summaries.
+Lowering assigns new control nodes to the containing loop of the operation it
+expands. It does not rebuild the loop tree. Inlining after normalization queues
+the affected caller for a local rebuild once its peepholes have settled.
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
index 4b0e7de4..e677e855 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
@@ -27,10 +27,10 @@ public class CodeGen {
Opto, // SCCP, numeric modes, seed the peephole worklist
IterPostOpto, // Peepholes and inlining using SCCP results
FinalizeIR, // Field layout, offset cleanup, function/CU roots
+ LoopTree, // Normalize loops and insert structural exits
TypeCheck, // Last check for bad programs
Serialize, // Save ideal IR, including opaque class initialization
Lower, // Expand checked class initialization to ordinary IR
- LoopTree, // Build a loop tree; break infinite loops
Unlink, // Unlink call sites before machine code generation
Select, // Convert to target hardware nodes
Schedule, // Global schedule (code motion) nodes
@@ -196,6 +196,7 @@ public class CodeGen {
step(target, Phase.IterPostOpto, this::iterPostOpto, dump);
// Field layouts; field symbols become constant offsets
step(target, Phase.FinalizeIR, this::finalizeIR, dump);
+ step(target, Phase.LoopTree, this::loopTree, dump);
// Final error check - bad programs fail here
step(target, Phase.TypeCheck, this::typeCheck, dump);
// Save reloadable ideal IR for a later seperate compilation
@@ -203,9 +204,6 @@ public class CodeGen {
// Eval2 executes ideal operations, including CLInit, directly. Only
// machine compilation expands them before scheduling.
step(target, Phase.Lower, () -> { if( cpu!=null ) lower(); }, dump);
- // Compute the loop-tree, used for approximating exec frequencies for
- // scheduling and register allocation
- step(target, Phase.LoopTree, this::loopTree, dump);
// Detach call-graph edges; ideal execution retains unloaded summaries
// as dispatch targets and schedules their bodies on first use.
step(target, Phase.Unlink, () -> unlink(cpu!=null), dump);
@@ -297,6 +295,18 @@ public class CodeGen {
public final GlobalBits _aliases = new GlobalBits();
public int alias(String clz) { return _aliases.next(clz); }
+ // Field visibility is independent of whether an instance has escaped.
+ // Seed from closed declarations before Opto, and extend when importing.
+ private final BitSet _publicAliases = new BitSet();
+ public void recordPublicAliases(TypeStruct ts) {
+ for( Field fld : ts._fields )
+ if( fld._alias>1 && fld._fname.charAt(0)!='_' && !ts.hiddenInit(fld) )
+ _publicAliases.set(fld._alias);
+ }
+ public boolean publicAlias(int alias) {
+ return (_phase==null || _phase.ordinal()<Phase.Opto.ordinal()) || _publicAliases.get(alias);
+ }
+
// C storage has one global alias per symbol, including across object files.
public int externAlias(String name) { return _aliases.next("C:"+name,GlobalBits.RESERVED); }
@@ -362,17 +372,27 @@ public class CodeGen {
return null;
}
- // An inline import can reveal a call to a private initializer whose
+ // An inline import can reveal a call to a private function whose
// unused summary was deleted after SCCP. Recreate the wrapper from its
// saved metadata; this is a direct call, not a function-pointer escape.
public FunNode restoreClinit(CompUnit cu) {
- if( cu==null || cu._obj==null ) return null;
+ return restoreSummary(cu,0);
+ }
+ public FunNode restoreFunction(int fidx) {
+ return restoreSummary(StaticData.owner(this,_fidxs.owner(fidx)),fidx);
+ }
+ private FunNode restoreSummary(CompUnit cu, int fidx) {
+ if( _phase.ordinal()<=Phase.Opto.ordinal() || cu==null || cu._src!=null || cu._obj==null ) return null;
ElfReader elf = getElf(cu._obj);
- if( elf._nodes!=null ) return null;
+ if( elf._nodes!=null || elf._functions==null ) return null;
for( FunctionSummary summary : elf._functions )
- if( summary.name().equals(TypeStruct.addClzPrefix(cu._cname)+".<clinit>") ) {
- if( _stop._inputs.find(cu._stop)==-1 ) _stop.addDef(cu._stop);
- return summary.install(this,cu);
+ if( fidx==0 ? summary.name().equals(TypeStruct.addClzPrefix(cu._cname)+".<clinit>")
+ : summary.sig().fidx()==fidx ) {
+ if( _stop._inputs.find(cu._stop)==-1 ) add(_stop).addDef(cu._stop);
+ FunNode fun = summary.install(this,cu);
+ fun.summary().bindCallees();
+ fun.summary().linkCallees();
+ return fun;
}
return null;
}
@@ -533,7 +553,7 @@ public class CodeGen {
// ---------------------------
// Last check for bad programs
- public CodeGen typeCheck() { return phase(Phase.TypeCheck, _phase==Phase.FinalizeIR, () -> TypeCheck.run(this)); }
+ public CodeGen typeCheck() { return phase(Phase.TypeCheck, _phase==Phase.LoopTree, () -> TypeCheck.run(this)); }
// ---------------------------
// TypeCheck queued surviving CLInits during its existing error walk.
@@ -544,8 +564,28 @@ public class CodeGen {
// ---------------------------
// Build the loop tree; break never-exit loops
public CodeGen loopTree() {
- return phase(Phase.LoopTree, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize),
- () -> _start.buildLoopTree(_linker,_stop));
+ return phase(Phase.LoopTree, _phase==Phase.FinalizeIR, () -> {
+ _start.buildLoopTree(_linker,_stop);
+ Iter.repair(this); // Structural exits can change Return/Stop bounds.
+ _iter.iterate(this);
+ });
+ }
+
+ // Only inlining changes loop nesting after normalization. Lowered diamonds
+ // inherit their enclosing loop; rebuild only callers that receive code.
+ private WorkList<FunNode> _loopWork;
+ public void invalidateLoopTree(FunNode fun) {
+ if( _start._ltree==null ) return;
+ if( _loopWork==null ) _loopWork=new WorkList<>();
+ _loopWork.push(fun);
+ }
+ boolean updateLoopTrees() {
+ if( _loopWork==null || _loopWork.isEmpty() ) return false;
+ FunNode fun;
+ while( (fun=_loopWork.pop())!=null )
+ if( !fun.isDead() && !fun._type.isHigh() ) fun.rebuildLoopTree(_stop);
+ Iter.repair(this);
+ return true;
}
// ---------------------------
@@ -586,7 +626,7 @@ public class CodeGen {
unlink(true);
}
private void unlink(boolean removeImports) {
- phase(Phase.Unlink, _phase==Phase.LoopTree, () -> {
+ phase(Phase.Unlink, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize), () -> {
_start.setDef(2,null); // Releases the compiler-only escape analysis.
if( removeImports ) Unlink.run(this,true);
else Unlink.forEval(this,_start,_stop);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java
index 37baf926..2e9be867 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionSummary.java
@@ -22,7 +22,7 @@ record FunctionSummary(TypeFunPtr sig, TypeTuple state, String name, int size, i
Node value = new ProjNode(body,2,"value").init();
ReturnNode ret = new ReturnNode(ctrl,memory,value,rpc,fun).init();
fun.setRet(ret);
- cu._stop.addDef(ret);
+ code.add(cu._stop).addDef(ret);
code.link(fun);
return fun;
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java
index d7837c43..cf460c16 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/GlobalCodeMotion.java
@@ -303,7 +303,7 @@ public abstract class GlobalCodeMotion {
visit.set(def._nid);
for( Node out : def._outputs )
if( out instanceof MemOpNode ld && ld._isLoad && late[ld._nid]==null ) work.push(ld);
- if( def instanceof MemMergeNode )
+ if( def instanceof MemJoinNode )
for( int i=1; i<def.nIns(); i++ )
if( def.in(i)!=null ) wakeLoads(def.in(i),late,work,visit);
}
@@ -325,7 +325,7 @@ public abstract class GlobalCodeMotion {
lca = anti_dep(load,phi.region().cfg(i),load.mem().cfg0(),lca,null,anti);
} else {
// Hunt for clobbering stores
- assert mem instanceof MemOpNode || mem instanceof EscapeNode ||
+ assert mem instanceof MemOpNode || mem instanceof MemJoinNode ||
mem instanceof CallNode || mem instanceof CLInitNode;
assert late[mem._nid]!=null;
lca = anti_dep(load,late[mem._nid],mem.cfg0(),lca,mem,anti);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Iter.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Iter.java
index 72cca23b..30efea28 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Iter.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Iter.java
@@ -22,20 +22,30 @@ public abstract class Iter {
private static Type iterImportReset(Type t) {
if( t.isHigh() )
return t.dual();
- if( t instanceof TypeMem mem )
- return TypeMem.make(mem._alias,iterImportReset(mem._t),mem._one,mem._clz,mem._final,TypeSet.FULL,TypeSet.FULL);
- if( t instanceof TypeMemPtr )
+ // Saved escape identities are already rebased into this compilation.
+ // Repair adds escapes from the new callers. Seeding FULL here instead
+ // feeds spurious escapes around the Start/Stop cycle, where ordinary
+ // lifting cannot recover the exclusions.
+ switch( t ) {
+ case TypeMem mem -> {
+ return TypeMem.make( mem._alias, iterImportReset( mem._t ), mem._one, mem._clz, mem._final, mem._escFs, mem._escAs );
+ }
+ case TypeMemPtr typeMemPtr -> {
return t.makeStorage();
- if( t instanceof TypeStruct )
+ }
+ case TypeStruct typeStruct -> {
return t.makeStorage();
- if( t instanceof TypeTuple tt ) {
+ }
+ case TypeTuple tt -> {
TypeTuple rez = tt;
- for( int i=0; i<tt._types.length; i++ ) {
- Type tx = iterImportReset(tt._types[i]);
- if( tx != tt._types[i] ) rez = rez.makeFrom(i,tx);
+ for( int i = 0; i < tt._types.length; i++ ) {
+ Type tx = iterImportReset( tt._types[i] );
+ if( tx != tt._types[i] ) rez = rez.makeFrom( i, tx );
}
return rez;
}
+ default -> {}
+ }
return t;
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
index 54ccef09..8ce07a9c 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
@@ -88,7 +88,10 @@ public class IterPeeps {
// Inlined, run peeps until clean again
if( inlined ) { didInline = true; continue; }
// No more candidates, check the defer list
- if( !didInline ) break; // No more progress, so all the "maybe inline after cleanup" do not progress
+ if( !didInline ) {
+ if( code.updateLoopTrees() ) continue;
+ break; // No more progress, so deferred calls cannot inline.
+ }
// Some inlining happened, retry all the "try again after cleanup" calls
didInline = false;
code.addAll(defer);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java
index 63a39292..0b579d2a 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java
@@ -26,6 +26,8 @@ abstract public class Opto {
// get a fairly precise set of Call Graph edges between CallNodes and
// FunNodes.
public static void opto(CodeGen code) {
+ for( Type t : Parser.TYPES.values() )
+ if( t instanceof TypeStruct ts ) code.recordPublicAliases(ts);
TypeSet foreign = code._fidxs.foreign();
for( int fidx : code._externFunc.keySet() ) foreign = foreign.with(fidx);
code._start._foreign = TypeMem.START.makeFrom(foreign,code._aliases.foreign());
@@ -200,10 +202,10 @@ abstract public class Opto {
}
}
- // Function is now reachable by unknown callers through Start. The
+ // Function is reachable by escaped or still-summarized callers through Start. The
// Memory and callback defaults read Start's changing outside state.
// Scalar defaults remain constants; hidden self uses the owning class.
- static void linkStart( CodeGen code, FunNode fun ) {
+ public static void linkStart( CodeGen code, FunNode fun ) {
assert !fun.isDead();
StartCUNode start = fun._compunit._start;
if( !fun.unknownCallers() ) {
@@ -234,7 +236,6 @@ abstract public class Opto {
if( n.isDead() ) continue;
count++;
Type oval = n._type, nval = n.compute();
- if( n instanceof CLInitNode init ) init.link();
// Remember possible peephole work without walking the graph again.
// SCCP can still fall back to the old type, so filter at the end.
if( nval!=oldTypes.atX(n._nid) || n.isUnlocked() ) changes.push(n);
@@ -273,6 +274,12 @@ abstract public class Opto {
if( n instanceof StartNode )
linkStart(code,(TypeTuple)n._type);
+ if( n instanceof CLInitNode init ) init.link();
+ // A non-returning summary can still call other functions. Use entry
+ // reachability, not its returned control, even if nval is unchanged.
+ if( n instanceof SummaryNode summary && !summary.in(0)._type.isHigh() )
+ summary.linkCallees();
+
// Since n._type changed, visit all output neighbors
code._iter.addAll(n._outputs);
// SCCP consumes these without running peepholes. Save them for
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
index 882a0f8a..18dd8015 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ParseAll.java
@@ -1,6 +1,7 @@
package com.seaofnodes.simple.codegen;
import com.seaofnodes.simple.parser.Parser;
+import com.seaofnodes.simple.parser.Lexer;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.print.*;
import com.seaofnodes.simple.type.*;
@@ -28,6 +29,7 @@ public abstract class ParseAll {
private static final Ary<CompUnit> WORK = new Ary<>(CompUnit.class);
private static final Ary<CompUnit> NEEDS_LOAD = new Ary<>(CompUnit.class);
+ private static final HashMap<String,Lexer> REQUIRED_TYPES = new HashMap<>();
// Return a compilation unit (cached or new). If new, it does not necessarily
// need to be compiled.
@@ -88,6 +90,7 @@ public abstract class ParseAll {
private static void parseAll(CodeGen code, CompUnit cunit) {
WORK.clear(); // Cleanup from prior tests
NEEDS_LOAD.clear();
+ REQUIRED_TYPES.clear();
// Prime the pump with the first CompUnit
enqueue(cunit);
// Work through all unparsed compilation units and parse
@@ -103,6 +106,9 @@ public abstract class ParseAll {
// Load all pre-compiled CompUnits
for( CompUnit cu : NEEDS_LOAD )
loadSummaries(code,cu);
+ for( CompUnit cu : NEEDS_LOAD )
+ for( Node ret : cu._stop._inputs )
+ ((ReturnNode)ret).fun().summary().bindCallees();
// Many types will have been declared cyclically either internally or
// across multiple compilation units.
@@ -115,6 +121,9 @@ public abstract class ParseAll {
TypeStruct[] tss = Type.closeOver(ary.asAry(),Parser.TYPES);
for( TypeStruct ts : tss )
Parser.TYPES.put(ts._name,ts);
+ for( var required : REQUIRED_TYPES.entrySet() )
+ if( !(Parser.TYPES.get(required.getKey()) instanceof TypeStruct ts) || ts._fref )
+ throw Parser.error("Unknown type '"+required.getKey()+"'",required.getValue());
for( CompUnit cu : code._compunits.values() )
if( cu._ext==null )
cu._clz = (TypeStruct)Parser.TYPES.get(TypeStruct.addClzPrefix(cu._cname));
@@ -156,9 +165,11 @@ public abstract class ParseAll {
if( Parser.TYPES.get(typeName) instanceof TypeStruct ts && !ts._fref ) continue;
try {
CompUnit xcunit = findRequiredType(code,cunit,typeName);
- if( xcunit != null )
+ if( xcunit != null ) {
cunit.addDep(xcunit);
- else
+ if( !typeName.equals(xcunit._cname) || (xcunit._obj!=null && xcunit._src==null) )
+ REQUIRED_TYPES.putIfAbsent(typeName,required.getValue());
+ } else
throw Parser.error("Unknown type '"+typeName+"'",required.getValue());
} catch( IOException ioe ) {
throw new RuntimeException(ioe);
@@ -175,7 +186,16 @@ public abstract class ParseAll {
if( xcunit != null )
return xcunit;
}
- return findCUnitExternalSimple(code,typeName);
+ // A nested struct is declared inside its owning object; it need not
+ // have its own compilation-unit symbol. Validate the complete name
+ // after the owner's declarations have been loaded and closed.
+ for( String name=typeName; ; ) {
+ CompUnit cu = findCUnitExternalSimple(code,name);
+ if( cu!=null ) return cu;
+ int dot = name.lastIndexOf('.');
+ if( dot<0 ) return null;
+ name = name.substring(0,dot);
+ }
}
// Load the public symbols for this CompUnit, and add dependent CompUnits to the NEEDS_LOAD list.
@@ -243,6 +263,7 @@ public abstract class ParseAll {
cunit._clz = (TypeStruct)Parser.TYPES.get(TypeStruct.addClzPrefix(cunit._cname));
StartNode lstart = (StartNode)elf._nodes.at(0);
StopNode lstop = ( StopNode)elf._nodes.last();
+ Ary<SummaryNode> replaced = new Ary<>(SummaryNode.class);
// Add all new loaded functions to the linker table
for( Node n : lstop._inputs ) {
@@ -257,6 +278,8 @@ public abstract class ParseAll {
FunNode old = code._link(fun.sig().fidx());
code.link(fun);
if( old!=null && old.summary()!=null && !old.isDead() ) {
+ // Keep outgoing references until the loaded calls are linked.
+ replaced.add(old.summary().keep());
old.ret().keep();
for( int i = 1; i<old.nIns(); i++ )
if( old.in(i) instanceof CallNode call ) {
@@ -280,6 +303,10 @@ public abstract class ParseAll {
code.releaseReplacedNode(oldStart);
int idx = code._stop._inputs.find(oldStop);
if( idx!=-1 ) code._stop.delDef(idx);
+ // Retained summary defaults can still use the old memory input.
+ // Merge it before protecting the new projection from DCE below.
+ ProjNode newMem = cunit._start.proj(1);
+ if( oldMem!=null && !oldMem.isDead() && newMem!=null && oldMem!=newMem ) oldMem.subsume(newMem);
oldStart.subsume(cunit._start);
}
// Saved types describe the library's original compilation. Repair
@@ -289,6 +316,16 @@ public abstract class ParseAll {
if( startMem!=null ) code.keepUntilFinalize(startMem);
Iter.imports(code,elf._nodes);
+ // Deserialization may omit an entry's default. Other unloaded bodies
+ // can still reference it, via FunPtrs moved from the old Return above.
+ for( Node n : elf._nodes )
+ if( n instanceof FunNode fun && !fun.isDead() && fun.hasSummaryCallers() )
+ Opto.linkStart(code,fun);
+ Iter.repair(code);
+ for( Node n : elf._nodes )
+ if( n instanceof CallNode call && !call.isDead() ) call.idealize();
+ for( SummaryNode summary : replaced ) code.add(summary.unkeep());
+
// Add the new top-level loaded class
Parser.TYPES.put(cunit._clz._name,cunit._clz);
// Layout belongs to the allocator's object result. An initializer's
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
index c3be4b71..585cdbf1 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
@@ -338,7 +338,10 @@ public class RegAlloc {
if( splitEmptyMaskByUse(round,lrg) )
return true;
}
- if( lrg._mask.isEmpty() && lrg._multiDef && lrg._1regUseCnt > 1 && lrg._1regDefCnt <= 1 ) {
+ // Several call results can share this Phi web (all defined in RAX),
+ // while its arguments require different registers. Isolate those uses
+ // even when there is more than one constrained definition.
+ if( lrg._mask.isEmpty() && lrg._multiDef && lrg._1regUseCnt > 1 ) {
if( splitEmptyMaskSingleUses(round,lrg) )
return true;
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
index ec135149..7bc8b8ff 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
@@ -52,6 +52,12 @@ public class Serialize {
code._serials.put(cu,serial);
if( cu._fname.equals(code._srcName==null ? "Test" : code._srcName) ) code._serial=serial;
}
+ // Saved bodies can still call these functions even if lowering later
+ // inlines their last local caller. Keep native entries for that saved
+ // interface, using the already analyzed parameter bounds.
+ for( FunNode fun : code._linker )
+ if( fun!=null && !fun.isDead() && fun.isFromSource() )
+ Unlink.retainEntry(code,fun);
}
private BAOS serialize(CodeGen code, CompUnit top) {
@@ -104,9 +110,9 @@ public class Serialize {
BAOS baos = new BAOS();
// A - Print the C0DE header; last byte is the version number.
- // Format 12: TypeSet defaults and finite exception words replace XInt.
+ // Format 13: MemJoin triples replace MemMerge and Escape nodes.
// Earlier object formats must be rebuilt.
- baos.write('C').write('0').write('D').write('C');
+ baos.write('C').write('0').write('D').write('D');
// Count unique Types
var types = new HashMap<Type,Integer>();
@@ -126,7 +132,7 @@ public class Serialize {
if( n instanceof CallEndNode cend ) cend._rpc.gather(types);
if( n instanceof FunNode fun ) {
fun.sig().gather(types);
- TypeTuple state = (TypeTuple)fun.ret()._type;
+ TypeTuple state = fun.returnState();
TypeMem mem = (TypeMem)state.mem();
// Retention can happen on a path that never returns. The
// unit's escape summary includes those native-call effects.
@@ -138,6 +144,9 @@ public class Serialize {
}
if( n instanceof ParmNode parm ) parm._declaredType.gather(types);
if( n instanceof TypeNode con ) con._con .gather(types);
+ if( n instanceof MemJoinNode join )
+ for( int i=0; i<join.size(); i++ )
+ if( join.fld(i)!=null ) join.fld(i).gather(types);
}
stopType.gather(types);
startType.gather(types);
@@ -270,8 +279,6 @@ public class Serialize {
int count = n.nIns();
for( int j=0; j<count; j++ ) {
if( !writeInput(n,j,anodes) ) continue;
- 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.
@@ -335,8 +342,8 @@ public class Serialize {
Type.TAGOFFS();
// A - Read a header
- if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='C' )
- throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file");
+ if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='D' )
+ throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file "+elf._file);
// B - Packed read of #strings, then strings
int ndependents = bais.packed4(); // Number of dependent object files
@@ -368,8 +375,8 @@ 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() != 'C' )
- throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" );
+ if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != 'D' )
+ throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file "+elf._file );
// B - Packed read of #strings, then strings
int ndependents = bais.packed4(); // Number of dependent object files
@@ -421,8 +428,10 @@ public class Serialize {
elf._clz = (TypeStruct)types[1/*skip zero*/];
assert elf._clz._name==strs[1/*skip null ptr*/];
for( Type type : types )
- if( type instanceof TypeStruct ts )
+ if( type instanceof TypeStruct ts ) {
installType(ts);
+ code.recordPublicAliases(ts);
+ }
for( Type type : types ) {
if( !(type instanceof TypeStruct ts) || !TypeStruct.startsClzPrefix(ts._name) )
continue;
@@ -467,6 +476,12 @@ public class Serialize {
Type[] types = tread.types();
String[] strs = tread.strs();
GlobalBits fileAliases = tread.fileAliases();
+ // The saved CFG has structural exits. Keep its nonreturning summaries
+ // available for diagnostics when a body is loaded later for inlining.
+ HashMap<Integer,TypeTuple> nonreturning = new HashMap<>();
+ for( FunctionSummary summary : elf._functions )
+ if( summary.state().ctl()==Type.XCONTROL )
+ nonreturning.put(summary.sig().fidx(),summary.state());
// D - Read the nodes
@@ -492,6 +507,7 @@ public class Serialize {
if( n instanceof FunNode fun ) {
assert cu != null;
fun._compunit = cu;
+ fun._semanticReturn=nonreturning.get(fun.sig().fidx());
if( fun._name==null || fun._name.isEmpty() ) fun._name=fidxs.symbol(fun.sig().fidx());
}
if( n instanceof ExternNode ext && ext._con instanceof TypeFunPtr tfp && tfp.isConstant() ) {
@@ -505,17 +521,11 @@ public class Serialize {
// Node edges
for( Node n : nodes ) {
- int len = n instanceof MemMergeNode mem ? mem.readSize() : n.nIns();
+ int len = 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);
- // Remap only explicit slices; omitted aliases use the default.
- if( n instanceof MemMergeNode mem && i>=2 ) {
- if( def==null ) continue;
- int alias = aliases.map(fileAliases,fileAlias);
- mem.alias(alias,def);
- } else n.setDefX(i,def);
+ n.setDefX(i,def);
// Call's output[0] is always the CallEnd
if( n instanceof CallEndNode cend && i==0 ) {
var outs = cend.call()._outputs;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java
index 3d3a40dd..55abab52 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java
@@ -129,7 +129,7 @@ public final class StaticData {
if( f._extern ) continue;
int off=ts.offset(idx);
while( bits.size()<obj.offset+off ) bits.write(0);
- if( f._fname.equals("[]") ) ((TypeConAry)f._t).write(bits);
+ if( f._fname=="[]" ) ((TypeConAry)f._t).write(bits);
else {
Type value=f._t.isConstant() ? f._t : f._t.makeZero();
int log=f._t.log_size();
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java
index bb9a6196..3b03e941 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Unlink.java
@@ -1,11 +1,29 @@
package com.seaofnodes.simple.codegen;
import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Ary;
// Discard call-graph edges after LoopTree. Machine selection keeps only this
// object's bodies; ideal evaluation keeps imports so their calls can execute.
abstract class Unlink {
+ // A code-generation entry does not publish a function pointer or widen
+ // any parameter. It preserves an already checked callable implementation.
+ static void retainEntry(CodeGen code, FunNode fun) {
+ StartNode start = fun._compunit._start;
+ if( fun.nIns()>1 && fun.in(1)==start ) return;
+ code.add(fun).insertDef(1,start);
+ for( Node use : fun._outputs )
+ if( use instanceof ParmNode parm ) {
+ // Preserve the range, not a recursive widening iteration.
+ Type seed = parm._type instanceof TypeInteger ti ? ti.makeWide((byte)0) : parm._type;
+ code.add(parm).insertDef(1,ConstantNode.seed(seed).init());
+ code.addAll(parm._outputs);
+ parm.moveDepsToWorklist();
+ }
+ code.keepInCompUnit(fun);
+ }
+
// Disconnect compiler-only interprocedural edges before scheduling. Keep
// signatures in the linker; runtime calls resolve FIDXs, not graph edges.
static Ary<FunNode> forEval(CodeGen code, StartNode start, StopNode stop) {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
index ca30d868..6859f711 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
@@ -85,9 +85,9 @@ public class BulkMemPhiNode extends PhiNode {
if( ((RegionNode)region()).inProgress() || region().nIns()<=1 )
return null; // Input is in-progress
- // "Peek through" a MemMerge that covers this alias set on its default
+ // "Peek through" a MemJoin that covers this alias set on its default
for( int i=1; i<nIns(); i++ )
- if( in(i) instanceof MemMergeNode mmm && canPeek(mmm) ) {
+ if( in(i) instanceof MemJoinNode mmm && canPeek(mmm) ) {
setDef(i,mmm.in(1));
return this;
}
@@ -115,18 +115,18 @@ public class BulkMemPhiNode extends PhiNode {
if( m instanceof BulkMemPhiNode bulk ) {
if( bulk._aliases.get(alias) )
return false;
- } else if( m instanceof MemMergeNode mmm &&
+ } else if( m instanceof MemJoinNode mmm &&
mmm.in(1) instanceof BulkMemPhiNode bulk &&
bulk._aliases.get(alias) &&
- mmm.explicitAlias(alias)==null )
+ !mmm.hasAlias(alias) )
return false;
return true;
}
- // True if the MemMerge has no precise slice still covered by this Phi.
- private boolean canPeek(MemMergeNode mmm) {
- return missingAlias(mmm)==0;
+ // True if the MemJoin has no precise slice still covered by this Phi.
+ private boolean canPeek(MemJoinNode mmm) {
+ return !mmm.isSlice() && missingAlias(mmm)==0;
}
// Return an alias required by an input but still covered by this Phi, or 0.
@@ -138,7 +138,7 @@ public class BulkMemPhiNode extends PhiNode {
assert !(con._con instanceof TypeMem tmem && tmem._alias != 1);
yield 0;
}
- case MemMergeNode mmm -> missingAlias(mmm);
+ case MemJoinNode mmm -> missingAlias(mmm);
case MemOpNode mem -> unsplit(mem._alias);
case BulkMemPhiNode bulk -> missingAlias(bulk);
default -> throw Utils.TODO("Should not reach here");
@@ -155,11 +155,10 @@ public class BulkMemPhiNode extends PhiNode {
return switch(use) {
case ScopeNode scope -> 0;
case ParmNode parm -> 0;
- case MemMergeNode mmm -> missingAlias(mmm);
+ case MemJoinNode mmm -> missingAlias(mmm);
case BulkMemPhiNode bulk -> missingAlias(bulk);
case MemOpNode mem -> unsplit(mem._alias);
case MemPhiNode phi -> unsplit(phi._alias);
- case EscapeNode esc -> esc.pub()==this ? unsplit(esc.fld()._alias) : 0;
default -> {
assert use instanceof ReturnNode || use instanceof CallNode || use instanceof CLInitNode
: "Unexpected bulk-memory user "+use.getClass().getSimpleName()+"#"+use._nid+": "+use;
@@ -184,17 +183,17 @@ public class BulkMemPhiNode extends PhiNode {
return 0;
}
- // First explicit MemMerge slice still covered by this Phi. A user's slice
+ // First explicit MemJoin slice still covered by this Phi. A user's slice
// may point to this Phi after a precise Phi folds; splitting is still valid.
- private int missingAlias( MemMergeNode mmm ) {
- for( int i=2; i<mmm.nIns(); i++ )
- if( mmm.in(i)!=null && mmm.in(i)!=mmm.in(1) && !_aliases.get(mmm.aliasAt(i)) )
+ private int missingAlias( MemJoinNode mmm ) {
+ for( int i=2; i<mmm.nIns(); i+=3 )
+ if( mmm.in(i)!=null && (mmm.fld((i-2)/3)!=null || mmm.in(i)!=mmm.in(1)) && !_aliases.get(mmm.aliasAt(i)) )
return mmm.aliasAt(i);
return 0;
}
// Slice out given alias
- private MemMergeNode slice( int alias ) {
+ private MemJoinNode slice( int alias ) {
assert !_aliases.get(alias);
// Inputs are the same; MemPhi will sharpen his own inputs. If a
// parallel precise Phi already exists, reuse it instead of building a
@@ -231,7 +230,7 @@ public class BulkMemPhiNode extends PhiNode {
private boolean readySlice(Node precise) {
TypeMem mem = (TypeMem)_type;
TypeMem part = (TypeMem)precise._type;
- if( !mem._escAs.contains(part._alias) || mem.meet(part).isa(mem) ) return true;
+ if( (!CodeGen.CODE.publicAlias(part._alias) && !mem._escAs.contains(part._alias)) || mem.meet(part).isa(mem) ) return true;
precise.setType(precise.compute());
if( mem.meet(precise._type).isa(mem) ) return true;
addDep(precise);
@@ -241,8 +240,8 @@ public class BulkMemPhiNode extends PhiNode {
// Build aggregate memory over a bulk Phi, preserving every precise slice
// which the bulk has already excluded. The named alias is newly supplied
// (or replaces its old slice).
- MemMergeNode aggregate(Node bulk, int alias, Node precise) {
- MemMergeNode mmm = new MemMergeNode(null,bulk);
+ MemJoinNode aggregate(Node bulk, int alias, Node precise) {
+ MemJoinNode mmm = new MemJoinNode(null,bulk);
for( int old = _aliases.nextSetBit(0); old >= 0; old = _aliases.nextSetBit(old+1) )
{ assert old != alias; mmm.alias(old,precisePhi(old));}
mmm.alias(alias,precise);
@@ -259,11 +258,11 @@ public class BulkMemPhiNode extends PhiNode {
mphi = new MemPhiNode(ScopeNode.memName(alias),alias);
mphi.addDef(region());
// Due to cycles, must set before calling peephole
- // An escaped slice must preserve the bulk Phi's established bound.
- // An unescaped slice was excluded from that summary: include the
+ // A public or reachable slice must preserve the bulk Phi's bound.
+ // A private unescaped slice was excluded from that summary: include the
// facts hidden in predecessor slices before wiring any cyclic Phis.
TypeMem old = (TypeMem)_type;
- if( !old._escAs.contains(alias) )
+ if( !CodeGen.CODE.publicAlias(alias) && !old._escAs.contains(alias) )
old = (TypeMem)old.meet(sliceBound(this,alias,new BitSet()));
mphi.setType(TypeMem.make(alias,old._t,old._one,old._clz,false,old._escFs,old._escAs));
for( int i=1; i<nIns(); i++ )
@@ -271,21 +270,25 @@ public class BulkMemPhiNode extends PhiNode {
return CodeGen.CODE.add(mphi);
}
- // A bulk summary ignores unescaped slots in MemMerge inputs. Follow the
+ // A bulk summary ignores private unescaped slots in MemJoin inputs. Follow the
// same slots that splitting will expose, including across loop backedges.
// A visited cycle contributes TOP; its incoming definitions supply the bound.
private static TypeMem sliceBound(Node mem, int alias, BitSet visit) {
if( visit.get(mem._nid) ) return TypeMem.TOP;
visit.set(mem._nid);
- if( mem instanceof MemMergeNode merge )
- return sliceBound(merge.alias(alias),alias,visit);
+ if( mem instanceof MemJoinNode merge && !merge.isSlice() ) {
+ if( merge.hasAlias(alias) ) return merge.sliceType(alias,merge);
+ return sliceBound(merge.pub(),alias,visit);
+ }
if( mem instanceof BulkMemPhiNode bulk ) {
TypeMem bound = TypeMem.TOP;
for( int i = 1; i < bulk.nIns(); i++ )
bound = (TypeMem)bound.meet(sliceBound(bulk.in(i),alias,visit));
return bound;
}
- return mem._type instanceof TypeMem bound ? bound : TypeMem.BOT;
+ // Synthetic Never exits supply TOP, which contributes no memory facts.
+ return mem._type instanceof TypeMem bound ? bound :
+ mem._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
}
MemPhiNode _findPhi(int alias) {
@@ -297,7 +300,7 @@ public class BulkMemPhiNode extends PhiNode {
// Select an alias already split out of a predecessor's bulk memory.
private Node preciseInput(Node mem, int alias) {
- if( mem instanceof MemMergeNode mmm )
+ if( mem instanceof MemJoinNode mmm )
return mmm.alias(alias);
if( mem instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) )
return bulk.precisePhi(alias);
@@ -305,10 +308,10 @@ public class BulkMemPhiNode extends PhiNode {
}
// Every alias excluded by a bulk default must be supplied explicitly.
- static boolean checkMerge(MemMergeNode mmm) {
+ static boolean checkMerge(MemJoinNode mmm) {
if( !(mmm.in(1) instanceof BulkMemPhiNode bulk) ) return true;
for( int alias = bulk._aliases.nextSetBit(0); alias >= 0; alias = bulk._aliases.nextSetBit(alias+1) )
- if( mmm.explicitAlias(alias)==null )
+ if( !mmm.hasAlias(alias) )
return false;
return true;
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java
index ba744dc3..c5d7130f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java
@@ -4,6 +4,7 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Ary;
+import com.seaofnodes.simple.util.WorkList;
import java.util.BitSet;
import java.util.IdentityHashMap;
@@ -16,7 +17,7 @@ import java.util.IdentityHashMap;
* idepth is computed lazily upon first request, and is valid even in the
* Parser, and is used by peepholes during parsing and afterward.
* <p>
- * loop_depth is computed after optimization as part of scheduling.
+ * loop_depth is computed before type checking and maintained through lowering.
*
* Start - Block head; has constants and trailing Funs
* Region - Block head; has Phis. Includes Fun and Parms.
@@ -225,6 +226,25 @@ public abstract class CFGNode extends Node {
post.clear();
}
+ // Inlining has settled. Reconstruct just this caller's nesting, retaining
+ // the outer tree and every other function's loop descriptors.
+ public void rebuildLoopTree(StopNode stop) {
+ assert this instanceof FunNode;
+ WorkList<CFGNode> work = new WorkList<>();
+ work.push(this);
+ CFGNode cfg;
+ while( (cfg=work.popOnce())!=null ) {
+ cfg._pre=0;
+ cfg._ltree=null;
+ if( cfg instanceof ReturnNode ) continue;
+ for( Node use : cfg._outputs )
+ if( use instanceof CFGNode next && !cfg.skip(next) ) work.push(next);
+ }
+ BitSet post=CodeGen.CODE.visit();
+ _bltWalk(2,(FunNode)this,stop,post,new Ary<>(FunNode.class));
+ post.clear();
+ }
+
int _bltWalk( int pre, FunNode fun, StopNode stop, BitSet post, Ary<FunNode> work ) {
// Pre-walked?
if( _pre!=0 ) return pre;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java
index 4a122090..9b8c979d 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CLInitNode.java
@@ -183,8 +183,8 @@ public class CLInitNode extends CFGNode implements MultiNode {
// The callee establishes its parent before setting its own flag.
IfNode iff = CodeGen.CODE.add(new IfNode(ctrl,ready()).init());
- Node done = CodeGen.CODE.add(new CProjNode(iff,0,"True").init());
- Node cold = CodeGen.CODE.add(new CProjNode(iff,1,"False").init());
+ CProjNode done = CodeGen.CODE.add(new CProjNode(iff,0,"True").init());
+ CProjNode cold = CodeGen.CODE.add(new CProjNode(iff,1,"False").init());
Node fptr = new FunPtrNode(target.sig(),CodeGen.CODE._start,target.ret()).peephole();
CallNode call = CodeGen.CODE.add(new CallNode(_loc,cold,memory,ptr(),arg,fptr).init());
@@ -198,9 +198,11 @@ public class CLInitNode extends CFGNode implements MultiNode {
// the precise initializer effects already analyzed above.
end.setType(end.compute());
unlink();
- Node called = CodeGen.CODE.add(new CProjNode(end,0,ScopeNode.CTRL).init());
+ CProjNode called = CodeGen.CODE.add(new CProjNode(end,0,ScopeNode.CTRL).init());
Node after = CodeGen.CODE.add(new ProjNode(end,1,ScopeNode.MEM0).init());
RegionNode region = CodeGen.CODE.add(new RegionNode(_loc,null,done,called).init());
+ // This diamond stays within the original operation's containing loop.
+ iff._ltree = done._ltree = cold._ltree = call._ltree = end._ltree = called._ltree = region._ltree = _ltree;
Node merged = CodeGen.CODE.add(new BulkMemPhiNode(ScopeNode.MEM0,region,memory,after).init());
// Replace the individual outputs; no tuple-pack node or second
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java
index 073e4658..e6fba30d 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CProjNode.java
@@ -58,8 +58,13 @@ public class CProjNode extends CFGNode implements Proj {
}
// Flip a negating if-test, to remove the not
- if( ctrl() instanceof IfNode iff && iff.pred() != null && addDep(iff.pred()) instanceof NotNode not )
- return new CProjNode(new IfNode(iff.ctrl(),not.in(1)).peephole(),1-_idx,_idx==0 ? "False" : "True");
+ if( ctrl() instanceof IfNode iff && iff.pred() != null && addDep(iff.pred()) instanceof NotNode not ) {
+ IfNode flipped = new IfNode(iff.ctrl(),not.in(1));
+ flipped._ltree = iff._ltree;
+ CProjNode proj = new CProjNode(flipped.peephole(),1-_idx,_idx==0 ? "False" : "True");
+ proj._ltree = _ltree;
+ return proj;
+ }
// Copy of some other input
return ((MultiNode)ctrl()).pcopy(_idx,this);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
index abe7953b..d48210a6 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java
@@ -114,8 +114,11 @@ public class CallEndNode extends CFGNode implements MultiNode {
// This also covers invalid calls (e.g. wrong arity), which never link.
// SCCP links valid finite targets as soon as they become known, before
// computing their CallEnd, so this check does not trigger during SCCP.
+ // Specializing an outside call can reveal finite targets before their
+ // Return edges are linked. Retain the memory bound already established
+ // for the broader target set; missing edges do not invalidate it.
if( nIns()-1 < tfp.nfcns() )
- return TypeTuple.make(Type.CONTROL,TypeMem.BOT,tfp.ret());
+ return TypeTuple.make(Type.CONTROL,_type instanceof TypeTuple old ? old.mem() : TypeMem.BOT,tfp.ret());
// Start at a high tuple (matching Returns' tuple)
TypeTuple state = TypeTuple.STATE.dual();
@@ -123,7 +126,7 @@ public class CallEndNode extends CFGNode implements MultiNode {
for( int i=1; i<nIns(); i++ )
state = (TypeTuple)state.meet(in(i)._type);
// Keep a live continuation even before any callee exit is reachable.
- // Otherwise a transient no-return result can tear down the caller
+ // Otherwise, a transient no-return result can tear down the caller
// and lose class-init dependencies before SCCP finds those exits.
if( state.ctl()==Type.XCONTROL )
return TypeTuple.make(Type.CONTROL,TypeMem.TOP,Type.TOP);
@@ -137,7 +140,7 @@ public class CallEndNode extends CFGNode implements MultiNode {
}
public byte maybeInline() {
- byte intrinsic=Intrinsic.tryInline(this);
+ byte intrinsic = Intrinsic.tryInline(this);
if( intrinsic>0 ) return intrinsic;
byte inline = inlineCandidate(false);
if( CodeGen.CODE._midAssert )
@@ -154,11 +157,13 @@ public class CallEndNode extends CFGNode implements MultiNode {
public boolean loadForInline() {
CodeGen code = CodeGen.CODE;
if( code._phase!=CodeGen.Phase.IterPostOpto || nIns()!=2 ||
- !(in(1) instanceof ReturnNode ret) || ret.fun().summary()==null ) return false;
+ !(in(1) instanceof ReturnNode ret) || ret.fun().summary()==null )
+ return false;
// Fetch bodies only for calls in functions compiled from source here.
// Calls inside imported functions become eligible when inlined into one.
if( !(in(0) instanceof CallNode call) || !call.fun().isFromSource() ||
- inlineCandidate(true)<=0 ) return false;
+ inlineCandidate(true)<=0 )
+ return false;
code.loadForInline(ret.fun()._compunit);
return true;
}
@@ -167,7 +172,7 @@ public class CallEndNode extends CFGNode implements MultiNode {
// policy, but can only estimate the size of a summarized body.
private byte inlineCandidate(boolean loading) {
if( _inline < -2 ) return -2; // Never
- if( _folding ) return -2; // No, and will collapse anyways
+ if( _folding ) return -2; // No, and will collapse anyway
if( !(in(0) instanceof CallNode call) ) return -2; // malformed because mid-death
if( nIns()!=2 ) return -1; // Not exactly 1 link, but can change
@@ -219,7 +224,7 @@ public class CallEndNode extends CFGNode implements MultiNode {
// Bounded, conservative recognition of straight-line initializer boilerplate.
// Walk uses from the entry and stop at Return, never following callers or
- // constant inputs. This also avoids scanning sparse MemMerge input arrays.
+ // constant inputs. This also avoids scanning all the memory inputs.
// Watch only this small prefix, including an unsupported node that may fold.
private static final Node[] TINYBODY = new Node[15]; // Tiny worklist
private boolean smallBody(FunNode fun) {
@@ -235,7 +240,7 @@ public class CallEndNode extends CFGNode implements MultiNode {
if( n==ret ) continue;
if( n instanceof ParmNode parm && parm.region()!=fun ) return false;
if( n!=fun && !(n instanceof ParmNode) &&
- !(n instanceof StoreNode) && !(n instanceof MemMergeNode) )
+ !(n instanceof StoreNode) && !(n instanceof MemJoinNode) )
return false; // Something unexpected
if( n.nOuts()>TINYBODY.length ) return false; // Too big
for( Node use : n._outputs ) {
@@ -257,6 +262,7 @@ public class CallEndNode extends CFGNode implements MultiNode {
FunNode fun = ret.fun();
CallNode call = call();
assert fun.sig().isa(call.fptr()._type);
+ CodeGen.CODE.invalidateLoopTree(call.fun());
// Clone first
if( _inline==2 ) {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java
index a48f9115..c91d9a16 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -161,9 +161,11 @@ public class CallNode extends CFGNode {
// Walk the bits and link
for( int fidx = fidxs.next(0); fidx > 0; fidx = fidxs.next(fidx) ) {
FunNode fun = CodeGen.CODE.link(fidx);
+ boolean restored = fun==null;
+ if( fun==null && !CodeGen.CODE._midAssert ) fun = CodeGen.CODE.restoreFunction(fidx);
if( fun==null ) addDepForwards(CodeGen.CODE._start);
if( fun!=null && !addDep(fun)._folding && !linked(fun) )
- progress = link(fun);
+ progress = link(fun,restored);
}
}
}
@@ -180,7 +182,8 @@ public class CallNode extends CFGNode {
}
// Link so this calls fun
- public Node link( FunNode fun ) {
+ public Node link( FunNode fun ) { return link(fun,false); }
+ private Node link( FunNode fun, boolean restored ) {
assert !linked(fun);
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
@@ -207,7 +210,7 @@ public class CallNode extends CFGNode {
CodeGen code = CodeGen.CODE;
if( code._phase.ordinal()>CodeGen.Phase.Opto.ordinal() &&
code._phase.ordinal()<CodeGen.Phase.Lower.ordinal() ) {
- boolean repair = !fun.compute().isa(fun._type) || !cend().compute().isa(cend()._type);
+ boolean repair = restored || !fun.compute().isa(fun._type) || !cend().compute().isa(cend()._type);
for( Node use : fun._outputs )
if( use instanceof ParmNode && !use.compute().isa(use._type) ) repair = true;
if( repair ) Iter.repair(code);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java
index 9e130bb4..befd9f4e 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java
@@ -76,7 +76,7 @@ public class ConFldOffNode extends ConstantNode {
@Override public boolean eq(Node n) {
ConFldOffNode off = (ConFldOffNode)n; // Invariant
- return _ts._name==off._ts._name && _fname.equals(off._fname) && super.eq(n);
+ return _ts._name==off._ts._name && _fname==off._fname && super.eq(n);
}
@Override int hash() { return super.hash() * _ts._name.hashCode() * _fname.hashCode(); }
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
index 0569f352..2bf2d62b 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ConstantNode.java
@@ -72,7 +72,11 @@ public class ConstantNode extends TypeNode {
}
@Override public String label() { return "Con"; }
- @Override public Node copy() { return raw(this); }
+ @Override public Node copy() {
+ // Inlining clones function-local constants (including Never's TOP)
+ // before bodyEdge installs their new inputs. Machine copies retain edges.
+ return CodeGen.CODE._phase.ordinal()<CodeGen.Phase.Select.ordinal() ? copyEmpty() : raw(this);
+ }
@Override
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java
deleted file mode 100644
index cc1b3b58..00000000
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java
+++ /dev/null
@@ -1,143 +0,0 @@
-package com.seaofnodes.simple.node;
-
-import com.seaofnodes.print.ExprPrinter;
-import com.seaofnodes.simple.codegen.CodeGen;
-
-import com.seaofnodes.simple.type.*;
-import com.seaofnodes.simple.util.*;
-import java.util.HashMap;
-import java.util.IdentityHashMap;
-
-/**
- * Merge public and private aliases. A borrow orders partial-reader calls
- * after constructor Stores without adding the private values to escape sets.
- * 0 - control
- * 1 - private pointer
- * 2 - private alias
- * 3 - public alias
- */
-public class EscapeNode extends TypeNode {
- public final boolean _borrow;
-
- public EscapeNode(Field fld, Node self, Node priv, Node pub ) {
- this(fld,self,priv,pub,false);
- }
- public EscapeNode(Field fld, Node self, Node priv, Node pub, boolean borrow ) {
- super(fld,null,self,priv,pub);
- _borrow = borrow;
- }
- public EscapeNode(EscapeNode esc ) {
- super(esc); // Copy constructor
- _borrow = esc._borrow;
- // Except we do not want/need self ptr past Opto.
- // *NOTE* the weird direct stomp; this is correct because this
- // constructor does NOT set the backedges, because it is used to
- // copy-construct an entire graph and ALL edges will get rewritten.
- _inputs.set(1,null);
- _con = esc._con;
- }
-
- // Pointer to some private (unescaped) memory from a NewNode
- public Node self() { return in(1); }
- public Node priv() { return in(2); }
- public Node pub () { return in(3); }
- public Field fld() { return (Field)_con; }
-
- @Override public Tag serialTag() { return Tag.Escape; }
- @Override public void packed( BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node, Integer> anodes ) {
- assert !_borrow; // Source ^ interfaces cannot yet be serialized.
- baos.packed2(types.get(_con));
- }
- static Node make( BAOS bais, Type[] types) {
- return new EscapeNode((Field)types[bais.packed2()], null,null,null);
- }
-
- @Override
- protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) {
- p.p("Esc#").p(fld()._alias).p(" {");
- if( self()==null ) p.p("---");
- else p.n(self()).p(",");
- p.n(priv()).p("}, ");
- p.n(pub ());
- return p;
- }
-
- @Override
- public Type compute() {
- // A static constant array has no private heap writes to publish.
- // This depends on its type, regardless of which node produced it.
- if( self()!=null && self()._type instanceof TypeMemPtr ptr &&
- ptr.isConstant() && ptr._obj.isConAry() ) return pub()._type;
- if( priv()._type.isHigh() ) return TypeMem.TOP;
- if( pub ()._type.isHigh() ) return TypeMem.TOP;
- TypeMem mpriv = (TypeMem)priv()._type;
- TypeMem mpub = (TypeMem)pub ()._type;
- // Private memory comes from an allocation or other non-aliased source.
- // Public memory comes from anywhere, might be bulk memory with a very weak mem type.
- Field fld = fld();
- assert mpriv._alias==1 || mpriv._alias==fld._alias;
- assert mpub ._alias==1 || mpub ._alias==fld._alias;
- Type tpriv = mpriv._t instanceof TypeStruct ts && ts.findAlias(fld._alias)!=-1
- ? ts.at(ts.findAlias(fld._alias))._t
- : mpriv._t;
- assert !(mpub._t instanceof TypeStruct); // Never expect this, but if it starts to happen, need to optimize
- Type tpub = mpub._t;
-
- // t is meet of pub & priv. Pub memory can be very weak (e.g. alias 1)
- // and we're no worse than the declared field type
- Type bound = fld._t;
- if( _borrow && bound instanceof TypeMemPtr ptr && TypeMemPtr.mayBePartial(tpriv) )
- bound = ptr.withPartial(true).partialBound();
- Type t = tpriv.meet(tpub).join(bound);
- // Lending memory to a local read-only partial argument is an ordering
- // edge, not publication to unknown callers. Keep the public escape sets.
- if( _borrow )
- return TypeMem.make(fld._alias,t,false,false,false,mpub._escFs,mpub._escAs);
- // Publish this field's value, bounded by its declaration. The private
- // aggregate's escapes include other fields, and selecting an alias
- // from it can expose a weaker scalar/escape bound. Neither changes
- // which values this field can hold. Opaque referents contribute the
- // identities already available in public memory.
- return TypeMem.make(fld._alias,t,false,false,fld._final,mpub._escFs,mpub._escAs)
- .escapesFrom(t,mpub);
- }
-
- @Override public Node idealize() {
- if( self()._type instanceof TypeMemPtr ptr && ptr.isConstant() && ptr._obj.isConAry() )
- return pub();
- // Sharpen private memory input
- if( priv() instanceof MemMergeNode mmm ) {
- setDef(2,mmm.alias(fld()._alias));
- return this;
- }
- // Sharpen public memory input
- if( pub() instanceof MemMergeNode mmm ) {
- setDef(3,mmm.alias(fld()._alias));
- return this;
- }
- // New allocation is dead
- if( self()._type.isHigh() )
- if( pub()._type.isa(_type) ) return pub();
- else addDep(pub());
- return null;
- }
-
-// Upgrade the internal type
-@Override boolean _upgradeType( HashMap<String,Type> TYPES) {
- Type t = _con.upgradeType(TYPES);
- if( t == _con ) return false;
- unlock(); // Unlock before changing _con
- _con = t;
- return true;
-}
-
- @Override public boolean eq(Node n) {
- if( _borrow!=((EscapeNode)n)._borrow ) return false;
- if( fld()._alias!=((EscapeNode)n).fld()._alias )
- return false;
- assert _con == ((EscapeNode)n)._con;
- return true;
- }
-
- @Override int hash() { return _con.hashCode() ^ (_borrow ? 1024 : 0); }
-}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java
index e49162f4..119e0300 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java
@@ -31,7 +31,7 @@ public class FldOffNode extends TypeNode {
}
@Override public Type compute() {
- return Type.BOTTOM;
+ return TypeInteger.BOT;
}
@Override public Node idealize() {
@@ -43,7 +43,7 @@ public class FldOffNode extends TypeNode {
@Override public boolean eq(Node n) {
FldOffNode off = (FldOffNode)n; // Invariant
- return _fname.equals(off._fname) && super.eq(n);
+ return _fname==off._fname && super.eq(n);
}
@Override int hash() { return super.hash() * _fname.hashCode(); }
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java
index d34b342d..558ad0f4 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java
@@ -18,7 +18,7 @@ public final class FormatNode extends Node {
if( t instanceof TypeInteger ) return 2;
if( t instanceof TypeFloat ) return 3;
if( t instanceof TypeMemPtr p && !p.nullable() && p._obj.isAry() &&
- p._obj._name.equals("[]u8") ) return 4;
+ p._obj._name=="[]u8" ) return 4;
return 0;
}
@Override public Type compute() {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java
index 896dff05..e91d760d 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java
@@ -21,6 +21,10 @@ public class FunNode extends RegionNode {
private TypeFunPtr _sig; // Initial signature
private ReturnNode _ret; // Return pointer
+ // Never adds structural exits, not executions that return. Preserve the
+ // checked return state for diagnostics and separately compiled summaries.
+ public TypeTuple _semanticReturn;
+ public TypeTuple returnState() { return _semanticReturn==null ? (TypeTuple)ret()._type : _semanticReturn; }
public String _name; // Debug name
@@ -42,6 +46,7 @@ public class FunNode extends RegionNode {
_name = fun._name;
_compunit = fun._compunit;
_extern = fun._extern;
+ _semanticReturn = fun._semanticReturn;
}
@Override public Tag serialTag() { return Tag.Fun; }
@Override public void packed(BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node,Integer> anodes ) {
@@ -86,6 +91,20 @@ public class FunNode extends RegionNode {
// An unloaded body's Summary is constructed before every other user.
public SummaryNode summary() { return nOuts()>0 && out(0) instanceof SummaryNode summary ? summary : null; }
+ // Different sharpened FunPtrs can denote this same FIDX. Inspect their
+ // graph uses, not pointer use counts, to find still-unmaterialized calls.
+ public boolean hasSummaryCallers() {
+ if( _ret==null ) return false;
+ for( Node use : _ret._outputs )
+ if( use instanceof FunPtrNode ptr ) {
+ addDep(ptr); // Removing a summary use can release the default.
+ for( Node user : ptr._outputs )
+ if( user instanceof SummaryNode summary && summary.references(ptr) &&
+ !addDep(summary.in(0))._type.isHigh() ) return true;
+ }
+ return false;
+ }
+
// This invocation compiles the defining CompUnit from source. Imported
// functions still belong to a CompUnit, but its _src is null.
public boolean isFromSource() { return _compunit!=null && _compunit._src!=null; }
@@ -197,18 +216,26 @@ public class FunNode extends RegionNode {
// - Must be past pessimistic Iter, which discovers and links calls
// through class-field loads and other initially imprecise values.
// - FIDX is not in the escape set
+ // - No live unloaded summary still holds a call dependency
// Concrete callers keep the body alive; FinalizeIR retains surviving
// functions for emission without giving them unknown callers.
- if( !isRoot() && in(1) instanceof StartCUNode start ) {
+ // After serialization this can be a native entry for saved callers.
+ if( !isRoot() && in(1) instanceof StartCUNode start &&
+ (CODE._phase==null || CODE._phase.ordinal()<CodeGen.Phase.Serialize.ordinal()) ) {
boolean preOpto = CodeGen.CODE._phase == null ||
CodeGen.CODE._phase.ordinal() < CodeGen.Phase.Opto.ordinal();
- if( !preOpto && !start.escapedFIDX(_sig.fidx()) && _ret!=null ) {
+ if( !preOpto && !start.escapedFIDX(_sig.fidx()) && !hasSummaryCallers() && _ret!=null ) {
// CLInit has a call edge but no Return edge. Keep a called
// body's Return rooted even after dropping unknown callers.
if( !isClz() || nIns()<=2 ) {
StopCUNode stop = _compunit._stop;
- CODE.add(stop).delDef(stop._inputs.find(ret()));
- CODE.addAll(stop._outputs); // The outer Stop can drop an empty unit.
+ // A replaced summary can outlive its Return while its
+ // outgoing callee references are being released.
+ int idx = stop._inputs.find(ret());
+ if( idx!=-1 ) {
+ CODE.add(stop).delDef(idx);
+ CODE.addAll(stop._outputs); // The outer Stop can drop an empty unit.
+ }
}
return removeDeadPath(1);
} else {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java
index 46988a99..b3581d0d 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java
@@ -4,8 +4,14 @@ import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.type.*;
-/** A program-point view of self. Memory proves which slots may be read;
- * their values still come from ordinary Loads. Erased after TypeCheck. */
+
+// A 'self' pointer, with a deep TypeStruct whose fields are `scalar` if NOT
+// initialized, and otherwise their current value. Used to make sure we do not
+// read uninitialized memory. Removed after TypeCheck, or if we can prove not
+// needed.
+
+/** A program-point view of self. Memory proves which slots may be read;
+ * their values still come from ordinary Loads. Erased after TypeCheck. */
public class InitViewNode extends TypeNode {
public InitViewNode(TypeMemPtr declared, Node self, Node mem) { super(declared,null,self,mem); }
@Override public String label() { return "InitView"; }
@@ -16,7 +22,7 @@ public class InitViewNode extends TypeNode {
if( !(ptr instanceof TypeMemPtr p) ) return ptr;
TypeStruct state = mem instanceof TypeMem m && m._one && m._t instanceof TypeStruct ts
? ts : p._obj.makeInit();
- // An earlier alias can have fewer initialized slots. The declaration
+ // An earlier alias can have fewer initialized slots. The declaration
// supplies field types; this program point's memory supplies the proof.
return p.makeFrom(((TypeMemPtr)_con)._obj).withPartial(true).initialized(state);
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java
index 14efa315..d024da67 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java
@@ -47,8 +47,8 @@ public class LoadNode extends MemOpNode {
if( use==null ) continue;
dep.addDepForwards(use);
if( use instanceof StoreNode || use instanceof PhiNode ||
- use instanceof MemMergeNode ||
- use instanceof NewNode || use instanceof EscapeNode || use instanceof CallNode ||
+ use instanceof MemJoinNode ||
+ use instanceof NewNode || use instanceof CallNode ||
use instanceof CLInitNode ) return true;
}
return false;
@@ -61,7 +61,7 @@ public class LoadNode extends MemOpNode {
@Override
public Type compute() {
- Type mem0 = mem()._type;
+ Type mem0 = _alias>1 && mem() instanceof MemJoinNode join ? join.sliceType(_alias,this) : mem()._type;
Type ptr0 = ptr()._type;
// Validate argument types
if( ptr0.isHigh() )
@@ -98,13 +98,13 @@ public class LoadNode extends MemOpNode {
t = mem._alias==_alias ? mem._t : actual==null ? TypeScalar.BOT : actual._t;
} else if( mem._alias==_alias )
t = t.join(mem._t);
- // A final method's identity comes from its declaration, not from an
- // unknown outside writer. It remains callable on a local object even
- // when that function has never escaped to outside code.
+ // Final function fields retain their declared targets, including a
+ // choice between several private functions. Outside memory cannot
+ // overwrite them or remove targets which have not escaped.
if( !mem._one ) {
Type declared = Parser.TYPES.get(tmp._obj._name);
Field field = declared instanceof TypeStruct obj ? obj.field(_name) : null;
- if( !(field != null && field._final && field._t instanceof TypeFunPtr fun && fun.isConstant()) )
+ if( !(field != null && field._final && field._t instanceof TypeFunPtr) )
t = mem.outside(t);
}
// Store forwarding is also a value fact during SCCP. Waiting for the
@@ -143,7 +143,7 @@ public class LoadNode extends MemOpNode {
// Null checks are handled by types. Array elements retain control for
// range checks, but reading an array's length has no index to check.
if( in(0)!=null && ptr._type instanceof TypeMemPtr tmp &&
- (!tmp._obj.isAry() || _name.equals("#")) ) {
+ (!tmp._obj.isAry() || _name=="#") ) {
setDef(0,null);
return this;
}
@@ -154,7 +154,8 @@ public class LoadNode extends MemOpNode {
(fld=tmp._obj.field(_name)) != null &&
_alias != fld._alias) {
assert _alias==1 || _alias == fld._alias;
- assert !tmp._obj._open && !tmp._obj._fref;
+ // Field aliases are fixed as declarations are discovered; the
+ // containing initializer can still be open at this point.
unlock(); // Alias participates in GVN semantics
_alias = fld._alias;
return this;
@@ -163,18 +164,30 @@ public class LoadNode extends MemOpNode {
if( _alias == 1 )
return null;
+ // Whole-memory parameters lose individual alias types. Recover the
+ // class flag from every caller without moving a load across a call.
+ // SCCP must have finished discovering callers before we remove it.
+ if( _name=="$init" && ptr._type instanceof TypeMemPtr clz &&
+ TypeStruct.startsClzPrefix(clz._obj._name) &&
+ CodeGen.CODE._phase.ordinal()>=CodeGen.Phase.IterPostOpto.ordinal() &&
+ classInitialized(mem,new BitSet()) )
+ return CodeGen.CODE.con(TypeInteger.TRUE);
+
Node slice = CLInitNode.slice(mem,_alias,this);
if( slice!=mem ) { setDef(1,slice); return this; }
- if( mem instanceof MemMergeNode merge ) {
- setDef(1,merge.alias(_alias));
- // In support of uplifting control to a prior dominating load, if
- // we move our memory, recheck other loads to see if they can hoist.
- for( Node use : in(1).outs() )
- if( use instanceof LoadNode ld && use != this && ptr == ld.ptr() )
- CodeGen.CODE.add(ld);
-
- return this;
+ if( mem instanceof MemJoinNode merge ) {
+ Node sliceMem=merge.alias(_alias);
+ if( sliceMem!=mem ) {
+ setDef(1,sliceMem);
+ // In support of uplifting control to a prior dominating load, if
+ // we move our memory, recheck other loads to see if they can hoist.
+ for( Node use : in(1).outs() )
+ if( use instanceof LoadNode ld && use != this && ptr == ld.ptr() )
+ CodeGen.CODE.add(ld);
+
+ return this;
+ }
}
// Uplift control to a prior dominating load.
@@ -198,7 +211,7 @@ public class LoadNode extends MemOpNode {
// val = ptr.x; ptr.x = val;
if( mem() instanceof PhiNode memphi && !(memphi instanceof ParmNode) &&
(memphi instanceof MemPhiNode || (memphi._type instanceof TypeMem tm && tm._one)) &&
- memphi.region()._type == Type.CONTROL && memphi.nIns()== 3 &&
+ memphi.region()._type == Type.CONTROL && memphi.nIns()>2 &&
// Retain control on both copies only if it dominates both paths.
// The Region itself, or a later range check, cannot move to its inputs.
(in(0)==null || cfg0().domLCA(memphi.region().idom(this),this)==cfg0()) &&
@@ -211,8 +224,10 @@ public class LoadNode extends MemOpNode {
// is also loop invariant. A pointer Phi may select another object.
Node stop = memphi.region() instanceof LoopNode &&
!(ptr instanceof PhiNode p && p.region()==memphi.region()) ? memphi : null;
- if( find(memphi.in(2),ptr,stop,new BitSet())!=null ||
- (!(memphi.region() instanceof LoopNode) && find(memphi.in(1),ptr,null,new BitSet())!=null) ) {
+ boolean folds = false;
+ for( int i=memphi.region() instanceof LoopNode ? 2 : 1; i<memphi.nIns(); i++ )
+ folds |= find(memphi.in(i),ptr,stop,new BitSet())!=null;
+ if( folds ) {
// Integer loop Phis widen to i64. Keep the load's declared
// width at the result, as for ordinary typed loop variables.
if( _type instanceof TypeInteger && !declaredType().isa(_type) ) return null;
@@ -223,13 +238,46 @@ public class LoadNode extends MemOpNode {
phi.addDef(load(memphi.in(i),p,stop,phi));
}
CodeGen.CODE.add(phi.unkeep());
- return _type instanceof TypeInteger ? new ConvertNode(declaredType(),phi) : phi;
+ Node value = phi.peephole();
+ return _type instanceof TypeInteger ? new ConvertNode(declaredType(),value) : value;
}
}
return null;
}
+ // A class flag has one global slot per alias. Unknown memory and cycles
+ // fail the proof; a cycle must not establish its own initialization.
+ private boolean classInitialized(Node mem, BitSet active) {
+ addDep(mem);
+ if( mem._type.isHigh() ) return true;
+ if( mem._type instanceof TypeMem tm && tm._alias==_alias && tm._t==TypeInteger.TRUE ) return true;
+ if( active.get(mem._nid) ) return false;
+ active.set(mem._nid);
+ boolean ready=false;
+ if( mem instanceof MemJoinNode merge && !merge.isSlice() )
+ ready=classInitialized(merge.alias(_alias),active);
+ else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CLInitNode init ) {
+ addDep(init.ptr());
+ Field flag=init.flag();
+ ready=flag!=null && flag._alias==_alias;
+ }
+ else if( mem instanceof StoreNode st ) {
+ if( st._alias==_alias ) ready=addDep(st.val())._type==TypeInteger.TRUE;
+ else if( st._alias>1 ) ready=classInitialized(st.mem(),active);
+ } else if( mem instanceof PhiNode phi ) {
+ addDep(phi.region());
+ if( !phi.inProgress() ) {
+ ready=true;
+ for( int i=1; i<phi.nIns(); i++ )
+ if( !addDep(phi.region().in(i))._type.isHigh() &&
+ !classInitialized(phi.in(i),active) ) { ready=false; break; }
+ }
+ }
+ active.clear(mem._nid);
+ return ready;
+ }
+
// Load a flavored zero from a New
private Node zero(NewNode nnn) {
// Object fields acquire values from their initializer's Stores.
@@ -256,13 +304,17 @@ public class LoadNode extends MemOpNode {
addDep(mem);
if( mem==stop ) return mem;
switch( mem ) {
- case MemMergeNode merge: mem=merge.alias(alias); break;
+ case MemJoinNode merge:
+ Node next=merge.memory(alias,ptr,this);
+ if( next==mem ) return null;
+ mem=next;
+ break;
case StoreNode st:
// Alias 1 is still unresolved, not a proven different field.
if( st._alias==1 ) return null;
addDep(st.ptr());
- if( alias==st._alias && (ptr==address(st.ptr()) || ptr==address(st.nnptr())) &&
- (!_name.equals("[]") && _name.equals(st._name) || off()==st.off() ||
+ if( alias==st._alias && (sameAddress(ptr,address(st.ptr())) || sameAddress(ptr,address(st.nnptr()))) &&
+ (_name!="[]" && _name==st._name || off()==st.off() ||
addDep(off())._type.isConstant() && off()._type==addDep(st.off())._type) ) {
// Forwarding must preserve the pointer type already seen
// by users: completion, read-only view, and recursive shape.
@@ -275,6 +327,7 @@ public class LoadNode extends MemOpNode {
// A full-width load cannot narrow the forwarded value.
if( declaredType() instanceof TypeInteger ti && ti.log_size()==3 &&
!addDep(st.val())._type.isa(expected) ) return null;
+ if( expected instanceof TypeFloat && !addDep(st.val())._type.isa(expected) ) return null;
return st;
}
if( (external || alias==st._alias) && (external || !neverAlias(ptr,address(st.ptr()))) &&
@@ -292,12 +345,6 @@ public class LoadNode extends MemOpNode {
if( external || !(proj.in(0) instanceof NewNode nnn) ) return null;
if( declaredType()==Type.BOTTOM ) return null;
return nnn;
- case EscapeNode esc:
- if( external ) return null;
- addDep(esc.self());
- if( address(esc.self())==ptr ) { mem=esc.priv(); break; }
- if( neverAlias(ptr,address(esc.self())) ) { mem=esc.pub(); break; }
- return null;
case PhiNode phi:
if( phi instanceof ParmNode || (!(phi instanceof MemPhiNode) && !(phi._type instanceof TypeMem tm && tm._one)) ) return null;
addDep(phi.region());
@@ -332,10 +379,10 @@ public class LoadNode extends MemOpNode {
return CodeGen.CODE.add(phi.unkeep().peephole());
}
Node fold=folded(win);
- if( fold!=null ) return fold.peephole();
+ if( fold!=null ) return fold._type==null ? fold.peephole() : fold;
}
LoadNode ld=new LoadNode(_loc,_name,_alias,in(0),mem,ptr,off());
- return ld.peephole();
+ return ld.init();
}
// Type views preserve the address. Keep the actual Load pointer qualified
@@ -357,6 +404,14 @@ public class LoadNode extends MemOpNode {
return ptr;
}
+ // A class has one address even while parsing extends its declared shape.
+ // Constants for successive shapes need not yet have the same GVN node.
+ private static boolean sameAddress(Node a, Node b) {
+ return a==b || a._type instanceof TypeMemPtr x && b._type instanceof TypeMemPtr y &&
+ x._one && y._one && x.notNull() && y.notNull() &&
+ TypeStruct.startsClzPrefix(x._obj._name) && x._obj._name==y._obj._name;
+ }
+
private static boolean neverAlias( Node ptr1, Node ptr2 ) {
return ptr1.in(0) != ptr2.in(0) &&
// Unrelated allocations
@@ -365,6 +420,9 @@ public class LoadNode extends MemOpNode {
}
private static boolean hoistPtr(Node ptr, PhiNode memphi ) {
+ // Constants are available in every function; their Start input is a
+ // graph-walking edge, not a control dependence.
+ if( ptr.isConst() ) return true;
// Can I hoist ptr above the Region?
if( !(memphi.region() instanceof RegionNode r) )
return false; // Dead or dying Region/Phi
@@ -404,6 +462,7 @@ public class LoadNode extends MemOpNode {
// A typed load can already know its width while the stored value is
// still unresolved. Do not replace it with an untyped shift/and chain.
if( !(val._type instanceof TypeInteger) ) { addDep(val); return null; }
+ if( addDep(val)._type.isa(ti) ) return val;
if( ti._min==0 ) // Unsigned
return new AndNode(null,val,con(ti._max));
// Signed extension
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java
index 2ab76429..be39142e 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java
@@ -49,8 +49,9 @@ public class LoopNode extends RegionNode {
NeverNode iff = new NeverNode(1.2f,back()).init(); // Ideal never-branch
CProjNode t = new CProjNode(iff,0,"True" ).init();
CProjNode f = new CProjNode(iff,1,"False").init();
- setDef(2,t); // True continues loop, False (never) exits loop
+ CodeGen.CODE.add(this).setDef(2,t); // True continues loop, False (never) exits loop
ReturnNode ret = fun.ret();
+ if( fun._semanticReturn==null ) fun._semanticReturn=fun.returnState();
iff._ltree = t._ltree = _ltree;
ret._ltree = f._ltree = fun._ltree;
@@ -60,7 +61,8 @@ public class LoopNode extends RegionNode {
// executing. Keep synthetic nodes local; do not GVN into that graph.
Node top = ConstantNode.raw(Type.TOP);
top.setDef(0,fun);
- MemMergeNode memout = new MemMergeNode();
+ top.init();
+ MemJoinNode memout = new MemJoinNode();
memout.addDef(f); // placeholder for control
memout.addDef(top);
for( Node u : _outputs )
@@ -84,6 +86,9 @@ public class LoopNode extends RegionNode {
ctrl.keep().addDef(f );
mem .keep().addDef(memout);
expr.keep().addDef(top);
+ CodeGen.CODE.add(ctrl);
+ CodeGen.CODE.add(mem);
+ CodeGen.CODE.add(expr);
} else {
ctrl = f .keep();
mem = memout.keep();
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/MemJoinNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/MemJoinNode.java
new file mode 100644
index 00000000..f2255b05
--- /dev/null
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/MemJoinNode.java
@@ -0,0 +1,368 @@
+package com.seaofnodes.simple.node;
+
+import com.seaofnodes.print.ExprPrinter;
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.codegen.GlobalBits;
+import com.seaofnodes.simple.parser.Var;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.util.*;
+import java.util.*;
+
+/**
+ * Join ordinary aliases, completed private allocations, and partial
+ * allocations (as read-only loans). Input 0 is control, input 1 the bulk
+ * default. Each dense alias entry after that holds a {public memory, private
+ * memory, owner pointer} triple, and a Field. Ordinary entries have null
+ * private and owner inputs. Fields name publication/loan entries; a borrow
+ * bit distinguishes MID-construction loans from POST-construction publication.
+ *
+ * Several fields can share one private aggregate and owner. Nested allocations
+ * of the same class nest joins: one alias entry names one private owner. This
+ * can only happen if we have nested constructors fir the same class, e.g.
+ * allocate another Link insight of allocating a Link.
+ *
+ * MID-construction inputs are used to order private memory updates vs calls
+ * taking partial objects.
+ *
+ * Bulk types summarize externally reachable contents. A precise slice view
+ * uses the same node, with _slice set, to retain a field's value and escape
+ * bounds through memory Phis and calls. Such views are made only on demand.
+ */
+public class MemJoinNode extends Node {
+ // Dense input to alias map
+ private AryInt _aliases;
+ // Alias to input map
+ private IntHashMap _aliasToInput;
+ // Field by input
+ private Ary<Field> _fields;
+ // Borrow bit by input
+ private BitSet _borrows;
+
+ private int _slice; // Zero for bulk, alias for a precise view.
+ private int _aliasLimit=2; // Preserve ordinary aggregate fold eligibility.
+
+ public MemJoinNode(Node... nodes) { super(nodes); _type=TypeMem.BOT; }
+ public MemJoinNode(MemJoinNode mem) {
+ super(mem);
+ copyAliases(mem);
+ // Ownership is a typing/alias proof, not a runtime machine operand.
+ for( int i=0; i<size(); i++ ) _inputs.set(4+3*i,null);
+ }
+ private void copyAliases(MemJoinNode mem) {
+ _slice=mem._slice;
+ _aliasLimit=mem._aliasLimit;
+ if( mem._aliases==null ) return;
+ _aliases=new AryInt().addAll(mem._aliases);
+ _fields=new Ary<>(mem._fields.asAry());
+ _borrows=(BitSet)mem._borrows.clone();
+ _aliasToInput=new IntHashMap(0);
+ reindex();
+ }
+ @Override protected Object clone() throws CloneNotSupportedException {
+ MemJoinNode copy=(MemJoinNode)super.clone();
+ copy.copyAliases(this);
+ return copy;
+ }
+
+ public Node pub () { return in(1); }
+ public Node pub (int i) { return in(2+3*i); }
+ public Node priv(int i) { return in(3+3*i); }
+ public Node self(int i) { return in(4+3*i); }
+ public Field fld(int i) { return _fields.at(i); }
+ public boolean borrow(int i) { return _borrows.get(i); }
+ public int size() { return _aliases==null ? 0 : _aliases.len(); }
+ public boolean isSlice() { return _slice!=0; }
+ public int sliceAlias() { return _slice; }
+ public int aliasAt(int input) { assert (input-2)%3==0; return _aliases.at((input-2)/3); }
+ public Node in(Var v) { return in(v._idx); }
+
+ private int findAlias(int alias) { return _aliasToInput==null ? 0 : _aliasToInput.get(alias); }
+ public boolean hasAlias(int alias) { return findAlias(alias)!=0; }
+ private void reindex() {
+ _aliasToInput.clear();
+ for( int i=0; i<size(); i++ ) _aliasToInput.put(_aliases.at(i),2+3*i);
+ }
+ private void removeAlias(int idx) {
+ int input=2+3*idx;
+ for( int j=0; j<3; j++ ) { setDef(input,null); _inputs.remove(input); }
+ _aliases.remove(idx);
+ _fields.remove(idx);
+ for( int i=idx; i<size(); i++ ) _borrows.set(i,_borrows.get(i+1));
+ _borrows.clear(size());
+ reindex();
+ }
+
+ // Explicit ordinary slice, a precise join view, or null if defaulted.
+ public Node explicitAlias(int alias) {
+ int input = findAlias(alias);
+ if( input==0 ) return null;
+ int idx=(input-2)/3;
+ if( fld(idx)==null ) return pub(idx);
+ if( _slice==alias ) return this;
+ MemJoinNode slice = new MemJoinNode(null,pub(idx));
+ slice.join(fld(idx),pub(idx),priv(idx),self(idx),borrow(idx));
+ slice._slice=alias;
+ return slice.peephole();
+ }
+
+ // The precise alias slice
+ public Node alias(int alias) {
+ Node precise = explicitAlias(alias);
+ assert !(pub() instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) && precise==null);
+ return precise==null ? pub() : precise;
+ }
+
+ // Set precise alias slice
+ public Node alias(int alias, Node value) {
+ if( alias==1 ) return setDef(1,value);
+ if( value==null ) {
+ int input=findAlias(alias);
+ if( input!=0 ) removeAlias((input-2)/3);
+ } else entry(alias,null,value,null,null,false);
+ return value;
+ }
+ public MemJoinNode join(Field fld, Node pub, Node priv, Node self, boolean borrow) {
+ entry(fld._alias,fld,pub,priv,self,borrow);
+ return this;
+ }
+ private void entry(int alias, Field fld, Node pub, Node priv, Node self, boolean borrow) {
+ assert alias>1;
+ _aliasLimit=Math.max(_aliasLimit,alias+1);
+ if( _aliases==null ) {
+ _aliases=new AryInt(); _fields=new Ary<>(Field.class);
+ _borrows=new BitSet(); _aliasToInput=new IntHashMap(0);
+ }
+ int input=findAlias(alias), idx;
+ if( input==0 ) {
+ idx=0;
+ while( idx<size() && _aliases.at(idx)<alias ) idx++;
+ for( int i=size(); i>idx; i-- ) _borrows.set(i,_borrows.get(i-1));
+ _aliases.insert(idx,alias);
+ _fields.insert(fld,idx);
+ input=2+3*idx;
+ insertDef(input ,pub );
+ insertDef(input+1,priv);
+ insertDef(input+2,self);
+ reindex();
+ } else {
+ idx=(input-2)/3;
+ // Retain new inputs before replacing an old input's last use.
+ if( pub !=null ) pub .keep();
+ if( priv!=null ) priv.keep();
+ if( self!=null ) self.keep();
+ setDef(input ,pub );
+ setDef(input+1,priv);
+ setDef(input+2,self);
+ if( pub !=null ) pub .unkeep();
+ if( priv!=null ) priv.unkeep();
+ if( self!=null ) self.unkeep();
+ _fields.set(idx,fld);
+ }
+ _borrows.set(idx,borrow);
+ }
+
+ @Override public String label() { return _slice==0 ? "MEMJOIN" : "Join#"+_slice; }
+ @Override public boolean isMem() { return true; }
+ @Override protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) {
+ p.p(label()).p("[ ");
+ for( int i=0; i<size(); i++ ) {
+ p.p(_aliases.at(i)).p(":").n(pub(i));
+ if( fld(i)!=null ) p.p(borrow(i) ? " borrow{" : " publish{").n(priv(i)).p(",").n(self(i)).p("}");
+ p.p(" ");
+ }
+ return p.p("]");
+ }
+
+ @Override public Type compute() {
+ if( _slice!=0 ) return joined(0,this);
+ Type tmem=pub()._type;
+ if( !(tmem instanceof TypeMem defmem) ) return tmem.isHigh() ? TypeMem.TOP : TypeMem.BOT;
+ if( defmem._one ) {
+ if( !(defmem._t instanceof TypeStruct ts) ) return defmem.escapes(defmem._t);
+ for( int i=0; i<size(); i++ ) {
+ Node in=pub(i);
+ if( in!=null && in._type.isHigh() ) return TypeMem.TOP;
+ if( in instanceof StoreNode st ) {
+ Type val=((TypeMem)st._type)._t;
+ Field old=ts.field(st._name);
+ if( old==null ) {
+ assert ts._open;
+ old=Field.make(st._name,Type.BOTTOM,st._alias,st._init);
+ ts=ts.add(old);
+ }
+ ts=ts.replace(old.makeFrom(val));
+ }
+ }
+ return TypeMem.makePrivate(ts);
+ }
+ TypeMem mem=defmem;
+ for( int i=0; i<size(); i++ ) {
+ int alias=_aliases.at(i);
+ if( (CodeGen.CODE.publicAlias(alias) || mem._escAs.contains(alias)) && pub(i)!=null ) {
+ Type part=fld(i)==null ? pub(i)._type : joined(i,this);
+ if( !part.isHigh() ) mem=(TypeMem)mem.meet(part);
+ }
+ }
+ return mem;
+ }
+
+ public TypeMem sliceType(int alias, Node dep) {
+ dep.addDepForwards(this);
+ int input=findAlias(alias);
+ if( input!=0 ) return joined((input-2)/3,dep);
+ return memoryType(pub(),alias,dep);
+ }
+ private static TypeMem memoryType(Node n, int alias, Node dep) {
+ dep.addDepForwards(n);
+ if( n instanceof MemJoinNode join && !join.isSlice() ) return join.sliceType(alias,dep);
+ return n._type instanceof TypeMem mem ? mem : n._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
+ }
+ private TypeMem joined(int idx, Node dep) {
+ int alias=_aliases.at(idx);
+ TypeMem mpub=memoryType(pub(idx),alias,dep);
+ Field fld=fld(idx);
+ if( fld==null ) return mpub;
+ Node owner=self(idx);
+ if( owner!=null && dep.addDepForwards(owner)._type instanceof TypeMemPtr ptr && ptr.isConstant() && ptr._obj.isConAry() ) return mpub;
+ TypeMem mpriv=memoryType(priv(idx),alias,dep);
+ if( mpriv.isHigh() || mpub.isHigh() ) return TypeMem.TOP;
+ assert mpriv._alias==1 || mpriv._alias==alias;
+ assert mpub ._alias==1 || mpub ._alias==alias;
+ Type value=mpriv._t;
+ if( value instanceof TypeStruct ts ) {
+ int fldx=ts.findAlias(alias);
+ value=fldx<0 ? TypeScalar.BOT : ts.at(fldx)._t;
+ }
+ Type bound=fld._t;
+ if( borrow(idx) && bound instanceof TypeMemPtr ptr && TypeMemPtr.mayBePartial(value) ) bound=ptr.withPartial(true).partialBound();
+ Type t=value.meet(mpub._t).join(bound);
+ TypeMem result=TypeMem.make(alias,t,false,false,!borrow(idx) && fld._final,mpub._escFs,mpub._escAs);
+ return borrow(idx) ? result : result.escapesFrom(t,mpub);
+ }
+
+ // Unknown aliasing keeps the join, never discards a memory side.
+ public Node memory(int alias, Node ptr, Node dep) {
+ dep.addDep(this);
+ int input=findAlias(alias);
+ if( input==0 ) return pub();
+ int idx=(input-2)/3;
+ if( fld(idx)==null ) return pub(idx);
+ if( !fld(idx)._extern ) {
+ Node owner=address(self(idx),dep);
+ ptr=address(ptr,dep);
+ if( ptr==owner ) return priv(idx);
+ if( ptr instanceof ProjNode a && a.in(0) instanceof NewNode &&
+ owner instanceof ProjNode b && b.in(0) instanceof NewNode && a.in(0)!=b.in(0) )
+ return pub(idx);
+ }
+ return this;
+ }
+ private static Node address(Node ptr, Node dep) {
+ dep.addDep(ptr);
+ while( ptr instanceof InitViewNode || ptr instanceof ReadOnlyNode ||
+ (ptr instanceof ConstructNode con && con._partial) ) {
+ ptr=ptr.in(1);
+ dep.addDep(ptr);
+ }
+ return ptr;
+ }
+
+ @Override public Node idealize() {
+ boolean progress=false, allDefault=size()==_aliasLimit-2;
+ for( int i=0; i<size(); i++ ) {
+ if( fld(i)!=null ) {
+ Node owner=self(i);
+ if( owner!=null && owner._type instanceof TypeMemPtr ptr && ptr.isConstant() && ptr._obj.isConAry() ) {
+ if( isSlice() ) return pub(i);
+ alias(_aliases.at(i),pub(i));
+ return this;
+ }
+ for( int j=0; j<2; j++ ) {
+ int input=2+3*i+j;
+ if( in(input) instanceof MemJoinNode join && !join.isSlice() ) {
+ Node n=join.alias(_aliases.at(i));
+ if( n!=in(input) ) { setDef(input,n); return this; }
+ }
+ }
+ if( isSlice() && owner!=null && owner._type.isHigh() ) {
+ if( pub(i)._type.isa(_type) ) return pub(i);
+ addDep(pub(i));
+ }
+ allDefault=false;
+ } else if( pub(i)==pub() ) { removeAlias(i--); progress=true; }
+ else allDefault=false;
+ }
+ if( allDefault && !isSlice() ) return pub();
+ // Preserve triples while flattening; an ordinary override replaces
+ // the entire entry. A precise view cannot supply the bulk remainder.
+ if( !isSlice() && pub() instanceof MemJoinNode mem && !mem.isSlice() ) {
+ keep();
+ for( int i=0; i<mem.size(); i++ ) {
+ int alias=mem._aliases.at(i);
+ if( findAlias(alias)==0 ) entry(alias,mem.fld(i),mem.pub(i),mem.priv(i),mem.self(i),mem.borrow(i));
+ }
+ CodeGen.CODE.add(mem.pub());
+ setDef(1,mem.pub());
+ return unkeep();
+ }
+ return progress ? this : null;
+ }
+
+ void _useless() {
+ for( int i=1; i<nIns(); i++ )
+ if( in(i) instanceof PhiNode phi ) {
+ Node in=phi.peephole();
+ CodeGen.CODE.addAll(phi._outputs);
+ phi.moveDepsToWorklist();
+ if( in!=phi ) { if( !phi.iskeep() ) phi.subsume(in); setDef(i,in); }
+ }
+ }
+ @Override boolean _upgradeType(HashMap<String,Type> types) {
+ boolean progress=false;
+ for( int i=0; i<size(); i++ ) {
+ Field fld=fld(i);
+ if( fld==null ) continue;
+ Field next=(Field)fld.upgradeType(types);
+ if( next!=fld ) { unlock(); _fields.set(i,next); progress=true; }
+ }
+ return progress;
+ }
+ @Override public boolean eq(Node n) {
+ MemJoinNode join=(MemJoinNode)n;
+ return this==n || (isSlice() && _slice==join._slice && fld(0)==join.fld(0) && borrow(0)==join.borrow(0));
+ }
+ @Override int hash() { return _slice==0 ? 0 : _slice ^ fld(0).hashCode() ^ (borrow(0) ? 1024 : 0); }
+
+ @Override public Tag serialTag() { return Tag.MemJoin; }
+ @Override public void packed(BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node,Integer> nodes) {
+ baos.packed4(_slice);
+ baos.packed4(_aliasLimit);
+ baos.packed2(size());
+ for( int i=0; i<size(); i++ ) {
+ assert !borrow(i); // Source ^ interfaces are not separately compiled.
+ baos.packed2(_aliases.at(i));
+ baos.packed2(fld(i)==null ? 0 : types.get(fld(i))+1);
+ }
+ }
+ static MemJoinNode make(BAOS bais, Type[] types, GlobalBits fileAliases, GlobalBits aliases) {
+ MemJoinNode mem=new MemJoinNode(null,null);
+ int slice=bais.packed4();
+ mem._slice=slice==0 ? 0 : aliases.map(fileAliases,slice);
+ int limit=bais.packed4(), size=bais.packed2();
+ for( int i=0; i<size; i++ ) {
+ int alias=aliases.map(fileAliases,bais.packed2()), type=bais.packed2();
+ // Retain edge order even when alias renaming reorders IDs.
+ if( mem._aliases==null ) {
+ mem._aliases=new AryInt(); mem._fields=new Ary<>(Field.class);
+ mem._borrows=new BitSet(); mem._aliasToInput=new IntHashMap(0);
+ }
+ mem._aliases.push(alias);
+ mem._fields.add(type==0 ? null : (Field)types[type-1]);
+ mem.addDef(null); mem.addDef(null); mem.addDef(null);
+ mem._aliasLimit=Math.max(mem._aliasLimit,alias+1);
+ }
+ mem._aliasLimit=Math.max(mem._aliasLimit,limit);
+ if( size!=0 ) mem.reindex();
+ return mem;
+ }
+}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
deleted file mode 100644
index 03cf4d36..00000000
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
+++ /dev/null
@@ -1,239 +0,0 @@
-package com.seaofnodes.simple.node;
-
-import com.seaofnodes.simple.parser.Var;
-import com.seaofnodes.print.ExprPrinter;
-
-import com.seaofnodes.simple.*;
-import com.seaofnodes.simple.codegen.CodeGen;
-import com.seaofnodes.simple.util.BAOS;
-import com.seaofnodes.simple.type.*;
-import com.seaofnodes.simple.util.Utils;
-import com.seaofnodes.simple.util.AryInt;
-import com.seaofnodes.simple.util.IntHashMap;
-
-import java.util.*;
-
-/**
- * Memory merge: default bulk memory plus dense inputs for explicit alias slices.
- */
-public class MemMergeNode extends Node {
-
- public MemMergeNode( Node ...nodes) { super(nodes); _type = TypeMem.BOT; }
- // Inputs 0/1 are control/default; the remaining inputs are dense precise slices.
- // Keep alias order so graph walks retain the old sparse representation's order.
- private AryInt _aliases;
- private IntHashMap _aliasToInput;
- private int _readSize;
- // 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; }
-
- private void copyAliases(MemMergeNode mem) {
- if( mem._aliases==null ) return;
- _aliases = new AryInt().addAll(mem._aliases);
- _aliasToInput = new IntHashMap(0);
- reindex();
- }
-
- @Override protected Object clone() throws CloneNotSupportedException {
- MemMergeNode copy = (MemMergeNode)super.clone();
- copy.copyAliases(this);
- return copy;
- }
-
- public int aliasAt(int input) { return _aliases.at(input-2); }
-
- // Explicit input, or null when the default supplies this alias.
- public Node explicitAlias(int alias) {
- int input = _aliasToInput==null ? 0 : _aliasToInput.get(alias);
- return input==0 ? null : in(input);
- }
-
- // The reader has not wired the dense inputs yet.
- public int readSize() { return _readSize; }
-
- private void reindex() {
- _aliasToInput.clear();
- for( int i=0; i<_aliases.len(); i++ ) _aliasToInput.put(_aliases.at(i),i+2);
- }
-
- private void removeAlias(int input) {
- setDef(input,null);
- _inputs.remove(input);
- _aliases.remove(input-2);
- reindex();
- }
- @Override public Tag serialTag() { return Tag.MemMerge; }
- public void packed( BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node, Integer> anodes ) {
- // 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 limit=bais.packed4(), count=bais.packed2();
- assert 2<=count && count<=limit;
- MemMergeNode mem=new MemMergeNode(null,null);
- mem._readSize=count;
- mem._aliasLimit=limit;
- return mem;
- }
-
- @Override public String label() { return "ALLMEM"; }
- @Override public boolean isMem() { return true; }
-
- @Override
- protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) {
- p.p("MEM[ ");
- for( int j=2; j<nIns(); j++ ) {
- p.p(aliasAt(j));
- p.p(":");
- Node n = in(j);
- while( n instanceof ScopeNode loop ) {
- p.p("Lazy_");
- n = loop.mem();
- }
- if( n==null ) p.p("___ ");
- else p.n(n).p(" ");
- }
- return p.unchar(' ').p("]");
- }
-
-
- @Override public Type compute() {
- Type tmem = in(1)._type;
- if( !(tmem instanceof TypeMem defmem) )
- // A MemMerge is structurally memory even while its default input
- // is a weak, not-yet-specialized Phi.
- return tmem.isHigh() ? TypeMem.TOP : TypeMem.BOT;
- // Is this a single private instance memory?
- if( defmem._one ) {
- if( !(defmem._t instanceof TypeStruct ts) )
- return defmem;
- // Perfect singleton memory, so all updates are parallel and
- // independent and stack.
- for( int i=2; i<nIns(); i++ ) {
- Node in = in(i);
- if( in !=null && in._type.isHigh() )
- return TypeMem.TOP;
- if( in instanceof StoreNode st ) {
- Type val = ((TypeMem)st._type)._t;
- Field old = ts.field(st._name);
- // Lazy add an expected field for open structs.
- if( old==null ) { assert ts._open;
- old = Field.make(st._name,Type.BOTTOM,st._alias,st._init);
- ts = ts.add(old);
- }
- Field fld = old.makeFrom(val);
- // TODO: val leaks into perfect singleton memory, along with its fidxs and aliases
- ts = ts.replace(fld);
- }
- }
- return TypeMem.makePrivate(ts);
-
- }
-
- // Normal public memory; meet across escaped inputs
- TypeMem mem = defmem;
- for( int i=2; i<nIns(); i++ ) {
- // Has this alias escaped?
- if( mem._escAs.contains(aliasAt(i)) &&
- in(i) != null && !in(i)._type.isHigh() ) {
- mem = (TypeMem)mem.meet(in(i)._type);
- }
- }
- return mem;
- }
-
- @Override public Node idealize() {
- assert nIns() != 0 && in(1)!=null; // Always have a default. if( nIns()==0 ) return null;
-
- // Preserve the existing fold rule for this storage experiment: every alias
- // slot must explicitly equal the default. Do not also change which empty
- // aggregates fold away; that changes optimization order and spill decisions.
- boolean progress=false, allDefault=nIns()==_aliasLimit;
- for( int i=2; i<nIns(); i++ ) {
- if( in(1)==in(i) ) { removeAlias(i--); progress=true; }
- else allDefault=false;
- }
-
- // If not merging any memory (all memory is just the default)
- if( allDefault )
- return in(1); // Become default memory
-
- // Collapse stacked merged-mem
- if( in(1) instanceof MemMergeNode mem ) {
- // A dead memory cycle can lose its last use when we bypass mem.
- // Keep the peephole's result alive until the worklist sees it.
- keep();
- // Goal is to swap my default mem with mem's default mem
- for( int i=2; i<mem.nIns(); i++ ) {
- if( mem.in(i) != null ) {
- // deeper default mem has a non-default
- int alias = mem.aliasAt(i);
- if( explicitAlias(alias)==null )
- alias(alias,mem.in(i));
- }
- }
- CodeGen.CODE.add(mem.in(1));
- setDef(1,mem.in(1));
- return unkeep();
- }
-
- return progress ? this : null;
- }
-
-
- public Node in( Var v ) { return in(v._idx); }
-
- public Node alias( int alias ) {
- Node precise = explicitAlias(alias);
- assert !(in(1) instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) && precise==null);
- return precise==null ? in(1) : precise;
- }
-
- public Node alias( int alias, Node st ) {
- if( alias==1 ) return setDef(1,st);
- assert alias>1;
- _aliasLimit=Math.max(_aliasLimit,alias+1);
- int input = _aliasToInput==null ? 0 : _aliasToInput.get(alias);
- if( st==null ) {
- if( input!=0 ) removeAlias(input);
- return st;
- }
- if( input!=0 ) return setDef(input,st);
- if( _aliases==null ) {
- _aliases = new AryInt();
- _aliasToInput = new IntHashMap(0);
- }
- int pos = Arrays.binarySearch(_aliases._es,0,_aliases.len(),alias);
- assert pos<0;
- pos = -pos-1;
- _aliases.insert(pos,alias);
- for( int i=pos; i<_aliases.len(); i++ ) _aliasToInput.put(_aliases.at(i),i+2);
- insertDef(pos+2,st);
- return st;
- }
-
- // Now one-time do a useless-phi removal
- void _useless( ) {
- for( int i=1; i<nIns(); i++ ) {
- if( in(i) instanceof PhiNode phi ) {
- // Do an eager useless-phi removal
- Node in = phi.peephole();
- CodeGen.CODE.addAll(phi._outputs);
- phi.moveDepsToWorklist();
- if( in != phi ) {
- if( !phi.iskeep() ) // Keeping phi around for parser elsewhere
- phi.subsume(in);
- setDef(i,in); // Set the update back into Scope
- }
- }
- }
- }
-
- @Override public boolean eq( Node n ) {
- return this==n;
- }
-}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/MemOpNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
index bce11b50..27506ad2 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/MemOpNode.java
@@ -148,12 +148,18 @@ public abstract class MemOpNode extends TypeNode {
private Ary<Node> antiDeps( Node mem, Ary<Node> antideps ) {
for( Node use : mem._outputs ) {
- if( use instanceof MemMergeNode merge ) {
- if( merge.alias(_alias)==mem )
- antiDeps(merge,antideps);
+ if( use instanceof MemJoinNode merge ) {
+ if( merge.isSlice() ) {
+ if( merge.sliceAlias()==_alias && !antideps.contains(merge) ) antideps.add(merge);
+ } else {
+ // Both public and private sides are ordering inputs.
+ boolean reads=!merge.hasAlias(_alias) && merge.pub()==mem;
+ for( int i=0; i<merge.size(); i++ )
+ reads |= merge.aliasAt(2+3*i)==_alias && (merge.pub(i)==mem || merge.priv(i)==mem);
+ if( reads ) antiDeps(merge,antideps);
+ }
} else if( use instanceof CallNode || use instanceof CLInitNode ||
(use instanceof MemOpNode st && !st._isLoad && st._alias==_alias) ||
- (use instanceof EscapeNode esc && esc.fld()._alias==_alias) ||
(use instanceof MemPhiNode phi && phi._alias==_alias) ||
(use instanceof BulkMemPhiNode phi && !phi.isSplit(_alias)) ) {
if( !antideps.contains(use) ) antideps.add(use);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java
index aaaedb89..938fcebf 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/MemPhiNode.java
@@ -54,12 +54,12 @@ public class MemPhiNode extends PhiNode {
@Override
public Node idealize() {
- // A precise memory Phi can always bypass a MemMerge and select its
+ // A precise memory Phi can always bypass a MemJoin and select its
// matching slice.
for( int i=1; i<nIns(); i++ ) {
- if( in(i) instanceof MemMergeNode mem ) {
- setDef(i,mem.alias(_alias));
- return this;
+ if( in(i) instanceof MemJoinNode mem ) {
+ Node slice=mem.alias(_alias);
+ if( slice!=mem ) { setDef(i,slice); return this; }
}
Node slice = CLInitNode.slice(in(i),_alias,this);
if( slice!=in(i) ) { setDef(i,slice); return this; }
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java b/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java
index e52b7762..ac072a74 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/Node.java
@@ -72,8 +72,8 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
public enum Tag {
Add,And,BulkMemPhi,EQ,NE,LT,LE,ULT,
CallEnd,Call,ConFldOff,Con,CLInit,CProj,
- Div,Escape,Extern,ExternOffset,Fun,FunPtr,Guard,
- If,Load,Loop,MemMerge,MemPhi,Minus,Mul,
+ Div,Extern,ExternOffset,Fun,FunPtr,Guard,
+ If,Load,Loop,MemJoin,MemPhi,Minus,Mul,
New,Never,Not,Or,Parm,Phi,Proj,PtrToInt,
ReadOnly,Return,Region,RoundF32,
Sar,Shl,Shr,Start,StartCU,StopCU,Stop,Store,Sub,
@@ -120,13 +120,12 @@ public abstract class Node extends BaseNode<Node> implements Cloneable {
case Mod -> new ModNode(null,null,(byte)bais.packed1());
case CProj -> CProjNode.make(bais,strs);
case Con -> ConstantNode.make(bais ,types);
- case Escape-> EscapeNode.make(bais ,types);
case Extern-> ExternNode.make(bais,strs,types);
case ExternOffset-> new ExternOffsetNode(strs[bais.packed2()]);
case FunPtr-> FunPtrNode.make(bais, types);
case Fun -> FunNode.make(bais,strs,types);
case Load -> new LoadNode(bais,strs,types,fileAliases,aliases);
- case MemMerge->MemMergeNode.make(bais);
+ case MemJoin ->MemJoinNode.make(bais,types,fileAliases,aliases);
case MemPhi-> MemPhiNode.make(bais,strs,types,fileAliases,aliases);
case BulkMemPhi-> BulkMemPhiNode.make(bais,strs,types,fileAliases,aliases);
case New -> NewNode.make(bais ,types);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java
index aea402f6..65807b12 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ParmNode.java
@@ -87,7 +87,7 @@ public class ParmNode extends PhiNode {
Type arg = in(i)._type;
// The unknown-caller callback input is Start's memory
// projection, interpreted using this parameter's signature.
- if( i==1 && r.in(i) instanceof StartNode && _idx>1 && arg instanceof TypeMem outside )
+ if( i==1 && r.in(i) instanceof StartNode && _declaredType instanceof TypeFunPtr && arg instanceof TypeMem outside )
arg = outside.outside(_declaredType);
t = t.meet(arg);
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index 94376086..c6bab40c 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -5,6 +5,7 @@ import com.seaofnodes.print.ExprPrinter;
import com.seaofnodes.simple.*;
import com.seaofnodes.simple.codegen.Serialize;
+import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.*;
import java.util.HashMap;
@@ -184,8 +185,8 @@ public class PhiNode extends Node {
// 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) {
- 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;
+ if( op instanceof CFGNode || op instanceof ConstantNode || op instanceof PhiNode ||
+ op instanceof ProjNode || op instanceof NewNode || op instanceof ScopeNode || op instanceof MemJoinNode ) return false;
// A bulk Phi must split its aliases before factoring precise Stores.
if( this instanceof BulkMemPhiNode ) return false;
// Bulk splitting currently identifies parallel slices by Region/alias.
@@ -264,6 +265,9 @@ public class PhiNode extends Node {
for( Node in : x._inputs )
if( in!=null ) in.addUse(x);
x = x.peephole();
+ // The trial Phi had no users during its first peephole.
+ // Revisit it after the factored operation is connected.
+ CodeGen.CODE.add(x);
cp._inputs.set(j,x);
}
if( x!=null ) x.addUse(cp);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java
index f2972c91..1108f64f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ReturnNode.java
@@ -71,6 +71,7 @@ public class ReturnNode extends CFGNode {
}
@Override public Parser.ParseException err() {
+ if( _fun.returnState().ctl()==Type.XCONTROL ) return null;
if( ctrl()._type == Type.CONTROL &&
expr()._type == Type.TOP )
return Parser.error("No defined return type",null);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java
index 854a0d9b..21a8ebc2 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java
@@ -30,9 +30,9 @@ public class SarNode extends ArithNode {
int shift = (int)(i.value()&63);
if( shift==0 ) return lhs;
// A value already in the signed range needs no further extension.
- if( lhs instanceof ShlNode && lhs.in(2)._type instanceof TypeInteger j &&
+ if( lhs instanceof ShlNode && addDep(lhs.in(2))._type instanceof TypeInteger j &&
j.isConstant() && (j.value()&63)==shift ) {
- Node value = lhs.in(1);
+ Node value = addDep(lhs.in(1));
if( value._type instanceof TypeInteger && value._type==_type )
return value;
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
index 80d2aa0a..3c48f551 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ScopeNode.java
@@ -16,7 +16,7 @@ import java.util.*;
* The Scope node is purely a parser helper - it tracks names to nodes with a
* stack of variables.
*/
-public class ScopeNode extends MemMergeNode {
+public class ScopeNode extends MemJoinNode {
/**
* The control is a name that binds to the currently active control
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java
index 204e0c4b..7fd4f20a 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java
@@ -77,7 +77,7 @@ public class StoreNode extends MemOpNode {
@Override
public Type compute() {
Type val = val()._type;
- Type mem0 = mem()._type;
+ Type mem0 = _alias>1 && mem() instanceof MemJoinNode join ? join.sliceType(_alias,this) : mem()._type;
Type ptr0 = ptr()._type;
// Validate argument types
if( ptr0.isHigh() || mem0.isHigh() )
@@ -116,7 +116,7 @@ public class StoreNode extends MemOpNode {
// Allocation uses a private TypeMem and nothing else does. This
// memory is truly private; a temporary singleton until it escapes -
// which is never does in a constructor.
- if( !_name.equals("[]") && mem._one )
+ if( _name!="[]" && mem._one )
// Just track the stored value
return TypeMem.make(_alias,val,true,false,fld==null ? _init : fld._final,null,null).escapesFrom(val,outside);
@@ -132,7 +132,9 @@ public class StoreNode extends MemOpNode {
Type t = val.meet(tfld);
// Bulk memory's final bit describes its conservative remainder, not
// this newly precise slice. Slice finality comes from the field.
- boolean xfinal = fld != null && fld._final;
+ // An open receiver may still carry a provisional forward field.
+ // Finality falls in the lattice, so do not promise mutability yet.
+ boolean xfinal = ptr._obj._open || (fld != null && fld._final);
return TypeMem.make(_alias,t,mem._one,mem._clz,xfinal,mem._escFs,mem._escAs).escapesFrom(val,outside);
}
@@ -149,21 +151,21 @@ public class StoreNode extends MemOpNode {
assert !(mem()._type instanceof TypeMem mem) || _alias == 1 || mem._alias == 1 || _alias == mem._alias;
- // Simple store-after-MemMerge to a known alias can bypass. Happens when inlining.
+ // Simple store-after-MemJoin to a known alias can bypass. Happens when inlining.
Node mem = mem();
- if( _alias != 1 && mem instanceof MemMergeNode merge ) {
- setDef(1,merge.alias(_alias));
- return this;
+ if( _alias != 1 && mem instanceof MemJoinNode merge ) {
+ Node slice=merge.alias(_alias);
+ if( slice!=mem ) { setDef(1,slice); return this; }
}
Field fld;
if( _alias==1 && ptr()._type instanceof TypeMemPtr tmp && (fld=tmp._obj.field(_name)) != null && _size != 0 ) {
- // Expand Store(bulkMem,alias#1) into MemMerge(bulkMem,#N:Store(bulkMem,alias#N)).
+ // Expand Store(bulkMem,alias#1) into MemJoin(bulkMem,#N:Store(bulkMem,alias#N)).
// Normally I'd like to just drop in this xform and move on, but
// users of the bulk Store memory might nontheless depend on the
// sharp memory type (e.g. I64) from the store's memory. Using the
- // MemMerge means using the bulk memory which e.g. might be BOT.
+ // MemJoin means using the bulk memory which e.g. might be BOT.
// Check for store users with the same alias, and use the new store
// directly, preserving the sharper graph.
Node st = new StoreNode(_loc,_name,fld._alias,fld._t,in(0),mem,ptr(),off(),val(),_init,_size).peephole();
@@ -176,9 +178,9 @@ public class StoreNode extends MemOpNode {
i--; // setDef removed use from this Store's outputs
}
}
- MemMergeNode mmm = mem instanceof BulkMemPhiNode bulk
+ MemJoinNode mmm = mem instanceof BulkMemPhiNode bulk
? bulk.aggregate(mem,fld._alias,st)
- : new MemMergeNode(null,mem);
+ : new MemJoinNode(null,mem);
if( !(mem instanceof BulkMemPhiNode) )
mmm.alias(fld._alias,st);
return mmm.init();
@@ -251,8 +253,8 @@ public class StoreNode extends MemOpNode {
Field fld = obj.field(_name);
if( fld == null || fld._t == null )
return 0;
- if( fld._t == Type.BOTTOM )
- return 0; // Store into a final field
+ // Broad inferred declarations still reserve full-width slots. Match
+ // TypeStruct's layout rather than leaving these Stores unsized.
assert fld._t != Type.TOP;
// Freshly parsed field stores retain the declaring structure on their
// symbolic offset even after the pointer's flow type sharpens.
@@ -275,7 +277,7 @@ public class StoreNode extends MemOpNode {
return switch( use ) {
case MemOpNode mem -> mem._alias;
case MemPhiNode phi -> phi._alias;
- case EscapeNode esc -> esc.pub()==this ? esc.fld()._alias : 0;
+ case MemJoinNode join -> join.isSlice() && join.pub(0)==this ? join.sliceAlias() : 0;
default -> 0;
};
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index 5b945457..5cf2d50a 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -9,16 +9,51 @@ import java.util.HashMap;
public class SummaryNode extends CFGNode implements MultiNode {
public TypeTuple _state;
- // Callees and touched class initializers, by FIDX, for class-init cycle checks.
+ // Callees and touched class initializers, by FIDX. Used for class-init
+ // cycle checks and to retain callees until their call sites are loaded.
public final int[] _classDependencyFIDXs;
+ // Inputs [2,_args) are actual arguments; the remaining inputs retain
+ // callees whose call sites are still inside this unloaded body.
+ private final int _args;
public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, Node... inputs) {
super(inputs);
_state = state;
_classDependencyFIDXs = classDependencyFIDXs;
+ _args = inputs[0] instanceof FunNode fun ? 2+fun.sig().nargs() : inputs.length;
CodeGen.CODE.add(CodeGen.CODE._globalEscapes);
}
+ // Bind after all summaries have been installed, so forward references
+ // can use ordinary graph edges rather than another linker-side table.
+ public void bindCallees() {
+ assert nIns()==_args;
+ if( _classDependencyFIDXs==null ) return;
+ for( int fidx : _classDependencyFIDXs ) {
+ if( fidx==0 ) continue; // Unknown callbacks are covered by escapes.
+ FunNode fun = CodeGen.CODE._link(fidx);
+ if( (fun==null || fun.isDead()) && CodeGen.CODE._phase!=null &&
+ CodeGen.CODE._phase.ordinal()>CodeGen.Phase.Opto.ordinal() )
+ fun = CodeGen.CODE.restoreFunction(fidx);
+ if( fun!=null && !fun.isDead() )
+ addDef(new FunPtrNode(fun.sig(),CodeGen.CODE._start,fun.ret()).init());
+ }
+ }
+
+ public boolean references(FunPtrNode ptr) {
+ for( int i=_args; i<nIns(); i++ ) if( in(i)==ptr ) return true;
+ return false;
+ }
+
+ // SCCP activates these defaults only when this summary becomes reachable.
+ // A dependency does not publish the callee's function pointer.
+ public void linkCallees() {
+ for( int i=_args; i<nIns(); i++ ) {
+ FunPtrNode ptr = (FunPtrNode)in(i);
+ if( ptr.ret()!=null ) Opto.linkStart(CodeGen.CODE,ptr.fun());
+ }
+ }
+
@Override public String label() { return "Summary"; }
@Override public boolean blockHead() { return true; }
@Override public Type compute() {
@@ -26,7 +61,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 = firstArgument(); i<nIns(); i++ ) {
+ for( int i = firstArgument(); i<_args; 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,7 +74,7 @@ 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 = firstArgument(); i<nIns(); i++ ) {
+ for( int i = firstArgument(); i<_args; 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);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java b/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java
index 55a9cdb0..9f820ad1 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/arm/arm.java
@@ -52,7 +52,7 @@ public class arm extends Machine {
static final long WR_BITS = 0x7FFFFFFFL; // All the GPRs, not RSP
static final RegMask WMASK = new RegMask(WR_BITS);
- // Float mask from(d0–d31)
+ // Float mask from(d0–d31)
static final long FP_BITS = 0xFFFFFFFFL<<D0;
static final RegMask DMASK = new RegMask(FP_BITS);
@@ -319,12 +319,11 @@ public class arm extends Machine {
case ConstantNode con-> con(con);
case DivNode div -> div.mode()==2 ? new DivFARM(div) : new DivARM(div);
case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new ModARM(mod);
- case EscapeNode esc -> new EscapeNode(esc);
case FunNode fun -> new FunARM(fun);
case FunPtrNode fptr -> fptr(fptr);
case IfNode iff -> jmp(iff);
case LoadNode ld -> ld(ld);
- case MemMergeNode mem-> new MemMergeNode(mem);
+ case MemJoinNode mem-> new MemJoinNode(mem);
case MinusNode neg -> {
if( neg.mode()==2 ) throw Utils.TODO();
yield new NegARM(neg);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java b/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java
index 70585732..a92c423a 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/riscv/riscv.java
@@ -223,12 +223,11 @@ public class riscv extends Machine {
case ConstantNode con -> con(con);
case DivNode div -> div.mode()==2 ? new DivFRISC(div) : new DivRISC(div);
case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new DivRISC(mod);
- case EscapeNode esc -> new EscapeNode(esc);
case FunNode fun -> new FunRISC(fun);
case FunPtrNode fptr -> fptr(fptr);
case IfNode iff -> jmp(iff);
case LoadNode ld -> ld(ld);
- case MemMergeNode mem -> new MemMergeNode(mem);
+ case MemJoinNode mem -> new MemJoinNode(mem);
case MinusNode neg -> {
if( neg.mode()==2 ) throw Utils.TODO();
yield new NegRISC(neg);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java b/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
index 9e0d864a..8ac758f9 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
@@ -308,12 +308,11 @@ public class x86_64_v2 extends Machine {
case ConstantNode con -> con(con);
case DivNode div -> div.mode()==2 ? new DivFX86(div) : new DivX86(div);
case ModNode mod -> mod.mode()==2 ? new ModFNode(mod) : new DivX86(mod);
- case EscapeNode esc -> new EscapeNode(esc);
case FunNode fun -> new FunX86(fun);
case FunPtrNode fptr -> fptr(fptr);
case IfNode iff -> jmp(iff);
case LoadNode ld -> ld(ld);
- case MemMergeNode mem -> new MemMergeNode(mem);
+ case MemJoinNode mem -> new MemJoinNode(mem);
case MinusNode neg -> neg.mode()==2 ? new NegFX86(neg) : new NegX86(neg);
case MulNode mul -> mul.mode()==2 ? new MulFX86(mul) : mul(mul);
case NewNode nnn -> new NewX86(nnn);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
index 481d2851..594376ff 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java
@@ -106,11 +106,10 @@ final class Allocations {
Node st = P.peep(new StoreNode(null, "#", 1, TypeInteger.U32, null, smem, self, ConFldOffNode.make(ts,"#"), len.unkeep(), true));
Node prior = P.mem();
- Node esc = P.peep(new EscapeNode(lenFld,self,st,prior));
- P.mem(P.mergeAlias(prior,lenFld._alias,esc));
- prior = P.mem();
- esc = P.peep(new EscapeNode(bodyFld,self,smem,prior));
- P.mem(P.mergeAlias(prior,bodyFld._alias,esc));
+ MemJoinNode join = new MemJoinNode(null,prior);
+ join.join(lenFld ,prior,st ,self,false);
+ join.join(bodyFld,prior,smem,self,false);
+ P.mem(P.peep(join));
smem.unkeep();
return self.unkeep();
}
@@ -186,17 +185,13 @@ final class Allocations {
}
priv.keep();
+ MemJoinNode merge = new MemJoinNode(null,pub);
for( Field field : ts._fields ) {
Type storage = field._t.makeStorage();
Field escaped = field._final ? field : field.makeFrom(storage).makeFrom(true);
- pub.keep();
- Node esc = new EscapeNode(escaped,self,priv,pub).peephole();
- MemMergeNode merge = new MemMergeNode(null,pub);
- merge.alias(field._alias,esc);
- Node next = merge.peephole();
- pub.unkeep();
- pub = next;
+ merge.join(escaped,pub,priv,self,false);
}
+ pub = merge.peephole();
Node finished = new ConstructNode(self,priv,P.loc(),ctor!=null).peephole();
priv.unkeep();
ReturnNode ret = (ReturnNode)new ReturnNode(ctl,pub,finished,rpc,fun).peephole();
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
index 079853cd..6b310b76 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java
@@ -69,9 +69,10 @@ final class ArrayInitializers {
Node result=new ArrayInitNode(P.ctrl(),mem,self,len,
generator ? -1 : values.size(),site,values).peephole().keep();
Node prior=P.mem();
- P.mem(P.mergeAlias(prior,length._alias,new EscapeNode(length,result,slen.unkeep(),prior).peephole()));
- prior=P.mem();
- P.mem(P.mergeAlias(prior,body._alias,new EscapeNode(body,result,mem,prior).peephole()));
+ MemJoinNode join=new MemJoinNode(null,prior);
+ join.join(length,prior,slen.unkeep(),result,false);
+ join.join(body ,prior,mem ,result,false);
+ P.mem(join.peephole());
mem.unkeep(); self.unkeep(); len.unkeep();
for( Node value : values ) value.unkeep();
result.unkeep();
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Construction.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Construction.java
index 7797cae4..a552c8d6 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Construction.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Construction.java
@@ -18,7 +18,7 @@ import com.seaofnodes.simple.util.Ary;
* the original constructor may write through an incomplete pointer.
*
* Calls borrowing self receive its Stores on the ordinary public memory edge,
- * using aliasable Escape slices without publishing its identity. Field values
+ * using borrowed MemJoin slices without publishing its identity. Field values
* come from memory, not the pointer's initialization shape. Incomplete values
* may be retained only in private construction memory. Nested object references
* conservatively promise no initialized fields; arrays are born initialized.
@@ -101,15 +101,12 @@ final class Construction {
Node self = _frame._self;
TypeStruct ts = (TypeStruct)Parser.TYPES.get(((TypeMemPtr)self._type)._obj._name);
Node priv = selfMem().keep();
+ MemJoinNode loan = new MemJoinNode(null,pub);
for( Field fld : ts._fields ) {
- pub.keep();
- Node loan = new EscapeNode(fld,self,priv,pub,true).peephole();
- Node next = P.mergeAlias(pub,fld._alias,loan);
- pub.unkeep();
- pub = next;
+ loan.join(fld,pub,priv,self,true);
}
priv.unkeep();
- return pub;
+ return loan.peephole();
}
boolean own(Node ptr) {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java
index 6c626669..0a306d0f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java
@@ -70,7 +70,6 @@ final class ControlFlow {
// control, memory and locals just as an explicit else arm does.
if( doRHS || fside.equals("||") )
fScope = P._scope;
- pred.unkeep();
// Check the trinary widening int/flt
if( !fside.equals("else") ) {
@@ -86,6 +85,8 @@ final class ControlFlow {
tScope.balanceIf(fScope);
// Merge results
+ boolean trueExits = tScope.ctrl()._type==Type.XCONTROL;
+ boolean falseExits = fScope.ctrl()._type==Type.XCONTROL;
RegionNode r = P.ctrl(tScope.mergeScopes(fScope,P.loc()));
Node ret = P.peep(new PhiNode("",r,lhs.unkeep(),rhs.unkeep()));
// Immediately fail e.g. `arg ? 7 : ptr`
@@ -93,6 +94,12 @@ final class ControlFlow {
if( !fside.equals("else") && (err = ret.err()) !=null ) throw Parser.error(err.getMessage(),site);
ret.keep();
r.peephole();
+ // Locals retain their guarded values in Scope. Fields are loaded
+ // again, so retain the surviving branch's facts as well. A write or
+ // call changes the memory input and prevents reuse of a guarded Load.
+ if( trueExits != falseExits )
+ P._scope.addGuards((CFGNode)P.ctrl(),pred,trueExits);
+ pred.unkill();
return ret.unkeep();
}
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java
index a7726521..cc5e3144 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java
@@ -238,7 +238,7 @@ final class Functions {
// - - If isInit, also incrementally extend the self-type.
// If isInit
// - upgrade and close the self-type
- // - Store class singleton fields; instance Stores already exist
+ // - Field Stores already exist at their source positions
// - <init> and user constructors return their current private memory
// Unstack the {break,continue,return} scopes.
@@ -297,16 +297,14 @@ final class Functions {
// Last expression is the return
if( P.ctrl()._type==Type.CONTROL ) {
// Constructors get special return types
- if( fun.isClz() ) {
- assert last!=null;
- } else if( isCtor ) {
+ if( isCtor && !fun.isClz() ) {
last = P.construction.selfMem();
}
addReturn(last);
// exit path is now dead (nothing live after a "return")
}
if( isInit )
- P.structs.finishInitializer(typeName,fun.isClz(),self);
+ P.structs.finishInitializer(typeName,self);
// Build a return from the _returnScope.
// Can be no returns for never-exit functions
@@ -385,15 +383,12 @@ final class Functions {
expr.keep();
// Force the pending lazy bulk-memory Phi.
P.mem(); // Force a pending lazy bulk-memory Phi
- // Class fields are still stored at exit. Instance fields already
- // travel in expr's private memory; only their scope layout is retained.
+ // Both initializers already carry their field Stores in memory.
+ // Retain only the declaration layout across early-return scopes.
int lexN = P._scope.enclosingFuncOrDecl();
Kind.Func k = (Kind.Func)P._scope._kinds.at(lexN);
if( FunNode.isInit(k._name) ) {
int nestedLexSize = lexN+1 < P._scope.depth() ? P._scope._kinds.at(lexN+1)._lexSize : P._scope.nIns();
- if( k._name.endsWith(".<clinit>") )
- for( int i = k._lexSize; i<nestedLexSize; i++ )
- P._scope.update(P._scope.var(i),null);
if( _returnScope != null ) {
Var vexpr = _returnScope._vars.pop();
Node oldX = _returnScope.removeLast();
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Parser.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Parser.java
index 9c18385d..626a6335 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Parser.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Parser.java
@@ -264,7 +264,7 @@ public class Parser {
// precise alias update. ScopeNode treats this as one opaque value.
Node mergeAlias(Node bulk, int alias, Node precise) {
assert bulk != null : "Missing bulk memory for alias #"+alias;
- MemMergeNode merge = new MemMergeNode(null,bulk);
+ MemJoinNode merge = new MemJoinNode(null,bulk);
merge.alias(alias,precise);
return peep(merge);
}
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
index 4796995f..5deb799c 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java
@@ -74,7 +74,13 @@ final class References {
if( var._fref )
return P.expressions.parsePostfix(rvalue);
Node fieldSelf = fieldSelf(var);
- if( fieldSelf!=null ) return parseField(fieldSelf,id,pre);
+ if( fieldSelf!=null ) {
+ int afterName=P.pos();
+ char ch=pre==0 ? P._lexer.matchOperAssign() : (char)pre;
+ P.pos(afterName);
+ if( ch!=0 ) checkAssignment(var,site);
+ return parseField(fieldSelf,id,pre);
+ }
int kx = P._scope.kindx(var);
int fx = P._scope.enclosingFunction();
@@ -244,6 +250,9 @@ final class References {
if( fld!=null && decl==Type.BOTTOM && !ts._fref )
throw Parser.error( "'" + ts._name + "' is not fully initialized, field '" + fld._fname + "' needs to be set in a constructor",site );
Node op = P.expressions.opAssign(ch,load, decl ).keep();
+ // The RHS may itself write fields or call a helper. Preserve its
+ // memory effects before storing this update's result.
+ mem = P.construction.storeMemory(expr);
mem.keep();
if( !P.construction.own(expr) && expr._type instanceof TypeMemPtr view && view._ro && P.ctrl()._type!=Type.XCONTROL )
throw Parser.error("Cannot modify final field '"+name+"'",site);
@@ -263,24 +272,25 @@ final class References {
Node defaultSelf() {
int selfx = P._scope._kinds.at(P._scope.enclosingFuncOrDecl())._lexSize;
- return P._scope.in(P._scope.update(P._scope.var(selfx),null));
+ Node self = P._scope.in(P._scope.update(P._scope.var(selfx),null));
+ // A singleton's declarations extend its shape while parsing. Instance
+ // receivers instead keep their construction/access-qualified view.
+ if( self._type instanceof TypeMemPtr ptr && ptr._one && Parser.TYPES.get(ptr._obj._name) instanceof TypeStruct shape )
+ return P.peep(new ConvertNode(ptr.makeFrom(shape),self));
+ return self;
}
- // Find the receiver for a field lvalue. Instance initializers use memory;
- // class declarations retain their Scope values until initializer exit.
+ // Fields use their receiver's memory, including inside their own initializer.
Node fieldSelf(Var var) {
int kx = P._scope.kindx(var);
ScopeNode.Kind kind = P._scope._kinds.at(kx);
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;
+ ptr._obj._name==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;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java
index 0c2a25f7..e72a11b2 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java
@@ -194,7 +194,6 @@ final class Statements {
P.ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection
P._scope.addGuards(ifT,pred.unkeep(),false); // Up-cast predicate
parseStatement().isKill(); // Parse loop body
- P._scope.removeGuards(ifT);
// Merge the loop bottom into other continue statements
if (_continueScope != null) {
@@ -212,6 +211,9 @@ final class Statements {
throw P.errorSyntax( "Unexpected code after expression" );
P.pos(old);
}
+ // The condition also guards the for-update. Reloaded fields need
+ // these facts just as locals do; stores still change their memory.
+ P._scope.removeGuards(ifT);
// The true branch loops back, so whatever is current _scope.ctrl gets
// added to head loop as input. endLoop() updates the head scope, and
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java
index 3a3d894c..55bc2946 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java
@@ -194,7 +194,7 @@ final class Structs {
return nvar;
}
- void finishInitializer( String typeName, boolean isClz, ParmNode self ) {
+ void finishInitializer( String typeName, ParmNode self ) {
int lex = P._scope.klast()._lexSize;
assert P._scope.var(lex)._name=="self";
TypeStruct tself = (TypeStruct)Parser.TYPES.get(typeName);
@@ -222,57 +222,25 @@ final class Structs {
// Improve the receiver type in scope.
// Class self-type is a singleton pointer. Instance <init> receives the
// broad allocation pointer, while private memory tracks initialized fields.
- self._declaredType = self._type = isClz ? TypeMemPtr.make((byte)2,tself,true) : TypeMemPtr.make(constructorRecv(tself)).withPartial(true);
FunNode fun = self.fun();
+ self._declaredType = self._type = fun.isClz() ? TypeMemPtr.make((byte)2,tself,true) : TypeMemPtr.make(constructorRecv(tself)).withPartial(true);
+ P._code.addAll(self._outputs);
+ self.moveDepsToWorklist();
fun.setSig(fun.sig().makeFrom(self._type,0));
-
- // When can _returnScope be null here? A never-exit constructor will
- // not have any returns, and thus no need to gather values and store
- // them into the (never) constructed object
- if( P.functions._returnScope==null )
- return;
-
- // Class singleton fields retain their store-at-exit path. Instance
- // initializers already returned their current private memory.
- if( !isClz ) return; // Instance fields already have their Stores.
- Node mmm = P.functions._returnScope.mem(1);
-
- // Store constructor results into fields
- for( int i = 0; i<tself.nkids(); i++ ) {
- Field fld = tself._fields[i];
- int vidx = fieldVarIdx(base,fld._fname);
- if( vidx == -1 )
- continue;
- Var v = P._scope.var(vidx);
- if( v._fref || v._extern!=0 ) continue; // C storage has no Simple initializer
- Node val = P.functions._returnScope.in(vidx);
- // A numeric merge can still be untyped while parsing. Retain its
- // declared conversion at the helper boundary, as assignments do.
- if( fld._t instanceof TypeInteger || fld._t instanceof TypeFloat )
- val = P.conversions.convertExpr(val,fld._t);
- // Store value into extended struct
- Node prior = mmm.keep();
- Node st = P.peep(new StoreNode(null, fld._fname, fld._alias, fld._t, null, prior, self, ConFldOffNode.make(tself,fld._fname), val, fld._final));
- mmm = P.mergeAlias(prior,fld._alias,st);
- prior.unkeep();
- }
- mmm = mmm.peephole();
-
- P.functions._returnScope.mem(mmm);
}
- // Instance declarations establish field metadata and emit their default
+ // Initializer declarations establish field metadata and emit their default
// Stores immediately. Required fields emit no Store until assigned.
void declareField(Var var, Node value, boolean uninit) {
- if( !(P._scope.klast() instanceof Kind.Func kind) || !FunNode.isInstance(kind._name) ) return;
- TypeStruct self = P._scope.constructorSelf();
+ if( !(P._scope.klast() instanceof Kind.Func kind) || !FunNode.isInit(kind._name) ) return;
+ TypeStruct self = ((TypeMemPtr)P._scope.var(kind._lexSize).type())._obj;
TypeStruct shape = (TypeStruct)Parser.TYPES.get(self._name);
Field old = shape.field(var._name);
Field fld = old==null ? Field.make(var._name,var.type(),P._code.alias(P._ref._cname),var._final) : old.makeFrom(var.type());
Parser.TYPES.put(shape._name,shape = shape.addOrUpdate(fld));
if( uninit || var._extern!=0 ) return;
Node ptr = P.references.defaultSelf();
- Node mem = P.construction.selfMem().keep();
+ Node mem = P.construction.memory(ptr).keep();
Node st = new StoreNode(var._loc,fld._fname,fld._alias,fld._t,P.ctrl(),mem,ptr,
ConFldOffNode.make(shape,fld._fname),value,true).peephole();
P.construction.store(ptr,fld._alias,st,mem);
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
index 8c19e897..d30ca21d 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java
@@ -137,7 +137,7 @@ final class Types {
TypeStruct self = P._scope.constructorSelf();
// Function types without a body must allow for writes. Function
// expressions can infer a weaker requirement in MethodAccess.
- return self == null ? TypePtr.PTR : TypeMemPtr.make(self);
+ return self == null ? TypePtr.PTR : TypeMemPtr.make(latestStruct(self));
}
// A function type is `{ type... -> type }` or `{ type }`.
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java b/chapter33/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java
index e4d1659d..d22b573f 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/print/ASMPrinter.java
@@ -54,8 +54,7 @@ public final class ASMPrinter extends AssemblyAdapter<Node> {
if( n instanceof PhiNode || n instanceof ProjNode )
if( n._type instanceof TypeMem || n._type instanceof TypeRPC ) return true;
if( postAlloc() && n instanceof CalleeSaveNode ) return true;
- if( n instanceof MemMergeNode ) return true;
- if( n instanceof EscapeNode ) return true;
+ if( n instanceof MemJoinNode ) return true;
return n.getClass()==ConstantNode.class;
}
@Override public boolean postAlloc() { return _code._phase.ordinal()>CodeGen.Phase.RegAlloc.ordinal() ||
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/print/IRPrinter.java b/chapter33/src/main/java/com/seaofnodes/simple/print/IRPrinter.java
index 531a549a..8f9fb616 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/print/IRPrinter.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/print/IRPrinter.java
@@ -12,7 +12,7 @@ public final class IRPrinter extends IRAdapter<Node> {
new com.seaofnodes.print.IRPrinter<>(new IRPrinter());
@Override public boolean global(Node n) { return n.isConst(); }
@Override public String type(Node n) { return n._type==null ? "" : n._type.str(); }
- @Override public String inputMark(Node n, Node def) { return n instanceof MemMergeNode && def instanceof MemMergeNode ? "^" : " "; }
+ @Override public String inputMark(Node n, Node def) { return n instanceof MemJoinNode && def instanceof MemJoinNode ? "^" : " "; }
@Override public Kind kind(Node n) {
if( n instanceof StartCUNode ) return Kind.UNIT;
if( n instanceof StopCUNode ) return Kind.UNIT;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java b/chapter33/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java
index 9ca0ec51..34695be7 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/print/SimpleGraphAdapter.java
@@ -64,9 +64,8 @@ public class SimpleGraphAdapter extends GraphAdapter<Node> {
if( n instanceof RegionNode && i == 0 ) return Role.ASSOC;
// Preserve known slot roles even when an input is not attached/typed yet.
if( i == 0 || n instanceof RegionNode || n instanceof StopNode ) return Role.CTRL;
- if( n instanceof MemMergeNode ||
- (i == 1 && (n instanceof MemOpNode || n instanceof ReturnNode || n instanceof CallNode)) ||
- (n instanceof EscapeNode && i >= 2) ) return Role.MEM;
+ if( n instanceof MemJoinNode ) return i>=2 && (i-2)%3==2 ? Role.DATA : Role.MEM;
+ if( i == 1 && (n instanceof MemOpNode || n instanceof ReturnNode || n instanceof CallNode) ) return Role.MEM;
Node def = n.in(i);
if( def instanceof CFGNode ) return Role.CTRL;
if( def != null && isMem(def) ) return Role.MEM;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java b/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java
index beaa719c..5b661e73 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java
@@ -115,7 +115,7 @@ public class Field extends Type {
int hash() { return _fname.hashCode() ^ _t.hashCode() ^ _alias ^ (_final ? 1024 : 0) ^ (_extern ? 2048 : 0); }
private boolean static_eq( Field f ) {
- return _fname.equals(f._fname) && _alias==f._alias && _final==f._final && _extern==f._extern && _t !=null && f._t !=null;
+ return _fname==f._fname && _alias==f._alias && _final==f._final && _extern==f._extern && _t !=null && f._t !=null;
}
@Override boolean eq( Type t ) {
Field f = (Field)t;
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java
index a56aee69..011cbb37 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java
@@ -185,6 +185,19 @@ public class TypeMem extends Type {
return make(_alias,_t._upgradeType(TYPES),_one,_clz,_final,_escFs,_escAs);
}
+ @Override public TypeMem upgradeType(HashMap<String,Type> TYPES) {
+ TypeMem mem = (TypeMem)super.upgradeType(TYPES);
+ Type t = mem._t;
+ // A final singleton slot may have been seeded while its referent was
+ // still open. Recompute its escapes after closure, when recursive
+ // types are interned and their cached alias/FIDX summaries are valid.
+ // Aggregate memory and mutable slots can also hold earlier escapes.
+ if( mem._one && mem._clz && mem._final && mem._alias!=1 && t.isConstant() && !opaque(t) )
+ return make(mem._alias,t,mem._one,mem._clz,mem._final,
+ escapeFIDX(TypeSet.EMPTY,t),escapeAlias(TypeSet.EMPTY,t));
+ return mem;
+ }
+
@Override int hash() { return 9876543 + _alias + _t.hashCode() + (_one ? 8196 : 0) + (_clz ? 4098 : 0) + (_final ? 16392 : 0) + _escFs.hashCode() + _escAs.hashCode(); }
@Override boolean eq(Type t) {
diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
index dc5d5f18..86728184 100644
--- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
+++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
@@ -152,6 +152,8 @@ public class TypeStruct extends Type {
Field[] fs = new Field[_fields.length];
for( int i=0; i<_fields.length; i++ ) {
if( _fields[i]._extern ) { fs[i] = _fields[i]; continue; }
+ // BOT means unwritten, including during SCCP. TOP would disappear
+ // at a merge with a written path and hide missing initialization.
fs[i] = _fields[i].makeFrom(TypeScalar.BOT);
}
return make(_name,_open,_fref,fs);
@@ -336,7 +338,7 @@ public class TypeStruct extends Type {
int len = Math.min(_fields.length,that._fields.length);
for( int i=0; i<len; i++ ) {
Field f0 = _fields[i], f1 = that._fields[i];
- if( !f0._fname.equals(f1._fname) || f0._alias != f1._alias || f0._extern != f1._extern )
+ if( f0._fname!=f1._fname || f0._alias != f1._alias || f0._extern != f1._extern )
return BOT;
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java b/chapter33/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java
index cf57865e..27207523 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/BulkMemPhiTest.java
@@ -4,28 +4,77 @@ import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.TypeInteger;
import com.seaofnodes.simple.type.TypeMem;
+import com.seaofnodes.simple.type.TypeMemPtr;
import com.seaofnodes.simple.type.Type;
import com.seaofnodes.simple.type.TypeSet;
+import com.seaofnodes.simple.type.TypeStruct;
+import com.seaofnodes.simple.type.Field;
import org.junit.Test;
import static org.junit.Assert.*;
public class BulkMemPhiTest {
+ @Test public void testJoinedPrivateSliceSurvivesBulkPhi() {
+ for( boolean borrow : new boolean[]{false,true} ) {
+ CodeGen code=new CodeGen("");
+ code._phase=CodeGen.Phase.Lower;
+ Field field=Field.make("count",TypeInteger.I32,55,false);
+ TypeStruct shape=TypeStruct.make("JoinedCount",false,field);
+ Node defaults=code.con(TypeMem.START);
+ Node priv=code.con(TypeMem.makePrivate(shape));
+ MemJoinNode joined=new MemJoinNode(null,defaults)
+ .join(field,defaults,priv,code.con(TypeMemPtr.make(shape)),borrow).init();
+ Node ctrl=new CProjNode(code._start,0,"Ctrl").init();
+ Node iff=new IfNode(ctrl,code.con(TypeInteger.BOOL)).init();
+ RegionNode region=new RegionNode(null,null,
+ new CProjNode(iff,0,"True").init(),
+ new CProjNode(iff,1,"False").init()).init();
+ BulkMemPhiNode bulk=new BulkMemPhiNode("$mem",region,joined,defaults).init();
+ // The public input equals the default, but the private update must
+ // still be split out before the bulk Phi bypasses the join.
+ MemJoinNode split=(MemJoinNode)bulk.idealize();
+ assertTrue(split.hasAlias(55));
+ assertTrue(((BulkMemPhiNode)split.pub()).isSplit(55));
+ assertEquals(55,((TypeMem)split.alias(55)._type)._alias);
+ }
+ }
+
+ @Test public void testHighMemoryArmKeepsEscapeBound() {
+ CodeGen code = new CodeGen("");
+ code._phase = CodeGen.Phase.Lower;
+ code.recordPublicAliases(TypeStruct.make("Visible",false,Field.make("method",Type.BOTTOM,55,true)));
+ Node defaults = code.con(TypeMem.START);
+ Node method = code.con(TypeMem.make(55,Type.BOTTOM,false,false,false,TypeSet.of(4),TypeSet.EMPTY));
+ MemJoinNode fields = new MemJoinNode(null,defaults);
+ fields.alias(55,method);
+ fields.init();
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ NeverNode never = new NeverNode(1.2f,ctrl).init();
+ RegionNode region = new RegionNode(null,null,
+ new CProjNode(never,0,"True").init(),
+ new CProjNode(never,1,"False").init()).init();
+ BulkMemPhiNode bulk = new BulkMemPhiNode("$mem",region,fields,code.con(Type.TOP)).init();
+ MemJoinNode split = (MemJoinNode)bulk.idealize();
+ assertTrue("Splitting a synthetic exit must not widen memory",split._type.isa(bulk._type));
+ assertSame(TypeSet.of(4),((TypeMem)split.alias(55)._type)._escFs);
+ }
+
@Test public void testUnescapedSliceKeepsItsOwnEscapes() {
CodeGen code = new CodeGen("");
code._phase = CodeGen.Phase.Lower;
Node defaults = code.con(TypeMem.START);
Node method = code.con(TypeMem.make(55,Type.BOTTOM,false,false,false,TypeSet.of(4),TypeSet.EMPTY));
- MemMergeNode fields = new MemMergeNode(null,defaults);
+ MemJoinNode fields = new MemJoinNode(null,defaults);
fields.alias(55,method);
fields.init();
- assertSame("The bulk excludes this unescaped field",TypeMem.START,fields._type);
+ assertSame("A private unescaped slice does not publish its contents",
+ TypeSet.EMPTY,((TypeMem)fields._type)._escFs);
Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
Node iff = new IfNode(ctrl,code.con(TypeInteger.BOOL)).init();
RegionNode region = new RegionNode(null,null,
new CProjNode(iff,0,"True").init(),
new CProjNode(iff,1,"False").init()).init();
BulkMemPhiNode bulk = new BulkMemPhiNode("$mem",region,fields,defaults).init();
- MemMergeNode split = (MemMergeNode)bulk.idealize();
+ MemJoinNode split = (MemJoinNode)bulk.idealize();
Node precise = split.alias(55);
assertTrue("A new slice must not inherit an escape bound that excludes its method",
precise.compute().isa(precise._type));
@@ -33,7 +82,25 @@ public class BulkMemPhiTest {
assertTrue(((TypeMem)precise._type)._escFs.contains(4));
}
- // Reduced from Capitalize's Lower-phase failure. A precise MemMerge slot
+ @Test public void testPublicOrReachableSlicePublishesContents() {
+ CodeGen code = new CodeGen("");
+ code._phase = CodeGen.Phase.Opto;
+ code.recordPublicAliases(TypeStruct.make("Visibility",false,
+ Field.make("method",Type.BOTTOM,55,true),Field.make("_method",Type.BOTTOM,56,true)));
+ for( int alias : new int[]{55,56} ) {
+ Node method = code.con(TypeMem.make(alias,Type.BOTTOM,false,false,false,TypeSet.of(4),TypeSet.EMPTY));
+ for( boolean reachable : new boolean[]{false,true} ) {
+ Node defaults = code.con(TypeMem.START.makeFrom(TypeSet.EMPTY,reachable ? TypeSet.of(alias) : TypeSet.EMPTY));
+ MemJoinNode fields = new MemJoinNode(null,defaults);
+ fields.alias(alias,method);
+ fields.init();
+ assertEquals(alias==55 || reachable,((TypeMem)fields._type)._escFs.contains(4));
+ assertTrue(((TypeMem)fields.alias(alias)._type)._escFs.contains(4));
+ }
+ }
+ }
+
+ // Reduced from Capitalize's Lower-phase failure. A precise MemJoin slot
// may still be supplied by bulk memory which covers the requested alias.
@Test public void testBulkInPreciseSlot() {
CodeGen code=new CodeGen("");
@@ -49,7 +116,7 @@ public class BulkMemPhiTest {
// collapse before the surrounding aggregate gets another peephole.
RegionNode done=new RegionNode(null,null,region,code.XCTRL).init();
MemPhiNode precise=new MemPhiNode("$4",4,done,bulk,m1).init();
- MemMergeNode merge=new MemMergeNode(null,m0);
+ MemJoinNode merge=new MemJoinNode(null,m0);
merge.alias(4,precise);
merge.init();
Node folded=precise.peepholeOpt();
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java b/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java
index 7983141d..058e385b 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java
@@ -78,7 +78,7 @@ public class CallEndTest {
// with its data parameter, not share it with the old body.
FldOffNode off = new FldOffNode(fun.parm(3),"<<",null).init();
fun.ret().setDef(2,off);
- assertSame(Type.BOTTOM,off._type);
+ assertSame(TypeInteger.BOT,off._type);
assertTrue("Unresolved field offset belongs to the function",fun.body().get(off._nid));
return;
}
@@ -145,6 +145,31 @@ public class CallEndTest {
}
}
+ // A callback can become finite before Call idealize links its Returns.
+ // Computing CallEnd first must preserve the outside call's memory bound.
+ @Test public void testSpecializedUnlinkedCallRetainsMemory() {
+ CodeGen code = new CodeGen("return 0;").driver(CodeGen.Phase.Opto);
+ code._phase = CodeGen.Phase.IterPostOpto;
+ TypeFunPtr unknown = TypeFunPtr.make(false,TypeFunPtr.TEMPTY,TypeInteger.I32);
+ Node fptr = ConstantNode.raw(unknown);
+ CallNode call = new CallNode(null,ConstantNode.raw(Type.CONTROL),
+ ConstantNode.raw(TypeMem.START),fptr).init();
+ CallEndNode end = new CallEndNode(call,TypeRPC.BOT);
+ TypeTuple outside = (TypeTuple)end.compute();
+ end.setType(outside);
+ assertNotSame(TypeMem.BOT,outside.mem());
+
+ fptr._type = TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOOL,100);
+ assertTrue(fptr._type.isa(unknown));
+ TypeTuple finite = (TypeTuple)end.compute();
+ assertTrue(finite.isa(outside));
+ assertSame(outside.mem(),finite.mem());
+ assertSame(TypeInteger.BOOL,finite.ret());
+ end.setType(finite);
+ assertSame(finite,end.compute());
+ assertEquals("compute must not link Returns",1,end.nIns());
+ }
+
@Test public void testExternalTargets() {
CodeGen code = new CodeGen("return 0;").parse();
code.externFunc(100,"first");
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index 9f733da5..89b0553d 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -58,13 +58,16 @@ else
public void testIfMergeB() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a=arg+1;
int b=0;
if( arg==1 )
b=a;
else
b=a+1;
-return a+b;""");
+return a+b;
+}
+""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return ((((Phi(Region,arg,(((arg+1)<<32)>>32))+1)<<32)>>32)+Sar);", code.print());
}
@@ -73,13 +76,16 @@ return a+b;""");
public void testIfMerge2() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a=arg+1;
int b=arg+2;
if( arg==1 )
b=b+a;
else
a=b+1;
-return a+b;""");
+return a+b;
+}
+""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return ((((Phi(Region,arg,(((arg+2)<<32)>>32))+1)<<32)>>32)+(((Phi(Region,(((arg+1)<<32)>>32),2)+Phi(Region,Sar,arg))<<32)>>32));", code.print());
}
@@ -108,6 +114,7 @@ return a;
public void testMerge4() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a=0;
int b=0;
if( arg )
@@ -115,6 +122,7 @@ if( arg )
if( arg==0 )
b=2;
return arg+a+b;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
String ir = code.print();
@@ -127,12 +135,14 @@ return arg+a+b;
public void testMerge5() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a=arg==2;
if( arg==1 )
{
a=arg==3;
}
return a;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return (arg==Phi(Region,3,2));", code.print());
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java
index d1af5d14..39809ae0 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java
@@ -246,6 +246,7 @@ return a+b;
@Test
public void testDemo2NonConst() {
CodeGen code = new CodeGen("""
+{ // Local SSA regression; file-level bindings are class fields.
int a = 0;
int b = 1;
int c = 0;
@@ -256,6 +257,7 @@ if( arg ) {
else b = 3;
}
return a+b+c;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return Phi(Region,6,1,5);", code.print());
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java
index 20786571..6b53c394 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java
@@ -42,6 +42,7 @@ return a;
public void testWhileNested() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int sum = 0;
int i = 0;
while(i < arg) {
@@ -53,6 +54,7 @@ while(i < arg) {
}
}
return sum;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return Phi(Loop,0,Phi(Loop,Phi_sum,(((Phi_sum+Phi(Loop,0,(((Phi_j+1)<<32)>>32)))<<32)>>32)));", code.print());
@@ -62,6 +64,7 @@ return sum;
public void testWhileScope() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a = 1;
int b = 2;
while(a < 10) {
@@ -69,6 +72,7 @@ while(a < 10) {
else b = 4;
}
return b;
+}
""");
code.parse();
assertEquals("return Phi(Loop,2,Phi(Region,Phi_b,4));", code.print());
@@ -131,9 +135,11 @@ return a;
public void testWhile2() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a = 1;
while(arg) a = 2;
return a;
+}
""");
code.parse();
assertEquals("return Phi(Loop,1,2);", code.print());
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java
index 249beb11..d88016b9 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java
@@ -34,6 +34,7 @@ return arg;
public void testEx5() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a = 1;
while(arg < 10) {
arg = arg + 1;
@@ -44,7 +45,8 @@ while(arg < 10) {
a = a + 1;
}
return a;
- """);
+}
+""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return Phi(Loop,1,Phi(Region,Phi_a,(((Phi_a+1)<<32)>>32),Phi_a));", code.print());
assertTrue(code.ctrl() instanceof CProjNode);
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java
index 13950789..8d9b5b85 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java
@@ -105,6 +105,7 @@ public class Chapter10Test {
public void testFuzzer() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a = arg/3;
int b = arg*5;
int x = arg*7;
@@ -121,6 +122,7 @@ if( (arg/13)==0 ) {
}
int r = g+h;
return p-r;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return 0;", code.print());
@@ -386,16 +388,16 @@ return ret.v0;
CodeGen code = new CodeGen(
"""
int cnt = 1;
-// cnt is incremented exactly once, it is not part of s0 constructor
-// hence s0.x is always 1, and cnt remains at 2
+// Each instance initializer increments the class field.
struct s0 { int x = cnt++; };
s0 a = new s0();
s0 b = new s0();
-// a.x==1, b.x==1, cnt==2
+// a.x==1, b.x==2, cnt==3
return a.x * 100 + b.x * 10 + cnt;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("Stop[ return 112; return Test.s0; ]", code.print());
+ assertEquals("Stop[ return 123; return Test.s0; ]", code.print());
+ assertEquals("123",Eval2.eval(code,0));
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java
index b2d773ee..7f2fa6a1 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java
@@ -11,6 +11,7 @@ public class Chapter13Test {
public void testPrimes() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
if( arg < 2 ) return 0;
int primeCount = 1;
int prime = 3;
@@ -33,6 +34,7 @@ while( prime <= arg ) {
prime = prime + 2;
}
return primeCount;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return Phi(Region,0,Phi(Loop,1,Phi(Region,Phi_primeCount,Phi_primeCount,(((Phi_primeCount+1)<<32)>>32))));", code.print());
@@ -143,6 +145,7 @@ return i;
public void testAntiDeps5() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
struct _S { int f; };
!_S !v = new _S;
while(1) {
@@ -151,9 +154,10 @@ while(1) {
v.f = 2;
}
return v.f;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return ((Phi(Loop,0,2)<<32)>>32);", code.print());
+ assertEquals("return Phi(Loop,0,2);", code.print());
for( int arg : new int[]{-1,0,1,3,100} )
assertEquals("0",Eval2.eval(code,arg));
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java
index bc2ad8d3..640416ff 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java
@@ -55,9 +55,11 @@ return b;
public void testU8While() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
u8 b = 123;
while( b ) b = b + 456;// Truncate
return b;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return 0;", code.print());
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java
index 8a66dcc5..2cd7cbd8 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java
@@ -482,10 +482,12 @@ return sum;
@Test
public void testFor1() {
CodeGen code = new CodeGen("""
+{ // Local SSA regression; file-level bindings are class fields.
int sum=0, i=0;
for( ; i<arg; i++ )
sum += i;
return sum;
+}
""");
code.driver(CodeGen.Phase.FinalizeIR);
assertEquals("return Phi(Loop,0,(((Phi_sum+Phi(Loop,0,(((Phi_i+1)<<32)>>32)))<<32)>>32));", code.print());
@@ -588,7 +590,8 @@ for( ; ptr; ptr = ptr.next )
return sum;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return Phi(Loop,0,(((Phi_sum+.i)<<32)>>32));", code.print());
+ // Class fields can retain constructor bodies; inspect this entry's return.
+ assertEquals("return Phi(Loop,0,(((Phi_sum+.i)<<32)>>32));", code.link(code.compunit()).ret().toString());
assertEquals("45", Eval2.eval(code, 10));
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java
index b1caae96..b6dc5138 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter18Test.java
@@ -13,6 +13,52 @@ import static org.junit.Assert.*;
import static org.junit.Assert.fail;
public class Chapter18Test {
+ @Test public void testLateInlineNonreturningLoop() {
+ CodeGen code = new CodeGen("val spin_noInline={ -> while(1) {} }; if(arg) spin_noInline(); return 7;")
+ .driver(Phase.TypeCheck);
+ FunNode spin = code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("spin_noInline") ? f : null);
+ assertNotNull(spin);
+ CallEndNode end = code._stop.walk(n -> n instanceof CallEndNode c && c.nIns()==2 && c.in(1)==spin.ret() ? c : null);
+ assertNotNull(end);
+ spin._name="spin";
+ code.add(end);
+ code._iter.iterate(code);
+ assertTrue(end.isDead());
+ assertEquals("7",Eval2.eval(code,0));
+ assertNull(Eval2.eval(code,1,10));
+ }
+
+ @Test public void testLateInlineLoopTree() {
+ CodeGen code = new CodeGen("""
+ val work_noInline = { i64 n -> i64 j=0; while(j<n) j++; return j; };
+ val keep_noInline = { i64 n -> i64 j=0; while(j<n) j+=2; return j; };
+ i64 i=0;
+ while(i<arg) { i=work_noInline(i)+1; }
+ return i+keep_noInline(arg);
+ """).driver(Phase.TypeCheck);
+ FunNode work = code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("work_noInline") ? f : null);
+ FunNode keep = code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("keep_noInline") ? f : null);
+ assertNotNull(work);
+ assertNotNull(keep);
+ LoopNode untouched = code._stop.walk(n -> n instanceof LoopNode l && !(l instanceof StartNode) && l.fun()==keep ? l : null);
+ assertNotNull(untouched);
+ CFGNode.LoopTree untouchedTree = untouched._ltree;
+ CallEndNode end = code._stop.walk(n -> n instanceof CallEndNode c && c.nIns()==2 && c.in(1)==work.ret() ? c : null);
+ assertNotNull(end);
+ LoopNode outer = end.call().loop();
+ CFGNode.LoopTree oldTree = outer._ltree;
+ // Permit this one call to inline after the initial normalization.
+ work._name="work";
+ code.add(end);
+ code._iter.iterate(code);
+ assertTrue("The late call was inlined",end.isDead());
+ assertNotSame("Rebuild the caller",oldTree,outer._ltree);
+ assertSame("Leave other functions alone",untouchedTree,untouched._ltree);
+ assertNotNull(code._stop.walk(n -> n instanceof LoopNode l && l!=outer &&
+ l._ltree!=null && l._ltree._par==outer._ltree ? l : null));
+ assertEquals("11",Eval2.eval(code,5));
+ }
+
@Test public void testNeverExitLoopDepth() {
String[] sources = {
"if(arg) while(1) {} return 7;",
@@ -21,7 +67,7 @@ public class Chapter18Test {
"int x=0; while(arg) { if(arg==2) while(1) { x++; } x++; arg--; } return x;"
};
for( String src : sources ) {
- CodeGen code = new CodeGen(src).driver(CodeGen.Phase.LoopTree);
+ CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck);
int[] nevers = {0};
code._stop.walk(n -> {
if( n instanceof FunNode fun )
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java
index 50fecdfd..0d97a91c 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java
@@ -294,13 +294,16 @@ return a;""");
public void testIfMerge2() {
CodeGen code = new CodeGen(
"""
+{ // Local SSA regression; file-level bindings are class fields.
int a=arg+1;
int b=arg+2;
if( arg==1 )
b=b+a;
else
a=b+1;
-return a+b;""");
+return a+b;
+}
+""");
code.driver(Phase.LocalSched,"x86_64_v2", "SystemV");
assertEquals("return (add,(sari,(shli,(inc,Phi(Region,arg,(sari,(shli,(addi,arg))))))),(sari,(shli,(add,Phi(Region,(sari,(shli,(inc,arg))),2),Phi(Region,sari,arg)))));", code.print());
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java
index 226425ca..bf4ec581 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java
@@ -29,15 +29,19 @@ public class Chapter20Test {
};
for( String target : new String[]{"x86_64_v2","riscv","arm"} )
for( String src : sources ) {
- CodeGen code = new CodeGen(src).driver(CodeGen.Phase.RegAlloc,target,"SystemV");
+ CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck);
+ assertNotNull(code._stop.walk(n -> n instanceof com.seaofnodes.simple.node.NeverNode ? n : null));
+ code.driver(CodeGen.Phase.RegAlloc,target,"SystemV");
com.seaofnodes.simple.codegen.RegAllocTestSupport.checkRegisters(code);
- assertNotNull(code._stop.walk(n -> {
+ // Early normalization allows peepholes to fold Phi(value,TOP).
+ // Any TOP that survives must still need neither a register nor a split.
+ code._stop.walk(n -> {
if( n._type!=com.seaofnodes.simple.type.Type.TOP ) return null;
assertEquals(-1,code._regAlloc.regnum(n));
for( var use : n.outs() )
assertFalse(use instanceof com.seaofnodes.simple.node.SplitNode);
- return n;
- }));
+ return null;
+ });
code.encode();
}
}
@@ -154,6 +158,7 @@ return _sqrt(x) + _sqrt(y);
public void testNewtonFloat() {
String src =
"""
+{ // Local SSA regression; file-level bindings are class fields.
val _test_sqrt_noInline = { flt x ->
flt epsilon = 1e-15;
flt guess = x;
@@ -165,6 +170,7 @@ val _test_sqrt_noInline = { flt x ->
}
};
flt farg = arg; return _test_sqrt_noInline(farg) + _test_sqrt_noInline(farg+2.0);
+}
""";
testCPU(src,"x86_64_v2", "SystemV",40,null);
testCPU(src,"riscv" , "SystemV",17,null);
@@ -209,6 +215,7 @@ flt farg = arg; return _test_sqrt_noInline(farg) + _test_sqrt_noInline(farg+2.0)
public void testArray1() {
String src =
"""
+{ // Local SSA regression; file-level bindings are class fields.
int[] !ary = new int[arg];
// Fill [0,1,2,3,4,...]
for( int i=0; i<ary#; i++ )
@@ -217,9 +224,10 @@ for( int i=0; i<ary#; i++ )
for( int i=0; i<ary#-1; i++ )
ary[i+1] += ary[i];
return ary[1] * 1000 + ary[3]; // 1 * 1000 + 6
+}
""";
testCPU(src,"x86_64_v2", "SystemV",-1,"return (add,.[],(muli,.[]));");
- testCPU(src,"riscv" , "SystemV",9,"return (add,.[],(mul,.[],1000));");
+ testCPU(src,"riscv" , "SystemV",7,"return (add,.[],(mul,.[],1000));");
testCPU(src,"arm" , "SystemV",13,"return (add,.[],(mul,.[],1000));");
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index 7a59adb0..77fb0377 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -315,6 +315,7 @@ return new _s0.v1;
public void testArray1() {
String src =
"""
+{ // Local SSA regression; file-level bindings are class fields.
int[] !ary = new int[arg];
// Fill [0,1,2,3,4,...]
for( int i=0; i<ary#; i++ )
@@ -323,9 +324,10 @@ for( int i=0; i<ary#; i++ )
for( int i=0; i<ary#-1; i++ )
ary[i+1] += ary[i];
return ary[1] * 1000 + ary[3]; // 1 * 1000 + 6
+}
""";
testCPU(src,"x86_64_v2", "SystemV",-1,"return (add,.[],(muli,.[]));");
- testCPU(src,"riscv" , "SystemV",9,"return (add,.[],(mul,.[],1000));");
+ testCPU(src,"riscv" , "SystemV",7,"return (add,.[],(mul,.[],1000));");
testCPU(src,"arm" , "SystemV",13,"return (add,.[],(mul,.[],1000));");
}
@@ -430,6 +432,7 @@ val hashCode = { !String self ->
@Test public void testLoop2() {
String src =
"""
+{ // Local SSA regression; file-level bindings are class fields.
int i = 0;
while(true) {
i += 1;
@@ -439,6 +442,7 @@ while(true) {
continue;
}
return i;
+}
""";
testCPU(src,"x86_64_v2", "win64" ,0,"return (!=0)(sari,(shli,(inc,Phi(Loop,0,Phi(Region,(!=0),(!=0),0)))));");
testCPU(src,"riscv" , "SystemV",0,"return (!=0)( ( ( Phi(Loop,0,Phi(Region,(!=0),(!=0),0)) + #1 ) << #32 ) >> #1056 );");
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java
index 8667c0bd..87b41707 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java
@@ -226,6 +226,7 @@ return (x == 0 && y == 1 && z==-1) && switch && g
@Test
public void testFuncCall() throws IOException {
String src = """
+{ // Local SSA regression; file-level bindings are class fields.
int a = 1;
int b = 1;
var sq_noInline = { int x ->
@@ -234,8 +235,9 @@ var sq_noInline = { int x ->
return (a && sq_noInline(0))
? 1 // Error
: 0; // Expected
+}
""";
- TestC.runSF( src, "and3", "", 2);
+ TestC.runSF( src, "and3", "", 0);
// Evaluate on RISC5 emulator
EvalRisc5 R5 = TestRisc5.build( src, "and3", 0, 2, false);
@@ -252,7 +254,7 @@ return (a && sq_noInline(0))
@Test
- public void testFRefFields() {
+ public void testFRefFields() throws IOException {
String src = """
// A hypothetical scanner class
struct _Scan {
@@ -277,9 +279,12 @@ return _s.peek('q');
""";
CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck);
- assertEquals("return Phi(Region,0,1);", code.print());
+ // Public method fields can retain other Returns in the whole-unit graph.
+ assertEquals("return Phi(Region,0,1);", code.link(code.compunit()).ret().toString());
assertEquals("1", Eval2.eval(code, 0));
- testCPU(src,"x86_64_v2", "win64",23,null);
+ // Entry scores 22; retained public skip and peek bodies each add 16.
+ testCPU(src,"x86_64_v2", "win64",54,null);
+ TestC.runSF(src.replace("return _s.peek('q');","return _s.peek('q') != 1;"),"frefFields","",-1);
};
@Test
@@ -309,7 +314,7 @@ return s.skip().x;
@Test
- public void testMethod() {
+ public void testMethod() throws IOException {
String src = """
// A hypothetical scanner class
struct _Scan {
@@ -331,9 +336,11 @@ return _s.require('[');
""";
CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck);
- assertEquals("return (.[]==91);", code.print());
+ assertEquals("return (.[]==91);", code.link(code.compunit()).ret().toString());
assertEquals("1", Eval2.eval(code, 0));
- testCPU(src,"x86_64_v2", "win64",4, null);
+ // Entry scores 20; retained public skip and require bodies each add 16.
+ testCPU(src,"x86_64_v2", "win64",52,null);
+ TestC.runSF(src.replace("return _s.require('[');","return _s.require('[') != 1;"),"method","",-1);
};
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java
index f4c4f12f..93eb35ff 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java
@@ -99,6 +99,7 @@ return (10 < something_specific < 20)
@Test
public void testStack3() throws IOException {
String src ="""
+{ // Local SSA regression; file-level bindings are class fields.
var sq_noInline = { int x ->
x*x;
};
@@ -106,6 +107,7 @@ int score = 4;
return (sq_noInline(2) <= score < sq_noInline(3))
? 0 // Expected
: 1; // Error
+}
""";
TestC.runSF( src, "stacked_r_3", "",0);
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
index b243beb2..87f9564d 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter33Test.java
@@ -3,7 +3,8 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.util.WorkList;
-import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.type.*;
+import com.seaofnodes.simple.parser.Parser;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.Test;
@@ -11,6 +12,19 @@ import static org.junit.Assert.*;
/** Regressions for the independent compiler fixes introduced in this chapter. */
public class Chapter33Test {
+ @Test public void testBroadFieldStoreMatchesLayout() {
+ CodeGen code=new CodeGen("return 0;").driver(CodeGen.Phase.FinalizeIR);
+ int alias=code.alias("Test");
+ TypeStruct ts=TypeStruct.make("Test.Broad",false,Field.make("value",Type.BOTTOM,alias,false));
+ Parser.TYPES.put(ts._name,ts);
+ Node ptr=code.con(TypeMemPtr.make(ts));
+ StoreNode store=new StoreNode(null,"value",alias,Type.BOTTOM,null,
+ code.con(TypeMem.make(alias,Type.BOTTOM)),ptr,code.con(ts.offset(0)),code.con(4294967297L),false).init();
+ store.idealize();
+ assertEquals("A broad declaration still reserves a complete storage slot",
+ ts.offset(1)-ts.offset(0),store.storeSize());
+ }
+
@Test public void testWorkListRequeueAndTraversal() {
CodeGen code = new CodeGen("return arg;").parse();
Node arg = code.expr();
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java b/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java
index 4cacd0e6..3b52a5d2 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java
@@ -27,6 +27,53 @@ import org.junit.runners.model.Statement;
import static org.junit.Assert.*;
public class ClassInitDependenciesTest {
+ @Test public void testInitializedFlagAcrossCallers() throws Exception {
+ for( String name : new String[]{"_read_noInline","read_noInline"} )
+ for( boolean both : new boolean[]{true,false} ) {
+ CodeGen code=compile("A",Map.of("A","""
+ int state=0;
+ val _read_noInline={ -> B.value; };
+ int value=0;
+ if(arg) { state=1; value=B.value; value+=_read_noInline(); }
+ else { state=2; BEFORE value+=_read_noInline(); }
+ """.replace("BEFORE",both ? "value=B.value;" : "").replace("_read_noInline",name),"B","int value=arg;"),123);
+ CLInitNode touch=code._stop.walk(n -> n instanceof CLInitNode init &&
+ init.fun()._name.endsWith(name) ? init : null);
+ if( both && name.startsWith("_") ) assertNull("Every caller has already initialized B",touch);
+ else assertNotNull("An uninitialized or unknown caller still needs the check",touch);
+ }
+ }
+
+ @Test public void testLoweringPreservesLoopTree() throws Exception {
+ Path root=tempDir("lower-loops-");
+ Files.writeString(root.resolve("A.smp"),"int value=arg;");
+ CodeGen code=new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Main",
+ "int i=0; while(i<arg) { i+=A.value+1; } return i;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ var loops=new java.util.IdentityHashMap<LoopNode,CFGNode.LoopTree>();
+ int[] touches={0};
+ code._start.walk(n -> {
+ if( n instanceof LoopNode loop && !(loop instanceof StartNode) ) loops.put(loop,loop._ltree);
+ if( n instanceof CLInitNode init && init.loopDepth()>0 ) touches[0]++;
+ return null;
+ });
+ assertFalse(loops.isEmpty());
+ assertTrue("Exercise class initialization inside a loop",touches[0]>0);
+ CFGNode.LoopTree outer=code._start._ltree;
+ code.driver(CodeGen.Phase.Lower,"x86_64_v2","SystemV");
+ assertSame(outer,code._start._ltree);
+ for( var entry : loops.entrySet() )
+ if( !entry.getKey().isDead() ) assertSame(entry.getValue(),entry.getKey()._ltree);
+ code._start.walk(n -> {
+ if( n instanceof CFGNode cfg && !cfg.isDead() && !cfg._type.isHigh() &&
+ !(cfg instanceof StartNode) && !(cfg instanceof StopNode) &&
+ cfg.fun()!=null && cfg.fun().summary()==null )
+ assertNotNull("Missing containing loop for "+cfg.label(),cfg._ltree);
+ return null;
+ });
+ code.driver(CodeGen.Phase.Encoding,"x86_64_v2","SystemV");
+ }
+
@Test public void testPrivateInitializerCallEdges() throws Exception {
for( long seed : new long[]{1,123,987654321} ) {
Path root = tempDir("private-roots-");
@@ -429,7 +476,11 @@ public class ClassInitDependenciesTest {
if( n instanceof CLInitNode init && init.fun()==fun && init.cu()==b ) {
touches[0]++;
TypeTuple state=(TypeTuple)init._type;
- assertSame(TypeMem.BOT,state._types[1]);
+ // Initialization merges whole memory; its escape sets
+ // can be sharper than the all-escaped MemBot bound.
+ TypeMem memory=(TypeMem)state._types[1];
+ assertEquals(1,memory._alias);
+ assertSame(Type.BOTTOM,memory._t);
TypeMem flag=(TypeMem)state._types[2];
assertEquals(b._clz.field("$init")._alias,flag._alias);
assertSame(TypeInteger.TRUE,flag._t);
@@ -547,6 +598,18 @@ public class ClassInitDependenciesTest {
object(dir,dir,"Spin","val spin_noInline={ -> while(1) {} return 7; };");
CodeGen code=new CodeGen(null,dir.toString(),new Ary<>(new String[]{dir.toString()}),
"Main","Spin.spin_noInline(); return 7;",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
+ FunNode spin=code._stop.walk(n -> n instanceof FunNode f && f._name.endsWith("spin_noInline") ? f : null);
+ assertNotNull(spin);
+ assertNotNull(spin.summary());
+ assertSame(Type.XCONTROL,spin.returnState().ctl());
+ assertNull(Eval2.eval(code,0,10));
+ }
+
+ @Test public void testInlineNonreturningObject() throws Exception {
+ Path dir=tempDir("nonreturning-inline-");
+ object(dir,dir,"Spin","val spin={ -> while(1) {} return 7; };");
+ CodeGen code=new CodeGen(null,dir.toString(),new Ary<>(new String[]{dir.toString()}),
+ "Main","Spin.spin(); return 7;",123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
assertNull(Eval2.eval(code,0,10));
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java b/chapter33/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java
index 57954652..d07b0e43 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java
@@ -7,6 +7,28 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class EscapeFlowTest {
+ @Test public void testLocalLinkedListEscapeMonotonicity() {
+ CodeGen code = new CodeGen(
+"""
+{
+ struct _LLI {
+ _LLI? next;
+ i64 i;
+ new _LLI = { _LLI? n, i64 ii -> next=n; i=ii; };
+ };
+ _LLI? !head = null;
+ while( arg-- ) {
+ head = new _LLI(head,arg);
+ }
+ int sum = 0;
+ for( var ptr = head; ptr; ptr = ptr.next )
+ sum += ptr.i;
+ return sum;
+}
+""").driver(CodeGen.Phase.FinalizeIR);
+ assertEquals("45",Eval2.eval(code,10));
+ }
+
@Test public void testFieldPublicationSelectsValue() {
CodeGen code = new CodeGen("return 0;").parse();
TypeFunPtr callback = TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOT,7);
@@ -19,14 +41,14 @@ public class EscapeFlowTest {
// The aggregate includes escapes from other fields. Publishing just
// callback must not publish the whole construction group.
Node priv = code.con(TypeMem.makePrivate(shape));
- EscapeNode esc = new EscapeNode(selected,self,priv,code.con(pub));
- TypeMem result = (TypeMem)esc.compute();
+ MemJoinNode esc = new MemJoinNode(null,code.con(pub)).join(selected,code.con(pub),priv,self,false);
+ TypeMem result = (TypeMem)esc.sliceType(21,esc);
assertSame(TypeSet.of(3).with(7),result._escFs);
assertSame(TypeSet.of(4),result._escAs);
assertSame(callback,result._t);
- EscapeNode borrow = new EscapeNode(selected,self,priv,code.con(pub),true);
- assertSame(pub._escFs,((TypeMem)borrow.compute())._escFs);
- assertSame(pub._escAs,((TypeMem)borrow.compute())._escAs);
+ MemJoinNode borrow = new MemJoinNode(null,code.con(pub)).join(selected,code.con(pub),priv,self,true);
+ assertSame(pub._escFs,((TypeMem)borrow.sliceType(21,borrow))._escFs);
+ assertSame(pub._escAs,((TypeMem)borrow.sliceType(21,borrow))._escAs);
}
@Test public void testFieldPublicationAfterAliasSelection() {
@@ -35,12 +57,12 @@ public class EscapeFlowTest {
TypeStruct shape = TypeStruct.make("PublishCount",false,selected);
Node self = code.con(TypeMemPtr.make(shape));
TypeMem pub = TypeMem.START.makeFrom(TypeSet.of(3),TypeSet.of(4));
- EscapeNode esc = new EscapeNode(selected,self,code.con(TypeMem.makePrivate(shape)),code.con(pub));
- TypeMem before = (TypeMem)esc.compute();
- // An alias selected from a MemMerge can have a weaker scalar bound
+ MemJoinNode esc = new MemJoinNode(null,code.con(pub)).join(selected,code.con(pub),code.con(TypeMem.makePrivate(shape)),self,false);
+ TypeMem before = (TypeMem)esc.sliceType(21,esc);
+ // An alias selected from a MemJoin can have a weaker scalar bound
// and escape summary. The declared integer field cannot hold pointers.
- esc.setDef(2,code.con(TypeMem.make(21,TypeScalar.BOT,true,false,false,TypeSet.FULL,TypeSet.FULL)));
- assertSame(before,esc.compute());
+ esc.setDef(3,code.con(TypeMem.make(21,TypeScalar.BOT,true,false,false,TypeSet.FULL,TypeSet.FULL)));
+ assertSame(before,esc.sliceType(21,esc));
assertSame(pub._escFs,before._escFs);
assertSame(pub._escAs,before._escAs);
}
@@ -51,9 +73,8 @@ public class EscapeFlowTest {
Field selected = Field.make("external",opaque,21,false);
TypeStruct shape = TypeStruct.make("PublishOpaque",false,selected);
TypeMem pub = TypeMem.START.makeFrom(TypeSet.of(3),TypeSet.of(4));
- EscapeNode esc = new EscapeNode(selected,code.con(TypeMemPtr.make(shape)),
- code.con(TypeMem.makePrivate(shape)),code.con(pub));
- TypeMem result = (TypeMem)esc.compute();
+ MemJoinNode esc = new MemJoinNode(null,code.con(pub)).join(selected,code.con(pub),code.con(TypeMem.makePrivate(shape)),code.con(TypeMemPtr.make(shape)),false);
+ TypeMem result = (TypeMem)esc.sliceType(21,esc);
assertSame(pub._escFs,result._escFs);
assertSame(pub._escAs,result._escAs);
}
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java b/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java
index d6d97ef1..36303c9e 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/Eval2.java
@@ -316,10 +316,9 @@ public abstract class Eval2 {
case ModNode mod -> mod.mode()==1
? (Object)(x(mod.in(2))==0 ? 0L : x(mod.in(1)) % x(mod.in(2)))
: (Object)(d(mod.in(1)) % d(mod.in(2)));
- case EscapeNode esc -> esc(esc);
case FunPtrNode fptr -> con(fptr._con);
case LoadNode ld -> load(ld);
- case MemMergeNode merge-> "$mem";
+ case MemJoinNode join -> join(join);
case MinusNode sub -> sub.mode()==1 ? (Object)(- x(sub.in(1))) : (Object)(- d(sub.in(1)));
case MulNode mul -> mul.mode()==1
? (Object)(x(mul.in(1)) * x(mul.in(2)))
@@ -392,14 +391,15 @@ public abstract class Eval2 {
};
}
- // Escapes of constant memory actually needs to set the memory
- private static Object esc(EscapeNode esc) {
- if( esc.priv() instanceof ConstantNode con ) {
+ // Publishing constant private memory initializes the corresponding field.
+ private static Object join(MemJoinNode join) {
+ for( int i=0; i<join.size(); i++ )
+ if( join.fld(i)!=null && join.priv(i) instanceof ConstantNode con ) {
TypeMem mem = (TypeMem)con._type;
Object val = con(mem._t);
- TypeMemPtr tmp = (TypeMemPtr)esc.self()._type;
- int idx = layout(tmp._obj).findAlias(esc.fld()._alias);
- Object[] fs = (Object[])val(esc.self());
+ TypeMemPtr tmp = (TypeMemPtr)join.self(i)._type;
+ int idx = layout(tmp._obj).findAlias(join.fld(i)._alias);
+ Object[] fs = (Object[])val(join.self(i));
if( tmp._obj.isAry() ) {
assert idx==0; // length field
assert (Long)val==fs.length;
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
index 51ed10c6..ba8c721e 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java
@@ -37,8 +37,9 @@ public class GlobalAssignmentTest {
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;
+ // Default expressions run in the instance initializer, including
+ // their writes to class fields.
+ if( value!=17 || initialized.seen!=17 ) return 9;
return 0;
};
return main();
@@ -46,7 +47,29 @@ public class GlobalAssignmentTest {
@Test public void storesGlobalMemory() throws Exception {
assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0));
- TestC.runSF(SOURCE,"global_assignment","",-1);
+ // The native entry calls main itself, after initializing the class.
+ TestC.runSF(SOURCE.replace("return main();",""),"global_assignment","",-1);
+ }
+
+ @Test public void initializerHelpersShareMemory() throws Exception {
+ String src="""
+ int value=7;
+ val read_noInline={ -> value; };
+ val write_noInline={ int n -> value=n; return value; };
+ int first=read_noInline();
+ value=9;
+ int second=read_noInline();
+ int returned=write_noInline(11);
+ int third=value;
+ if( first!=7 || second!=9 || returned!=11 || third!=11 ) return 1;
+ for( int i=0; i<3; i++ ) {
+ value+=2;
+ if( read_noInline()!=13+2*i ) return 2;
+ }
+ return value!=17;
+ """;
+ assertEquals("0",Eval2.eval(new CodeGen(src).driver(CodeGen.Phase.TypeCheck),0));
+ TestC.runSF(src,"initializer_helpers","",-1);
}
@Test public void rejectsFinalGlobal() {
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/MemMergeTest.java b/chapter33/src/test/java/com/seaofnodes/simple/MemJoinTest.java
index 253bce0b..b5d418ab 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/MemMergeTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/MemJoinTest.java
@@ -2,66 +2,83 @@ package com.seaofnodes.simple;
import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.node.*;
-import com.seaofnodes.simple.type.TypeMem;
+import com.seaofnodes.simple.type.*;
import org.junit.Test;
import static org.junit.Assert.*;
-public class MemMergeTest {
+public class MemJoinTest {
+ @Test public void testUnknownPrivateShapeBoundsStoredReferences() {
+ CodeGen code=new CodeGen("return 0;").parse();
+ TypeFunPtr callback=TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOT,7);
+ TypeStruct shape=TypeStruct.make("PrivateCallback",false,Field.make("callback",callback,21,true));
+ Node base=ConstantNode.raw(TypeMem.makePrivate(Type.BOTTOM).makeFrom(TypeSet.EMPTY,TypeSet.EMPTY));
+ StoreNode store=new StoreNode(null,"callback",21,callback,code._start,base,
+ code.con(TypeMemPtr.make(shape)),code.con(TypeInteger.ZERO),code.con(callback),true).init();
+ MemJoinNode mem=new MemJoinNode(null,base);
+ mem.alias(21,store);
+ Type bound=mem.compute();
+ base._type=TypeMem.makePrivate(shape);
+ store._type=store.compute();
+ TypeMem precise=(TypeMem)mem.compute();
+ assertTrue(precise._escFs.contains(7));
+ assertTrue("Learning the private shape must refine the old result",precise.isa(bound));
+ }
+
@Test public void testDenseAliasesAndDefaults() {
CodeGen code = new CodeGen("");
Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT).keep();
- MemMergeNode mem = new MemMergeNode(null,defaults);
+ MemJoinNode mem = new MemJoinNode(null,defaults);
mem.alias(10000,value);
mem.alias(2,value);
mem.alias(513,value);
- assertEquals(5,mem.nIns());
+ assertEquals(11,mem.nIns());
assertEquals(2,mem.aliasAt(2));
- assertEquals(513,mem.aliasAt(3));
- assertEquals(10000,mem.aliasAt(4));
+ assertEquals(513,mem.aliasAt(5));
+ assertEquals(10000,mem.aliasAt(8));
assertSame(value,mem.alias(10000));
assertSame(defaults,mem.alias(512));
assertNull(mem.explicitAlias(9999));
assertSame(value,mem.explicitAlias(10000));
mem.alias(513,null);
- assertEquals(4,mem.nIns());
- assertEquals(10000,mem.aliasAt(3));
+ assertEquals(8,mem.nIns());
+ assertEquals(10000,mem.aliasAt(5));
assertSame(value,mem.alias(10000));
mem.alias(2,defaults);
assertSame(mem,mem.idealize());
- assertEquals(3,mem.nIns());
+ assertEquals(5,mem.nIns());
assertSame(defaults,mem.alias(2));
// Removing/reinserting colliding keys must not leave tombstones or stale slots.
for( int i=0; i<100; i++ ) {
mem.alias(100+i*8,value);
mem.alias(100+i*8,null);
}
- assertEquals(3,mem.nIns());
+ assertEquals(5,mem.nIns());
mem.alias(10000,defaults);
assertSame(mem,mem.idealize());
assertEquals(2,mem.nIns());
// Retain the sparse implementation's fold eligibility for this experiment.
assertNull(mem.idealize());
- assertSame(defaults,new MemMergeNode(null,defaults).idealize());
+ assertSame(defaults,new MemJoinNode(null,defaults).idealize());
value.unkeep();
}
@Test public void testIndependentCopyMaps() {
CodeGen code = new CodeGen("");
Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT);
- MemMergeNode mem = new MemMergeNode(null,defaults);
+ MemJoinNode mem = new MemJoinNode(null,defaults);
mem.alias(200,value);
- MemMergeNode copy = (MemMergeNode)mem.copyEmpty();
+ MemJoinNode copy = (MemJoinNode)mem.copyEmpty();
for( Node in : mem._inputs ) copy.addDef(in);
copy.alias(7,value);
- assertEquals(3,mem.nIns());
- assertEquals(4,copy.nIns());
+ assertEquals(5,mem.nIns());
+ assertEquals(8,copy.nIns());
assertSame(defaults,mem.alias(7));
assertSame(value,mem.alias(200));
copy.alias(200,null);
assertSame(value,mem.alias(200));
assertSame(defaults,copy.alias(200));
code._phase = CodeGen.Phase.Select;
- MemMergeNode selected = new MemMergeNode(mem);
+ MemJoinNode selected = new MemJoinNode(mem);
assertEquals(200,selected.aliasAt(2));
assertSame(value,selected.alias(200));
}
@@ -69,13 +86,13 @@ public class MemMergeTest {
@Test public void testStackedMergesKeepOverrides() {
CodeGen code = new CodeGen("");
Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT), override = code.con(TypeMem.TOP);
- MemMergeNode inner = new MemMergeNode(null,defaults);
+ MemJoinNode inner = new MemJoinNode(null,defaults);
inner.alias(8,value);
inner.alias(10000,value);
- MemMergeNode outer = new MemMergeNode(null,inner);
+ MemJoinNode outer = new MemJoinNode(null,inner);
outer.alias(10000,override);
assertSame(outer,outer.idealize());
- assertEquals(4,outer.nIns());
+ assertEquals(8,outer.nIns());
assertSame(defaults,outer.in(1));
assertSame(value,outer.alias(8));
assertSame(override,outer.alias(10000));
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java
index 6505009d..36ac1477 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/PhaseTest.java
@@ -27,7 +27,7 @@ public class PhaseTest {
code.driver(Phase.TypeCheck); // A repeated request does not rerun anything.
assertEquals("45",Eval2.eval(code,10));
code.driver(Phase.LocalSched);
- assertEquals("Parse Iter Opto IterPostOpto FinalizeIR TypeCheck LoopTree Unlink Schedule LocalSched",
+ assertEquals("Parse Iter Opto IterPostOpto FinalizeIR LoopTree TypeCheck Unlink Schedule LocalSched",
String.join(" ",phases));
assertNull(code._serial);
assertNull(code._mach);
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SchedulingTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SchedulingTest.java
index 28b84ee1..1ed79526 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/SchedulingTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/SchedulingTest.java
@@ -36,7 +36,7 @@ public class SchedulingTest {
Node no = new CProjNode(iff,1,"False").init();
RegionNode region = new RegionNode(null,null,yes,no).init();
Node phi = new BulkMemPhiNode("mem",region,ret.mem(),ret.mem()).init();
- Node mem = new MemMergeNode(null,phi).init();
+ Node mem = new MemJoinNode(null,phi).init();
Node load = new LoadNode(null,"[]",2,ctrl,mem,code.con(TypeMemPtr.BOT),code.con(TypeInteger.ZERO)).init();
ret.setDef(0,region);
ret.setDef(2,load);
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java
index 447025f6..d1bf474f 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/SelectiveLoadingTest.java
@@ -4,6 +4,8 @@ import com.seaofnodes.simple.parser.Parser;
import com.seaofnodes.simple.codegen.*;
import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.TypeInteger;
+import com.seaofnodes.simple.type.TypeTuple;
+import com.seaofnodes.simple.type.Type;
import com.seaofnodes.simple.util.Ary;
import java.io.IOException;
import java.nio.file.*;
@@ -11,6 +13,77 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class SelectiveLoadingTest {
+ @Test public void testNonreturningSummaryRetainsCallees() throws Exception {
+ Path root=library("summary-nonreturning-");
+ Ary<String> paths=new Ary<>(new String[]{root.toString()});
+ object(root,paths,"Library","""
+ var _state=0;
+ val _helper_noInline={ -> _state=1; };
+ val spin_noInline={ -> _helper_noInline(); while(1) {} return 7; };
+ """);
+ CodeGen code=new CodeGen(null,root.toString(),paths,"Main",
+ "Library.spin_noInline(); return 7;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.IterPostOpto);
+ assertSame(Type.XCONTROL,function(code,"spin_noInline").summary()._state.ctl());
+ FunNode helper=function(code,"_helper_noInline");
+ assertTrue(helper.hasSummaryCallers());
+ assertTrue("Calls before a nonreturning exit still execute",helper.unknownCallers());
+ }
+
+ @Test public void testUnreachableSummaryCycleIsNotARoot() throws Exception {
+ Path root=library("summary-cycle-");
+ Ary<String> paths=new Ary<>(new String[]{root.toString()});
+ object(root,paths,"Library","""
+ val _left_noInline={ i64 x -> x ? _right_noInline(x-1) : 0; };
+ val _right_noInline={ i64 x -> x ? _left_noInline(x-1) : 1; };
+ val entry_noInline={ i64 x -> _left_noInline(x); };
+ """);
+ for( long seed : new long[]{1,123,987654321} ) {
+ CodeGen code=new CodeGen(null,root.toString(),paths,"Main","""
+ val _false_noInline={ -> false; };
+ if(_false_noInline()) return Library.entry_noInline(((arg<<32)>>32));
+ return 7;
+ """,seed,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
+ CompUnit library=code._compunits.get("Library");
+ for( FunNode fun : code._linker )
+ assertTrue("A cycle of summary references must not root its functions",
+ fun==null || fun.isDead() || fun._compunit!=library);
+ assertEquals("7",Eval2.eval(code,0));
+ }
+ }
+
+ @Test public void testSummaryCalleeDefaultAndRelease() throws Exception {
+ Path root = library("summary-callees-");
+ Ary<String> paths = new Ary<>(new String[]{root.toString()});
+ object(root,paths,"Library","""
+ val _helper_noInline={ int x -> x+1; };
+ val entry_noInline={ int x -> _helper_noInline(x); };
+ """);
+ CodeGen code = new CodeGen(null,root.toString(),paths,"Main",
+ "return Library.entry_noInline(((arg<<32)>>32));",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.IterPostOpto);
+ FunNode helper = function(code,"_helper_noInline");
+ assertTrue("An unloaded caller retains the default",helper.unknownCallers());
+ assertTrue(helper.hasSummaryCallers());
+ assertFalse("A summary call does not publish its target",
+ ((TypeTuple)code._start._type).mem()._escFs.contains(helper.sig().fidx()));
+
+ code.loadForInline(code._compunits.get("Library"));
+ code._iter.iterate(code);
+ helper = function(code,"_helper_noInline");
+ assertFalse("Concrete calls replace the summary references",helper.hasSummaryCallers());
+ // Loading the direct call reveals no publication of the helper's
+ // function pointer. Neither Start may widen to include that FIDX.
+ assertFalse("Loading a direct caller must not publish its private callee",
+ ((TypeTuple)code._start._type).mem()._escFs.contains(helper.sig().fidx()));
+ assertFalse("The library Start must also exclude its private callee",
+ ((TypeTuple)helper._compunit._start._type).mem()._escFs.contains(helper.sig().fidx()));
+ assertFalse("With concrete callers and no escape, the default must be released",helper.unknownCallers());
+ assertTrue(helper.nIns()>1);
+ code.driver(CodeGen.Phase.TypeCheck);
+ assertEquals("42",Eval2.eval(code,41));
+ }
+
@Test public void testSharedConstantsInSeparateObjects() throws Exception {
Path root = library("shared-constants-");
Path src = Files.createDirectory(root.resolve("src"));
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
index 72e26a2e..f7dd0d0b 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
@@ -10,6 +10,81 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class SeparateCompilationTest {
+ @Test public void testGlobalReadAfterImportedInitializer() throws Exception {
+ Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"global-read-");
+ var paths=new Ary<>(new String[]{lib.toString()});
+ new CodeGen(null,lib.toString(),paths,"Library",
+ "val number_noInline={ ->7; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ CodeGen code=new CodeGen(null,lib.toString(),paths,"Client","""
+ var value=Library.number_noInline();
+ val read_noInline={ ->value; };
+ value=4294967297;
+ return read_noInline();
+ """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck);
+ assertEquals("4294967297",Eval2.eval(code,0));
+ }
+
+ @Test public void testInferredImportedFieldStoreWidth() throws Exception {
+ Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"inferred-store-");
+ new CodeGen(null,lib.toString(),null,"Library",
+ "val number_noInline={ -> 7; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ String src="""
+ struct Box { var value=Library.number_noInline(); };
+ val b=new Box;
+ b.value=4294967297;
+ return b.value;
+ """;
+ CodeGen code=new CodeGen(null,lib.toString(),paths,"Client",src,123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("4294967297",Eval2.eval(code,0));
+ TestC.run(src.replace("return b.value;","return b.value!=4294967297;"),
+ "inferred_import_store",paths,TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void testImportedNestedTypeOnlyReference() throws Exception {
+ Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"nested-type-");
+ new CodeGen(null,lib.toString(),null,"Library",
+ "struct Box { i64 x=42; };",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ // No expression mentions Library: only this parameter requests its type table.
+ CodeGen code=new CodeGen(null,lib.toString(),paths,"Client",
+ "val read_noInline={ Library.Box b -> b.x; }; return 0;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ for( String name : new String[]{"Library.Missing"} ) {
+ try {
+ new CodeGen(null,lib.toString(),paths,"Client",
+ "val read_noInline={ "+name+" b -> b.x; }; return 0;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("Accepted nonexistent nested type "+name);
+ } catch( com.seaofnodes.simple.parser.Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("Unknown type"));
+ }
+ }
+ }
+
+ @Test public void testNestedTypeInAnotherSourceUnit() throws Exception {
+ Path root=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"nested-source-");
+ Files.createDirectories(root.resolve("Main"));
+ Files.writeString(root.resolve("Main/Library.smp"),"struct Box { i64 x=42; };");
+ CodeGen code=new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Main",
+ "val read_noInline={ Library.Box b -> b.x; }; return 0;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("0",Eval2.eval(code,0));
+ try {
+ new CodeGen(root.toString(),root.resolve("obj").toString(),null,"Main",
+ "val read_noInline={ Library.Missing b -> b.x; }; return 0;",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ fail("The owning file exists, but it does not define Missing");
+ } catch( com.seaofnodes.simple.parser.Parser.ParseException expected ) {
+ assertTrue(expected.getMessage(),expected.getMessage().contains("Unknown type"));
+ }
+ }
+
@Test public void testSparseWideMemoryImport() throws Exception {
Path build=Path.of("build/objs/separate");
Files.createDirectories(build);
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java b/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java
index d6783380..0163de05 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/StringFormatTest.java
@@ -11,6 +11,10 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class StringFormatTest extends TestC {
+ @Test public void testSingleIntegerInterpolation() throws Exception {
+ runSYS("val main={ -> sys.io.p(\"%(7)\"); return 0; };","singleIntegerInterpolation","7",-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.
diff --git a/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java b/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java
index 28b6b0fb..fb1834fa 100644
--- a/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java
+++ b/chapter33/src/test/java/com/seaofnodes/simple/TypeTest.java
@@ -1,12 +1,47 @@
package com.seaofnodes.simple;
import com.seaofnodes.simple.type.*;
+import java.util.HashMap;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.assertSame;
public class TypeTest {
+ @Test public void testSingletonMemoryUpgradeEscapes() {
+ TypeStruct open = TypeStruct.open("class:UpgradeChild");
+ TypeMemPtr ptr = TypeMemPtr.make((byte)2,open,true);
+ TypeFunPtr callback = TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOT,11);
+ TypeStruct child = open.add(Field.make("self",ptr,7,true))
+ .add(Field.make("callback",callback,8,true))
+ .add(Field.make("value",TypeInteger.BOT,9,false)).close();
+ HashMap<String,Type> types = new HashMap<>();
+ types.put(child._name,child);
+ TypeMem initial = TypeMem.make(6,ptr,true,true,true,TypeSet.FULL,TypeSet.FULL);
+ TypeMem upgraded = (TypeMem)initial.upgradeType(types);
+ assertSame(child,((TypeMemPtr)upgraded._t)._obj);
+ assertSame(TypeSet.of(11),upgraded._escFs);
+ assertSame(TypeSet.of(7).with(8).with(9),upgraded._escAs);
+ assertSame(upgraded,upgraded.upgradeType(types));
+
+ // Only a final singleton class slot can replace its old escape bound.
+ // Aggregate memory and mutable/non-class slots retain prior escapes.
+ for( TypeMem other : new TypeMem[]{
+ TypeMem.make(6,ptr,true,true,false,TypeSet.FULL,TypeSet.FULL),
+ TypeMem.make(6,ptr,true,false,true,TypeSet.FULL,TypeSet.FULL),
+ TypeMem.make(6,ptr,false,true,true,TypeSet.FULL,TypeSet.FULL),
+ TypeMem.make(1,ptr,true,true,true,TypeSet.FULL,TypeSet.FULL)} ) {
+ TypeMem kept = (TypeMem)other.upgradeType(types);
+ assertSame(TypeSet.FULL,kept._escFs);
+ assertSame(TypeSet.FULL,kept._escAs);
+ }
+ TypeStruct opaque = TypeStruct.forward("ExternalUpgradeChild");
+ types.put(opaque._name,opaque);
+ TypeMem external = TypeMem.make(6,TypeMemPtr.make((byte)2,opaque,true),
+ true,true,true,TypeSet.FULL,TypeSet.FULL);
+ assertSame(external,external.upgradeType(types));
+ }
+
@Test public void testFinalPointerCycles() {
TypeStruct cycle = TypeStruct.open("FinalPointerCycle");
Assert.assertFalse(cycle.isFinal());