diff options
Diffstat (limited to 'chapter33/src/main')
25 files changed, 316 insertions, 48 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 4b0e7de4..b9e56823 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); @@ -362,17 +360,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 +541,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 +552,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 +614,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/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..95eb46a6 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java @@ -200,10 +200,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() ) { @@ -235,6 +235,10 @@ abstract public class Opto { count++; Type oval = n._type, nval = n.compute(); if( n instanceof CLInitNode init ) init.link(); + // A nonreturning 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(); // 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); 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/Serialize.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java index ec135149..2d52c9c3 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) { @@ -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. @@ -467,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 @@ -492,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/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/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..cb56c9b6 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java @@ -123,7 +123,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 +137,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 +154,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 +169,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 @@ -257,6 +259,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/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/FldOffNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java index e49162f4..93f2baf9 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() { 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..b0293718 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,12 +216,15 @@ 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 ) { 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..7c6d6b56 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java @@ -163,6 +163,15 @@ public class LoadNode extends MemOpNode { if( _alias == 1 ) return null; + // Whole-memory parameters lose individual alias types. Recover the + // class flag from every caller without moving a load across a call. + // SCCP must have finished discovering callers before we remove it. + if( "$init".equals(_name) && ptr._type instanceof TypeMemPtr clz && + TypeStruct.startsClzPrefix(clz._obj._name) && + CodeGen.CODE._phase.ordinal()>=CodeGen.Phase.IterPostOpto.ordinal() && + classInitialized(mem,new BitSet()) ) + return CodeGen.CODE.con(TypeInteger.TRUE); + Node slice = CLInitNode.slice(mem,_alias,this); if( slice!=mem ) { setDef(1,slice); return this; } @@ -230,6 +239,38 @@ public class LoadNode extends MemOpNode { return null; } + // A class flag has one global slot per alias. Unknown memory and cycles + // fail the proof; a cycle must not establish its own initialization. + private boolean classInitialized(Node mem, BitSet active) { + addDep(mem); + if( mem._type.isHigh() ) return true; + if( mem._type instanceof TypeMem tm && tm._alias==_alias && tm._t==TypeInteger.TRUE ) return true; + if( active.get(mem._nid) ) return false; + active.set(mem._nid); + boolean ready=false; + if( mem instanceof MemMergeNode merge ) + ready=classInitialized(merge.alias(_alias),active); + else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CLInitNode init ) { + addDep(init.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. 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/MemMergeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java index 03cf4d36..d97e6052 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java @@ -110,7 +110,9 @@ public class MemMergeNode extends Node { // Is this a single private instance memory? if( defmem._one ) { if( !(defmem._t instanceof TypeStruct ts) ) - return defmem; + // Stores can introduce references even when the default has + // none. An unknown shape must bound the shaped result below. + return defmem.escapes(defmem._t); // Perfect singleton memory, so all updates are parallel and // independent and stack. for( int i=2; i<nIns(); i++ ) { 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/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/StoreNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java index 204e0c4b..511afa4e 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java @@ -251,8 +251,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. 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/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..026a4018 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); |
