diff options
16 files changed, 194 insertions, 24 deletions
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 6bded23f..cbc8ec23 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); @@ -540,7 +538,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. @@ -551,8 +549,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; } // --------------------------- @@ -593,7 +611,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/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/Serialize.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java index 35c2eac0..2d52c9c3 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java @@ -132,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. @@ -473,6 +473,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 @@ -498,6 +504,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() ) { 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..9e5fc7ef 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java @@ -257,6 +257,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/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/FunNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FunNode.java index 772de7fe..122de0ce 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 ) { 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..8869243e 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,6 +61,7 @@ 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); + top.init(); MemMergeNode memout = new MemMergeNode(); memout.addDef(f); // placeholder for control memout.addDef(top); @@ -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/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/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/Chapter20Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java index 226425ca..008902c5 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(); } } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java b/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java index 999e518d..71b90f7f 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/ClassInitDependenciesTest.java @@ -27,6 +27,36 @@ import org.junit.runners.model.Statement; import static org.junit.Assert.*; public class ClassInitDependenciesTest { + @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-"); @@ -551,6 +581,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/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); |
