From d9a46e588fe09ed58e160778b0d8dcee62d4d0e4 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Mon, 30 Nov 2026 10:43:11 -0800 Subject: Checkpoint Allocation2 before separate-compilation redesign Replace the legacy allocation planner, deletion proof engine, and independent FunctionEffects pass with Allocation2 as the sole allocation-analysis phase. Keep one Site per optimized allocation/static object, per-site weak field facts, dependency-driven escape propagation, incoming-edge counts, and points-to dumps. Move the shared node WorkList into util. Normalize Never exits before allocation analysis and TypeCheck while preserving semantic nonreturning summaries. Keep internal class-init call dependencies out of global escapes, sharpen hidden private-memory defaults, refresh singleton constant escape sets after type closure, and publish field-local escape facts. Detach unloaded summary wrappers from scheduling roots. Retain declaration metadata and optimized return states in C0DA objects without legacy contracts. Keep qualified forward type names separate from expression member access, allow peepholes to return dead self, and retain the supporting regressions. Use integer types for symbolic field offsets and Opto-high uninitialized fields. Make Breakout's debounce helper private. Remove disabled escape implementations, obsolete null assertions, duplicate graphics compilation, survey runners/results, investigation transcripts, and source archives. Consolidate the selected ownership, lifetime, storage, deletion, and growing-array designs with their rationale/examples and academic references. Replace the obsolete Chapter33 handoff in the AI notes with current guidance. This is an unfinished analysis checkpoint. Imported pointer identities, transitive escapes, intrinsic calls, construction checks, and cofinite-summary universe rebasing still need work. Import loading order is unchanged. Validation: main/test compilation and git diff --check pass. Before/after make -k -j8 tests_nographics both report 825 executions and 78 failures, with unchanged extracted failure names; all lattice shards pass. Chapter33 retains its three failing deletion/imported-identity/transitive-escape regressions. --- .../com/seaofnodes/simple/codegen/Allocation.java | 1147 -------------------- .../com/seaofnodes/simple/codegen/Allocation2.java | 134 ++- .../com/seaofnodes/simple/codegen/ArrayDelete.java | 538 --------- .../com/seaofnodes/simple/codegen/CodeGen.java | 38 +- .../com/seaofnodes/simple/codegen/FinalizeIR.java | 2 +- .../seaofnodes/simple/codegen/FunctionEffects.java | 131 --- .../seaofnodes/simple/codegen/FunctionSummary.java | 7 +- .../simple/codegen/GlobalCodeMotion.java | 2 +- .../com/seaofnodes/simple/codegen/IterPeeps.java | 86 +- .../seaofnodes/simple/codegen/ListScheduler.java | 2 +- .../java/com/seaofnodes/simple/codegen/Opto.java | 2 +- .../com/seaofnodes/simple/codegen/Serialize.java | 42 +- .../com/seaofnodes/simple/codegen/TypeCheck.java | 7 - .../java/com/seaofnodes/simple/codegen/Unlink.java | 19 +- .../java/com/seaofnodes/simple/node/CFGNode.java | 14 +- .../com/seaofnodes/simple/node/EscapeNode.java | 43 +- .../com/seaofnodes/simple/node/FldOffNode.java | 2 +- .../java/com/seaofnodes/simple/node/FunNode.java | 15 +- .../seaofnodes/simple/node/GlobalEscapeNode.java | 13 +- .../com/seaofnodes/simple/node/InitViewNode.java | 2 +- .../com/seaofnodes/simple/node/KeepAliveNode.java | 2 +- .../java/com/seaofnodes/simple/node/LoadNode.java | 24 - .../java/com/seaofnodes/simple/node/LoopNode.java | 2 + .../com/seaofnodes/simple/node/MemMergeNode.java | 1 - .../java/com/seaofnodes/simple/node/NewNode.java | 11 +- .../com/seaofnodes/simple/node/ReturnNode.java | 1 + .../com/seaofnodes/simple/node/SummaryNode.java | 25 +- .../com/seaofnodes/simple/parser/Allocations.java | 9 +- .../com/seaofnodes/simple/parser/Functions.java | 4 +- .../com/seaofnodes/simple/parser/References.java | 34 +- .../java/com/seaofnodes/simple/parser/Types.java | 97 +- .../java/com/seaofnodes/simple/type/TypeMem.java | 15 +- .../com/seaofnodes/simple/type/TypeMemPtr.java | 2 +- .../com/seaofnodes/simple/type/TypeStruct.java | 5 +- .../java/com/seaofnodes/simple/util/WorkList.java | 78 ++ 35 files changed, 342 insertions(+), 2214 deletions(-) delete mode 100644 chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java delete mode 100644 chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java delete mode 100644 chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java create mode 100644 chapter33/src/main/java/com/seaofnodes/simple/util/WorkList.java (limited to 'chapter33/src/main/java') diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java deleted file mode 100644 index 2c0d4664..00000000 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation.java +++ /dev/null @@ -1,1147 +0,0 @@ -package com.seaofnodes.simple.codegen; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; -import com.seaofnodes.simple.util.SB; -import com.seaofnodes.simple.util.BAOS; -import com.seaofnodes.simple.parser.Parser; -import java.util.*; - -/** First allocation-lifetime experiment. Builds plans, not machine allocations. - * One DFS of the call DAG: discover callees on entry, compose their symbolic - * summaries on exit. No call-tree expansion, caller rewalk, or IR mutation. - * Within a summary, reference edges propagate destination requirements with a - * small worklist. A rejected summary is never a usable allocation plan. - */ -public final class Allocation { - private final Summary[] _summaries; - private final Summary _entrySummary; - private final ArrayList _postorder = new ArrayList<>(); - public final ArrayList _deletes = new ArrayList<>(); - - // Destination bits: result, static storage, Call/Parm input indices, then - // borrowed field paths. A child's storage need not share its holder's owner. - private static final int RESULT=0, STATIC=1; - - /** One abstract storage object. Imported allocations are distinct per call - * site; a parameter denotes borrowed storage, not an allocation to move. */ - public static final class Site { - public final NewNode _allocation; // null for borrowed/static storage or unloaded allocations - public final int _arg; // >=2: Parm index, -1: static, 0: fresh/path - public final String _name; - public final long _bytes; // snapshot before later IR rewrites - public final boolean _fresh; // also true for allocations in unloaded bodies - private final boolean _buddy; - public final BitSet _owners = new BitSet(); - public final HashMap> _fields = new HashMap<>(); - public Summary _frame; // activation creating this object - public Summary _scope; // scratch frame, null for an external destination - private CFGNode _birth; // allocation control, or importing call - private final ArrayList _destinations; - private final HashMap _loads = new HashMap<>(); - Site _base; // borrowed field origin, e.g. arg3.c - String _field; - private int _depth; - - private Site(Summary sum, NewNode allocation, int arg, String name) { - this(sum,allocation,arg,name, - allocation!=null && allocation.size()._type instanceof TypeInteger size && size.isConstant() ? size.value() : -1, - allocation!=null,allocation!=null && allocation._deletable); - } - private Site(Summary sum, NewNode allocation, int arg, String name, long bytes, boolean fresh, boolean buddy) { - _allocation=allocation; _arg=arg; _name=name; - _destinations=sum._destinations; - _bytes=bytes; _fresh=fresh; _buddy=buddy; - if( arg>=2 ) _owners.set(arg); - if( arg==-1 ) _owners.set(STATIC); - } - - public String destination() { - if( buddy() ) return "buddy"; - if( _owners.isEmpty() ) return _scope==null || _scope._loop==null ? "frame" : _scope.name()+" iteration"; - SB sb = new SB(); - if( _owners.get(RESULT) ) sb.p("result & "); - if( _owners.get(STATIC) ) sb.p("static & "); - ArrayList names = new ArrayList<>(); - for( int i=_owners.nextSetBit(2); i>=0; i=_owners.nextSetBit(i+1) ) - names.add(_destinations.get(i)); - Collections.sort(names); // Paths are discovered in arbitrary order. - for( String name : names ) sb.p(name).p(" & "); - return sb.unchar(3).toString(); - } - - public boolean buddy() { return _buddy; } - } - - /** Symbolic summary, with separate destinations for separate arguments. - * Object fields are weak updates: all stored references remain possible. - * Borrowed field paths describe incoming contents separately from stores. */ - - // An activation summary: a function or one loop iteration. Loops share their - // enclosing function's SSA/Site vocabulary, so composition needs no cloning - // or argument substitution. Calls substitute that vocabulary in compose(). - public static final class Summary { - public final FunNode _fun; // owning function, also for loop frames - public final LoopNode _loop; // null for a function activation - public Summary _parent; - public final ArrayList _frames = new ArrayList<>(); - public final ArrayList _sites = new ArrayList<>(); - // Ports map formal/output identity to its value. Loop Phis are entry - // and continuation ports; captured SSA values name themselves. Memory - // ports are included; their retention effects are summarized below. - public final IdentityHashMap _entry = new IdentityHashMap<>(); - public final IdentityHashMap _exit = new IdentityHashMap<>(); - public final IdentityHashMap _next = new IdentityHashMap<>(); - public final HashSet _returns = new HashSet<>(); - public final HashSet _retained = new HashSet<>(); - public final HashSet _continues = new HashSet<>(); - public final HashSet _scratch = new HashSet<>(); - public final ArrayList _consumes = new ArrayList<>(); - boolean _opaqueEffects; // raw/native effects absent from the field graph - private final HashSet _escapes = new HashSet<>(); - public String _reject; - private byte _state; // 0 pre/unseen, 1 mid/active DFS, 2 post/complete - private byte _ownershipState; - private boolean _ownershipCycle; - // All allocation-interesting Nodes; Calls, Stores, News, Ptr ops - private final ArrayList _nodes = new ArrayList<>(); - // Just the Calls - private final ArrayList _calls = new ArrayList<>(); - // Pointer expression -> possible storage objects, in this function's vocabulary. - private final IdentityHashMap< Node,HashSet> _values; - // Call -> returned storage after substituting actuals and closing effects. - private final IdentityHashMap> _results; - private final BitSet _resolved; - private final BitSet _raw; // Scalar expressions feeding lexical lifetime endpoints - private final IdentityHashMap _loops = new IdentityHashMap<>(); - private final ArrayList _destinations; - private Site _static; - private int _pathLimit; // own reads plus the path depths imported at calls - private boolean _changed; - - private Summary(FunNode fun) { - _fun=fun; _loop=null; - _values=new IdentityHashMap<>(); - _results=new IdentityHashMap<>(); - _resolved=new BitSet(); - _raw=new BitSet(); - _destinations=new ArrayList<>(List.of("result","static")); - _static=new Site(this,null,-1,"static"); - } - private Summary(Summary fun, LoopNode loop) { - _fun=fun._fun; _loop=loop; - _values=fun._values; _results=fun._results; _resolved=fun._resolved; - _raw=fun._raw; - _destinations=fun._destinations; _static=fun._static; - } - public String name() { return _loop!=null ? "loop#"+_loop._nid : _fun==null ? "saved contract" : _fun.label(); } - // Hit the end of summary findings with no errors. - public boolean supported() { return _state==2 && _reject==null; } - // Throw or return valid summary - public Summary requireSupported() { - if( !supported() ) throw new IllegalStateException("Allocation "+name()+": "+_reject); - return this; - } - // Collect first rejection - private void reject(String why) { if( _reject==null ) _reject=why; } - } - - public Allocation(CodeGen code) { - _summaries = new Summary[code._linker._len]; - Summary entry=null; - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && !fun._type.isHigh() ) { - Summary sum=new Summary(fun); - _summaries[fun.sig().fidx()] = sum; - if( code.entryClinitName().equals(fun._name) ) entry=sum; - } - _entrySummary=entry; - for( Summary sum : _summaries ) - if( sum!=null ) - visit(sum); - // Callees precede callers. Discharged requirements disappear; incoming - // ones become the caller's own contract. This is separate from placement. - for( Summary sum : _postorder ) ownership(sum); - } - - private void ownership(Summary sum) { - if( sum._ownershipState==2 ) return; - if( sum._ownershipState==1 ) { sum._ownershipCycle=true; return; } - sum._ownershipState=1; - for( CallNode call : sum._calls ) { - if( call.fptr()._type instanceof TypeFunPtr fp && !XInt.isHigh(fp.fidxs()) ) - for( int fidx=XInt.next(fp.fidxs(),0); fidx>=0; fidx=XInt.next(fp.fidxs(),fidx) ) { - Summary callee=fidx<_summaries.length ? _summaries[fidx] : null; - if( callee!=null ) { ownership(callee); sum._ownershipCycle |= callee._ownershipCycle; } - } - } - for( CallNode call : sum._calls ) { - if( Intrinsic.arrayDelete(call) && Intrinsic.arrayDeleteType(call.tfp()) && call.nargs()==1 ) - consume(sum,new ArrayDelete(this,sum._nodes,call,2)); - else if( call.fptr()._type instanceof TypeFunPtr fp && !XInt.isHigh(fp.fidxs()) ) - for( int fidx=XInt.next(fp.fidxs(),0); fidx>=0; fidx=XInt.next(fp.fidxs(),fidx) ) { - Summary callee=fidx<_summaries.length ? _summaries[fidx] : null; - if( callee!=null ) - for( ArrayDelete.Consume requirement : new ArrayList<>(callee._consumes) ) - consume(sum,new ArrayDelete(this,sum._nodes,call,requirement)); - } - } - sum._ownershipState=2; - } - - private void consume(Summary sum, ArrayDelete check) { - // Recursive SCC heads need the same entry/outgoing ownership boundary - // as loop heads. Their allocation graphs are not built yet; do not - // assume a consuming requirement also proves a unique outgoing field. - if( sum._ownershipCycle ) check._reject="recursive consuming contracts are not supported"; - _deletes.add(check); - if( check._reject==null && check._requirement!=null && !sum._consumes.contains(check._requirement) ) - sum._consumes.add(check._requirement); - } - - void checkOwnership() { - // A first-class callback type does not yet carry consuming paths. - // Do not let it erase a requirement established on a concrete function. - for( Summary sum : _postorder ) for( CallNode call : sum._calls ) { - TypeFunPtr target=call.fptr()._type instanceof TypeFunPtr fp ? fp : null; - int first=target!=null && target.nargs()>0 && target.arg(0)==TypePtr.PTR ? 3 : 2; - for( int i=first; i()) ) - throw Parser.error("Unknown call cannot verify ownership of deletable storage",call._loc); - } - } - } - - private static boolean deletableStorage(Type t, HashSet seen) { - if( !seen.add(t) || !(t instanceof TypeMemPtr ptr) ) return false; - if( ptr._del ) return true; - if( ptr._obj._fields!=null ) - for( Field field : ptr._obj._fields ) if( deletableStorage(field._t,seen) ) return true; - return false; - } - - public Summary summary(String name) { - for( Summary sum : _summaries ) - if( sum!=null && name.equals(sum._fun._name) ) return sum; - throw new IllegalArgumentException("No allocation summary for "+name); - } - - Summary summary(FunNode fun) { return _summaries[fun.sig().fidx()]; } - - // Boundary contracts contain symbolic storage, never graph node IDs or - // implementation frames. Site zero is static storage. Local scratch is - // omitted; only external destinations and their reference graph survive. - static void write(BAOS out, Summary sum) { - assert sum._state==2; - out.packed4(sum._consumes.size()); - for( ArrayDelete.Consume consume : sum._consumes ) { - out.packed4(consume.arg()); out.packed4(consume.path().size()); - for( String field : consume.path() ) out.packedS(field); - } - out.packed1(sum._opaqueEffects ? 1 : 0); - out.packedS(sum._reject==null ? "" : sum._reject); - if( !sum.supported() ) return; - out.packed4(sum._destinations.size()); - for( String name : sum._destinations ) out.packedS(name); - ArrayList sites=new ArrayList<>(); - HashMap ids=new HashMap<>(); - ids.put(sum._static,0); - sites.add(sum._static); - for( Site site : sum._sites ) - if( site!=sum._static && !site._owners.isEmpty() ) { - ids.put(site,sites.size()); sites.add(site); - } - // Include field/path dependencies even when they have no destination - // of their own. Assign IDs before writing so cycles need no recursion. - for( int i=0; i values : site._fields.values() ) - for( Site child : values ) if( !ids.containsKey(child) ) { - ids.put(child,sites.size()); sites.add(child); - } - } - out.packed4(sites.size()); - for( Site site : sites ) { - out.packed4(site._arg); out.packedS(site._name); - out.packed8(site._bytes); - out.packed1((site._fresh ? 1 : 0) | (site.buddy() ? 2 : 0)); - out.packed4(site._owners.cardinality()); - for( int bit=site._owners.nextSetBit(0); bit>=0; bit=site._owners.nextSetBit(bit+1) ) out.packed4(bit); - } - for( Site site : sites ) { - out.packed4(site._base==null ? -1 : ids.get(site._base)); - if( site._base!=null ) out.packedS(site._field); - out.packed4(site._depth); - out.packed4(site._fields.size()); - for( var field : site._fields.entrySet() ) { - out.packedS(field.getKey()); out.packed4(field.getValue().size()); - for( Site child : field.getValue() ) out.packed4(ids.get(child)); - } - } - out.packed4(sum._returns.size()); - for( Site site : sum._returns ) out.packed4(ids.get(site)); - } - - static Summary read(BAOS in) { - Summary sum=new Summary((FunNode)null); - sum._state=2; - int consumes=in.packed4(); - for( int i=0; i path=new ArrayList<>(); - for( int j=0; j=0 ) { - site._base=sum._sites.get(base); site._field=in.packedS(); - site._base._loads.put(site._field,site); - } - site._depth=in.packed4(); - int fields=in.packed4(); - for( int j=0; j values=new HashSet<>(); - for( int k=0; k children : site._fields.values() ) sum._retained.addAll(children); - return sum; - } - - public void requireSupported() { - for( Summary sum : _postorder ) - sum.requireSupported(); - } - - /** Analysis-only deletion checkpoint. No storage is freed. A proof about - * incoming storage also reports the unique-entry contract still required. */ - public ArrayDelete checkArrayDelete(CallNode call, int arg) { - for( Summary sum : _postorder ) - if( sum._calls.contains(call) ) return new ArrayDelete(this,sum._nodes,call,arg); - throw new IllegalArgumentException("Deletion checkpoint is not in an analyzed body"); - } - - // A deliberately narrow helper contract: pointer fields are not changed, - // and the result is scalar or forwards known arguments. Scalar element - // copies, including loops, qualify. Scalar results need only effects; - // reference results also require an allocation contract for their origins. - boolean arrayBorrow(CallNode call) { - // A nonreturning call contributes no retained references to its caller. - if( call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP ) return true; - if( nativeCall(call) ) return false; // No pointer-memory effect contract yet. - Summary sum=target(call); - if( sum==null || sum._fun._extern ) return false; - Type ret=sum._fun.ret().expr()._type; - if( !(ret instanceof TypeInteger || ret instanceof TypeFloat) && arrayResult(call)==null ) return false; - return noReferenceEffects(sum._fun); - } - - // Direct argument forwarding is enough for copy/identity helpers. Field - // paths and fresh return storage are serialized too, but their deletion - // proofs need richer memory-origin queries before allowing these borrows. - ArrayList arrayResult(CallNode call) { - Summary sum=target(call); - if( sum==null || !sum.supported() ) return null; - ArrayList args=new ArrayList<>(); - for( Site site : sum._returns ) { - if( site._arg<2 || site._arg>=call.nIns()-1 ) return null; - args.add(call.arg(site._arg)); - } - return args; - } - - // Repeated consumption also needs an exclusive outgoing slot. Consuming - // the entry value alone does not promise that: a helper could publish its - // replacement into a second field before returning. The existing boundary - // graph (including imported graphs) suffices for this narrow proof. - boolean arrayOwned(CallNode call, ArrayDelete.Consume consume) { - return arrayOwned(target(call),consume); - } - - private static boolean arrayOwned(Summary sum, ArrayDelete.Consume consume) { - if( sum==null || !sum.supported() || sum._opaqueEffects || consume.path().isEmpty() ) return false; - Site owner=null; - for( Site site : sum._sites ) if( site._arg==consume.arg() ) owner=site; - if( owner==null ) return false; - for( int i=0; i stored=owner._fields.get(field); - Site incoming=owner._loads.get(field); - if( stored!=null && !stored.isEmpty() ) { - if( stored.size()!=1 || incoming!=null && !stored.contains(incoming) ) return false; - owner=stored.iterator().next(); - } else owner=incoming; - if( owner==null ) return false; - } - String field=consume.path().getLast(); - HashSet values=new HashSet<>(); - Set stored=owner._fields.get(field); - if( stored!=null ) values.addAll(stored); - Site incoming=owner._loads.get(field); - if( incoming!=null ) values.add(incoming); - for( Site value : values ) { - if( value!=incoming && !value._fresh || sum._returns.contains(value) ) return false; - for( Site site : sum._sites ) for( var edge : site._fields.entrySet() ) - if( edge.getValue().contains(value) && (site!=owner || !edge.getKey().equals(field)) ) return false; - } - return true; - } - - boolean arrayBorrow(CLInitNode init) { - return init.bypass() || noReferenceEffects(CodeGen.CODE.link(init.cu())); - } - - private static boolean noReferenceEffects(FunNode fun) { - FunctionEffects effects=CodeGen.CODE._effects.get(fun); - return effects!=null && !effects._referenceWrites; - } - - private void visit(Summary sum) { - if( sum._state==2 ) return; // Post-order, done - // Mid-visit, so found a Call Graph cycle, i.e. recursion - if( sum._state==1 ) { - // Recursive SCC/mega-call work goes here; do not expand a call tree. - sum.reject("recursive call component"); - return; - } - // Was pre-order, now mid-order - sum._state=1; - if( sum._fun.summary()!=null && sum._fun.summary()._allocation!=null ) { - Summary contract=sum._fun.summary()._allocation; - sum._reject=contract._reject; - sum._destinations.clear(); sum._destinations.addAll(contract._destinations); - sum._static=contract._static; - sum._sites.addAll(contract._sites); - sum._returns.addAll(contract._returns); - sum._retained.addAll(contract._retained); - sum._consumes.addAll(contract._consumes); - sum._opaqueEffects=contract._opaqueEffects; - } else if( sum._fun._extern || sum._fun.summary()!=null ) { - sum.reject("opaque body: allocation contract unavailable"); - } else { - // Collection interesting function body and call sites - collect(sum); - for( Node n : sum._nodes ) - if( n instanceof PtrToIntNode || n instanceof CLInitNode init && !arrayBorrow(init) ) sum._opaqueEffects=true; - for( CallNode call : sum._calls ) { - if( nativeCall(call) ) { - if( !Intrinsic.pure(call) && !Intrinsic.arrayDelete(call) && - !(call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP) ) sum._opaqueEffects=true; - // Native code borrows its arguments for this call only. - // Returned storage still needs an explicit origin contract. - Type ret=call.tfp().ret(); - if( !(ret instanceof TypeInteger || ret instanceof TypeFloat) ) - sum.reject("native result storage has no allocation contract at call #"+call._nid); - continue; - } - Summary callee = target(call); - if( callee==null ) sum.reject("opaque or indirect call #"+call._nid); - else { - // Recursive walk Call Graph DAG - visit(callee); - sum._opaqueEffects |= callee._opaqueEffects; - // If some callee is rejected, so is this caller - if( callee._reject!=null ) - sum.reject("call #"+call._nid+" -> "+callee._fun.label()+": "+callee._reject); - } - } - if( sum._reject==null ) - build(sum); - } - // Postder - sum._state=2; - _postorder.add(sum); - } - - Summary target(CallNode call) { - if( !(call.fptr()._type instanceof TypeFunPtr fp) || !fp.isConstant() ) return null; - int idx=fp.fidx(); - return idx>=0 && idx<_summaries.length ? _summaries[idx] : null; - } - - // Unlike external(), this excludes unknown targets and mixed Simple/native - // target sets. Every possible target must obey the native borrowing rule. - private static boolean nativeCall(CallNode call) { - if( !(call.fptr()._type instanceof TypeFunPtr fp) || XInt.isHigh(fp.fidxs()) || fp.nfcns()==0 ) return false; - for( int idx=XInt.next(fp.fidxs(),-1); idx>=0; idx=XInt.next(fp.fidxs(),idx) ) - if( CodeGen.CODE.externFunc(idx)==null ) return false; - return true; - } - - // Follow control, memory, and references, not arithmetic/offset expressions. - // Find allocations at control anchors too: their only remaining use might - // be a scalar load or a raw address buried under arithmetic. Don't walk into - // other functions, so no following linked Calls or Parms. - private void collect(Summary sum) { - BitSet seen = new BitSet(); - ArrayDeque work = new ArrayDeque<>(); - // Start at both ends: zero-exit loops cannot be reached from Return. - work.push(sum._fun.ret()); - work.push(sum._fun); - // Repeat until entire function is walked - while( !work.isEmpty() ) { - Node n = work.pop(); - if( seen.get(n._nid) ) continue; // Been there, done that - seen.set(n._nid); - // Add to function body - sum._nodes.add(n); - if( n instanceof CFGNode cfg && !(cfg instanceof ReturnNode) && - (cfg==sum._fun || !cfg.isFunLeaf()) ) - for( Node use : cfg._outputs ) - if( use instanceof CFGNode next && !cfg.skip(next) ) work.push(next); - if( n instanceof CFGNode ) - for( Node use : n._outputs ) - if( use instanceof NewNode alloc && alloc.ctrl()==n || - use instanceof ParmNode parm && parm.fun()==sum._fun ) - work.push(use); - // Reference uses stay within this function; Parm call links and - // constant/global anchors are boundaries. In particular, find raw - // conversions without following their scalar arithmetic users. - if( !n.isFunLeaf() || n instanceof ParmNode ) - for( Node use : n._outputs ) - if( use instanceof PtrToIntNode || pointer(use) && !use.isFunLeaf() ) - work.push(use); - if( n.isFunLeaf() ) continue; - if( n instanceof CallNode call ) sum._calls.add(call); - if( n instanceof LoopNode loop ) sum._loops.put(loop,new Summary(sum,loop)); - - // CLInit accesses static state, not caller parameters. Its body is - // analyzed separately; stores publishing local objects to static - // state already give those objects the static destination. Do not - // mistake an own-class initialization guard for recursive calling. - if( n instanceof CallEndNode cend ) { work.push(cend.call()); continue; } - - // Walk selected edges. We can skip pure-data ops, but need to - // walk both control and memory at least. - for( Node in : n._inputs ) - if( in!=null && (in instanceof CFGNode || in.isMem() || - in._type instanceof TypeMem || pointer(in) || in instanceof NewNode) ) - work.push(in); - } - keepOrigins(sum,seen); - } - - // Follow the scope endpoint backwards, not all uses of an integer address. - // Memory round trips and wrapper calls need no provenance: the original - // conversion is kept here until its own lexical scope ends. - private static void keepOrigins(Summary sum, BitSet seen) { - ArrayDeque work=new ArrayDeque<>(); - for( Node n : sum._nodes ) if( n instanceof KeepAliveNode ) work.push(n.in(1)); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( pointer(n) || n instanceof ConstantNode || n instanceof CFGNode || - n instanceof LoadNode || n.isFunLeaf() || - n instanceof ProjNode || sum._raw.get(n._nid) ) continue; - sum._raw.set(n._nid); - if( !seen.get(n._nid) ) { seen.set(n._nid); sum._nodes.add(n); } - for( Node in : n._inputs ) if( in!=null ) work.push(in); - } - } - // Post-order work during the Call Graph visit - private void build(Summary sum) { - loopFrames(sum); - for( Node n : sum._nodes ) { - // Gather allocation sites - if( n instanceof NewNode alloc ) { - if( !alloc._deletable && (!(alloc.size()._type instanceof TypeInteger size) || !size.isConstant()) ) - sum.reject("variable-size allocation #"+alloc._nid); - Site site = new Site(sum,alloc,0,"new#"+alloc._nid+":"+alloc._ts._name); - site._birth=(CFGNode)alloc.ctrl(); - if( TypeStruct.startsClzPrefix(alloc._ts._name) ) site._owners.set(STATIC); - sum._sites.add(site); - sum._values.put(alloc,set(site)); - } - if( n instanceof ParmNode parm && pointer(parm) ) { - if( parm.fun()!=sum._fun ) sum.reject("foreign parameter #"+parm._nid); - while( sum._destinations.size()<=parm._idx ) - sum._destinations.add("arg"+sum._destinations.size()); - Site site = new Site(sum,null,parm._idx,"arg"+parm._idx+":"+parm.label()); - sum._sites.add(site); - sum._values.put(parm,set(site)); - } - if( n instanceof LoadNode && pointer(n) ) sum._pathLimit++; - } - // Import fresh storage once per call, even though its reference edges - // may need several local rounds. No repeated walk of a callee's IR. - IdentityHashMap>> imports=new IdentityHashMap<>(); - for( CallNode call : sum._calls ) { - if( nativeCall(call) ) continue; - Summary callee=target(call); - IdentityHashMap> map=new IdentityHashMap<>(); - imports.put(call,map); - sum._results.put(call,new HashSet<>()); - map.put(callee._static,set(sum._static)); - int depth=0; - for( Site site : callee._sites ) { - depth=Math.max(depth,site._depth); - if( site==callee._static ) continue; - HashSet values=new HashSet<>(); - if( site._fresh && !site._owners.isEmpty() ) { - Site copy=new Site(sum,site._allocation,0,"call#"+call._nid+"/"+site._name,site._bytes,true,site.buddy()); - copy._birth=call; - if( site._owners.get(STATIC) ) copy._owners.set(STATIC); - sum._sites.add(copy); - values.add(copy); - } - map.put(site,values); - } - sum._pathLimit+=depth; - } - - // Loads, stores, and call effects depend on each other. Solve their weak - // unions before assigning owners: caching an early empty load would lose - // a later-discovered store. Targets, fields, and call results grow - // monotonically, including cyclic loop Phis. Each expression is visited - // once per round; a cycle uses the targets discovered so far. - do { - sum._changed=false; - sum._resolved.clear(); - for( CallNode call : sum._calls ) if( !nativeCall(call) ) compose(sum,call,imports.get(call)); - for( Node n : sum._nodes ) { - if( pointer(n) || sum._raw.get(n._nid) ) refs(sum,n); - if( n instanceof StoreNode store && pointer(store.val()) ) - if( edge(refs(sum,store.ptr()),store._name,refs(sum,store.val())) ) sum._changed=true; - } - if( pointer(sum._fun.ret().expr()) && sum._returns.addAll(refs(sum,sum._fun.ret().expr())) ) sum._changed=true; - } while( sum._changed && sum._reject==null ); - for( Site site : sum._returns ) site._owners.set(RESULT); - if( !sum._static._fields.isEmpty() ) sum._sites.add(sum._static); - - // Local closure only: an object retained in a destination retains its - // referenced objects there too. Cyclic object graphs need no DAG rewalk. - ArrayDeque work=new ArrayDeque<>(sum._sites); - while( !work.isEmpty() ) { - Site src = work.pop(); - for( Set values : src._fields.values() ) - for( Site dst : values ) { - int before = dst._owners.cardinality(); - dst._owners.or(src._owners); // Union owners set - if( dst._owners.cardinality() != before ) work.push(dst); - } - } - if( sum._reject==null ) { - frameBoundaries(sum); - summarizeFrame(sum,sum,imports); - if( sum._reject==null ) placeFrames(sum); - } - // Bin packing goes here: fixed destinations become caller landing zones. - // Free-list work goes here: only after checking remaining usable aliases. - // Parallel growing tips go here: one owner may need several storage areas. - } - - // n has pointer type - private static boolean pointer(Node n) { - return n!=null && (n._type instanceof TypeMemPtr || n._type instanceof TypePtr); - } - - // LoopTree already establishes reducible nesting and each CFG's tightest - // containing loop. Allocation only supplies the corresponding frame summaries. - private static void loopFrames(Summary sum) { - for( Summary frame : sum._loops.values() ) { - CFGNode.LoopTree tree=frame._loop._ltree; - assert tree!=null && tree._head==frame._loop && tree._par!=null; - frame._parent=tree._par._head instanceof StartNode ? sum : sum._loops.get(tree._par._head); - assert frame._parent!=null : "Missing enclosing loop summary"; - frame._parent._frames.add(frame); - } - } - - // Everything reachable through stored references. Used both for backedge - // safety and for retaining a winner's entire object graph on loop exit. - private static HashSet reachable(HashSet roots) { - HashSet seen=new HashSet<>(roots); - ArrayDeque work=new ArrayDeque<>(roots); - while( !work.isEmpty() ) - for( HashSet children : work.pop()._fields.values() ) - for( Site child : children ) - if( seen.add(child) ) work.push(child); - return seen; - } - - // A store to storage not born in this iteration can carry its value into - // the next iteration. Stores within an iteration's private graph are fine; - // a surviving root will bring that entire graph into reachable() instead. - private static void retained(HashSet dst, HashSet src, - HashSet born, HashSet carried) { - for( Site base : dst ) - if( !born.contains(base) ) { carried.addAll(src); return; } - } - - // Memory reaching the backedge exposes stores that a pointer-Phi check alone - // misses, e.g. an array allocated before the loop collecting each candidate. - // Stop at this header: entry memory and exit-only stores do not execute on - // the repeated path. Weak updates deliberately do not kill earlier stores. - private static ArrayList backMemory(LoopNode loop) { - ArrayList nodes=new ArrayList<>(); - BitSet seen=new BitSet(); - ArrayDeque work=new ArrayDeque<>(); - for( Node use : loop._outputs ) - if( use instanceof PhiNode phi && phi.region()==loop && phi._type instanceof TypeMem ) - work.push(phi.in(2)); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( seen.get(n._nid) ) continue; - seen.set(n._nid); - if( n instanceof PhiNode phi && phi.region()==loop ) continue; - if( n instanceof ParmNode || n.isFunLeaf() ) continue; - nodes.add(n); - if( n instanceof ProjNode proj ) work.push(proj.in(0)); - else if( n instanceof CallEndNode end ) work.push(end.call()); - else for( Node in : n._inputs ) - if( in!=null && in._type instanceof TypeMem ) work.push(in); - } - return nodes; - } - - private static Summary enclosing(Summary sum, CFGNode ctrl) { - if( ctrl==null || ctrl._type.isHigh() ) return sum; - assert ctrl._ltree!=null : "Missing LoopTree for CFG #"+ctrl._nid; - if( ctrl._ltree._head instanceof StartNode ) return sum; - Summary frame=sum._loops.get(ctrl._ltree._head); - assert frame!=null : "Missing loop summary for CFG #"+ctrl._nid; - return frame; - } - - // Earliest control for a boundary value/use, without scheduling or changing - // the IR. New's pointer AND private-memory projections inherit its control. - // Floating scalar calculations can finish before returning from a frame; - // only their scalar result then crosses the boundary. - static CFGNode control(Node n, IdentityHashMap cache, BitSet active) { - if( n instanceof CFGNode cfg ) return cfg; - if( n instanceof PhiNode phi ) return phi.region(); - if( n.isFunLeaf() ) return null; - if( cache.containsKey(n) ) return cache.get(n); - if( active.get(n._nid) ) return CFGNode.safeCFG(n); - active.set(n._nid); - CFGNode ctrl=null; - for( Node in : n._inputs ) - if( in!=null ) ctrl=CFGNode.deepest(ctrl,control(in,cache,active)); - active.clear(n._nid); - cache.put(n,ctrl); - return ctrl; - } - - // Export a value from its producing activation to the common ancestor, - // then capture it down to the consuming activation. These explicit ports, - // not a later placement scan of uses, define what must survive cleanup. - private static void crossing(Node value, Summary from, Summary to) { - Summary common=from; - while( true ) { - Summary up=to; - while( up!=null && up!=common ) up=up._parent; - if( up!=null ) break; - common=common._parent; - } - for( Summary frame=from; frame!=common; frame=frame._parent ) frame._exit.put(value,value); - for( Summary frame=to; frame!=common; frame=frame._parent ) frame._entry.put(value,value); - } - - // Build the function/iteration interfaces in the existing SSA vocabulary. - // A loop's backedge is a return into its next activation, with Phi inputs - // supplying the arguments. Breaks/fallout export through the normal interface. - private void frameBoundaries(Summary sum) { - IdentityHashMap controls=new IdentityHashMap<>(); - BitSet active=new BitSet(); - for( Site site : sum._sites ) if( site._birth!=null ) { - site._frame=enclosing(sum,site._birth); - for( Summary frame=site._frame; frame!=sum; frame=frame._parent ) frame._sites.add(site); - } - for( Summary frame : sum._loops.values() ) - for( Node use : frame._loop._outputs ) - if( use instanceof PhiNode phi && phi.region()==frame._loop ) { - frame._entry.put(phi,phi.in(1)); - frame._next.put(phi,phi.in(2)); - } - sum._exit.put(sum._fun.ret(),sum._fun.ret().expr()); - sum._exit.put(sum._fun.ret().mem(),sum._fun.ret().mem()); - for( Node n : sum._nodes ) if( n instanceof ParmNode ) sum._entry.put(n,n); - if( sum._loops.isEmpty() ) return; - for( Node n : sum._nodes ) { - boundaryInputs(sum,n,controls,active); - // collect() skips scalar arithmetic. Merge Phis still define exit - // ports, including scalar results loaded from reclaimed scratch. - if( n instanceof CFGNode ) - for( Node use : n._outputs ) - if( use instanceof PhiNode phi && phi.region()==n ) boundaryInputs(sum,phi,controls,active); - } - // Scalar users were deliberately omitted by collect(). Their pointer - // operands still need boundary ports (e.g. a load after an outside call). - for( var value : sum._values.entrySet() ) { - Node n=value.getKey(); - if( !pointer(n) || n instanceof ConstantNode ) continue; - Summary producer=enclosing(sum,control(n,controls,active)); - for( Node use : n._outputs ) { - if( use.isFunLeaf() || use instanceof PhiNode phi && phi.region() instanceof LoopNode ) continue; - crossing(n,producer,enclosing(sum,control(use,controls,active))); - } - } - } - - private static void boundaryInputs(Summary sum, Node n, IdentityHashMap controls, BitSet active) { - if( n.isFunLeaf() || n instanceof PhiNode phi && phi.region() instanceof LoopNode ) return; - Summary consumer=enclosing(sum,control(n,controls,active)); - for( Node in : n._inputs ) { - if( in==null || in instanceof ConstantNode || in instanceof CFGNode ) continue; - // Ordinary integer users do not extend the borrowing scope. Only - // the endpoint and its expression carry raw-address obligations. - if( sum._raw.get(in._nid) && - !(n instanceof KeepAliveNode) && !sum._raw.get(n._nid) ) continue; - crossing(in,enclosing(sum,control(in,controls,active)),consumer); - } - } - - // The same summary closure for function returns and loop exits. Effects on - // incoming storage escape the frame even without a returned pointer. Loops - // additionally describe the continuation's values and memory effects. - private void summarizeFrame(Summary sum, Summary frame, - IdentityHashMap>> imports) { - frame._state=1; - for( Summary child : frame._frames ) { - summarizeFrame(sum,child,imports); - if( child._reject!=null ) frame.reject(child._reject); - } - HashSet born=new HashSet<>(); - for( Site site : frame._sites ) if( site._fresh ) born.add(site); - for( Node value : frame._exit.values() ) - if( frame._loop!=null || pointer(value) ) frame._returns.addAll(refs(sum,value)); - for( Site site : sum._sites ) - if( !born.contains(site) ) - for( HashSet children : site._fields.values() ) frame._retained.addAll(children); - frame._escapes.addAll(frame._returns); - frame._escapes.addAll(frame._retained); - // Static allocations retain their absolute lifetime across substitution. - for( Site site : born ) if( site._owners.get(STATIC) ) frame._escapes.add(site); - frame._escapes.addAll(reachable(frame._escapes)); - if( frame._loop!=null ) { - for( var port : frame._next.entrySet() ) - if( pointer(port.getKey()) || sum._raw.get(port.getKey()._nid) ) - frame._continues.addAll(refs(sum,port.getValue())); - for( Node n : backMemory(frame._loop) ) { - if( n instanceof StoreNode store && pointer(store.val()) ) - retained(refs(sum,store.ptr()),refs(sum,store.val()),born,frame._continues); - if( n instanceof CallNode call && !nativeCall(call) ) { - var map=imports.get(call); - for( Site site : target(call)._sites ) - for( HashSet children : site._fields.values() ) - for( Site child : children ) retained(map.get(site),map.get(child),born,frame._continues); - } - } - frame._continues.addAll(reachable(frame._continues)); - for( Site site : frame._continues ) - if( born.contains(site) && !site.buddy() ) { - frame.reject(frame.name()+" carries "+site._name+" across its backedge; collection/overlap destinations not implemented"); - break; - } - } - frame._state=2; - } - - // Function and iteration cleanup use the same rule. Promote escaped storage - // to the enclosing frame until its interface no longer exports that storage. - // A function's external results already have symbolic owner requirements. - // No RSP adjustment or actual reclamation is emitted by this planning pass. - private static void placeFrames(Summary sum) { - for( Site site : sum._sites ) if( site._frame!=null ) { - // Buddy blocks are independent allocations, released by .del(). - // Keep tracking their references, but never put them in stack cleanup. - if( site.buddy() ) { site._scope=site._frame; continue; } - Summary scope=site._frame; - while( scope!=null && scope._escapes.contains(site) ) scope=scope._parent; - site._scope=scope; - if( scope!=null ) scope._scratch.add(site); - } - } - - // One element Set of Site - private static HashSet set(Site site) { - HashSet set = new HashSet<>(); set.add(site); return set; - } - - private static boolean edge(HashSet dst, String field, HashSet src) { - if( src.isEmpty() ) return false; - boolean changed=false; - for( Site site : dst ) - changed |= site._fields.computeIfAbsent(field,k -> new HashSet<>()).addAll(src); - return changed; - } - - // Select a field's possible values, not its containing object's storage. - // Fresh objects have only the stores we see. Borrowed objects also have an - // incoming value, named by a path. That path is a separate borrowed Site, - // substituted against the actual object's fields at each call. - private HashSet field(Summary sum, HashSet bases, String name) { - HashSet values=new HashSet<>(); - for( Site base : bases ) { - if( !base._fresh ) { - Site child=base._loads.get(name); - if( child==null ) { - // Weak updates can invent an unbounded path even in straight - // line code: p.next=p.next.next. Stop at the body's finite - // read count rather than silently truncate possible origins. - // Memory-ordered field updates go here. - if( base._depth>=sum._pathLimit ) { - sum.reject("cyclic field-path expansion at "+base._name+"."+name); - continue; - } - String path=(base._arg>=2 ? "arg"+base._arg : base._name)+"."+name; - child=new Site(sum,null,0,path); - child._base=base; child._field=name; child._depth=base._depth+1; - if( base==sum._static || base._owners.get(STATIC) ) child._owners.set(STATIC); - else { - child._owners.set(sum._destinations.size()); - sum._destinations.add(path); - } - base._loads.put(name,child); - sum._sites.add(child); - sum._changed=true; - } - values.add(child); - } - Set stored=base._fields.get(name); - if( stored!=null ) values.addAll(stored); - } - return values; - } - - // Which storage objects can this pointer expression denote? This resolves - // pointer VALUE flow, not the fields reachable through the pointer. A Phi - // unions possible targets; casts/views preserve targets; a call result uses - // compose's caller-side targets; a load selects one field's targets. - // New/Parm targets were seeded by build. - // Example: refs(cond ? a : b) = {site(a), site(b)}. - // build() uses these sets to add Store edges, then propagates owner requirements - // through that separate object graph. Cyclic SSA values use the prior known - // targets; the next local round propagates any newly discovered ones. - private HashSet refs(Summary sum, Node n) { - if( n==null || !(pointer(n) || sum._raw.get(n._nid)) ) return new HashSet<>(); - HashSet old = sum._values.computeIfAbsent(n,k -> new HashSet<>()); - if( n instanceof ParmNode || sum._resolved.get(n._nid) ) return old; - sum._resolved.set(n._nid); - HashSet values = new HashSet<>(); - if( n instanceof ConstantNode ) { - // Zero/null carries no storage obligation. Other constant objects - // have static backing; field() handles their incoming contents. - if( n._type!=Type.NIL && n._type!=TypeInteger.ZERO ) values.add(sum._static); - } else if( n instanceof ProjNode proj && proj.in(0) instanceof NewNode alloc && proj._idx==0 ) { - Set sites = sum._values.get(alloc); - if( sites==null ) sum.reject("foreign allocation #"+alloc._nid); - else values.addAll(sites); - } else if( n instanceof ProjNode proj && proj.in(0) instanceof CallEndNode end && proj._idx==2 ) { - Set result=sum._results.get(end.call()); - if( result==null ) sum.reject("foreign call #"+end.call()._nid); - else values.addAll(result); - } else if( n instanceof LoadNode load ) { - values.addAll(field(sum,refs(sum,load.ptr()),load._name)); - } else if( n instanceof PhiNode phi && !(phi instanceof ParmNode) ) { - for( int i=1; i refs(actual), static -> static, - // borrowed field -> actual field targets. Fresh Sites were imported once by - // build, tagged with this call. Private callee scratch stays in the callee. - // A second call gets distinct Sites for its fresh allocations. - // Then translate field edges and returned targets through the same map. - // For helper(h) { h.c = new Thing; }, calling helper(a) adds a.c -> call/new. - // The map values are SETS because an actual may select several objects. - // Callee result/argument owner bits are relative to its signature; do not - // copy them into the caller. build's closure derives the caller's owners - // from the translated edges and uses of the result. Only static is absolute. - private void compose(Summary sum, CallNode call, IdentityHashMap> map) { - Summary callee=target(call); - // Grow substitutions before transferring edges. A later local round - // resolves forward references and aliasing actuals. For example, after - // f(a,b) { a.c=new Thing; return b.c; }, f(h,h) returns that new Thing too. - for( Site site : callee._sites ) { - if( site._arg>=2 ) { - if( site._arg>=call.nIns()-1 ) - sum.reject("missing argument at call #"+call._nid); - else if( map.get(site).addAll(refs(sum,call.arg(site._arg))) ) sum._changed=true; - } else if( site._base!=null ) - if( map.get(site).addAll(field(sum,map.get(site._base),site._field)) ) sum._changed=true; - } - // Retention effects exist even when the function returns a scalar. - for( Site site : callee._sites ) { - HashSet dst=map.get(site); - if( dst.isEmpty() ) continue; - for( var field : site._fields.entrySet() ) for( Site child : field.getValue() ) { - HashSet src=map.get(child); - if( src==null ) sum.reject("unmapped retained storage at call #"+call._nid); - else sum._changed |= edge(dst,field.getKey(),src); - } - } - for( Site site : callee._returns ) { - Set returned=map.get(site); - if( returned==null ) sum.reject("unmapped returned storage at call #"+call._nid); - else sum._changed |= sum._results.get(call).addAll(returned); - } - } - - // Printing has its own rooted traversal: reversing the analysis's entire - // forest would put disconnected bodies (e.g. inlined constructors) first. - private void printPostorder(Summary sum, BitSet seen, ArrayList post) { - if( sum==null || seen.get(sum._fun._nid) ) return; - seen.set(sum._fun._nid); - ArrayList calls=new ArrayList<>(sum._calls); - calls.sort(Comparator.comparingInt(n -> n._nid)); - for( CallNode call : calls ) printPostorder(target(call),seen,post); - post.add(sum); - } - - @Override public String toString() { - StringBuilder out = new StringBuilder("Allocation destinations (analysis only; no stack lowering)\n"); - BitSet seen=new BitSet(); - ArrayList order=new ArrayList<>(); - printPostorder(_entrySummary,seen,order); - Collections.reverse(order); - int reachable=order.size(); - ArrayList other=new ArrayList<>(); - for( Summary sum : _summaries ) printPostorder(sum,seen,other); - Collections.reverse(other); - order.addAll(other); - for( int i=0; i calls=new ArrayList<>(sum._calls); - calls.sort(Comparator.comparingInt(n -> n._nid)); - for( CallNode call : calls ) { - Summary callee=target(call); - out.append("| call#").append(call._nid).append(" -> ") - .append(callee==null ? nativeCall(call) ? "native (borrow; no retain)" : "?" : callee._fun.label()).append("\n"); - } - if( !sum.supported() ) { - out.append("`-- REJECT: ").append(sum._reject).append("\n"); - continue; // Do not display a partial plan as a safe placement. - } - printFrames(out,sum,"| "); - printStorage(out,sum,"| "); - printSites(out,"| cleanup on return -> ",sum._scratch); - printSites(out,"`-- return -> ",sum._returns," | "); - } - return out.toString(); - } - - // Show storage in its owning frame, which may enclose its allocation site. - // Borrowed/external destinations remain at function level. - private static void printStorage(StringBuilder out, Summary frame, String indent) { - ArrayList sites=new ArrayList<>(); - for( Site site : frame._sites ) - if( site._scope==frame || (frame._loop==null && site._scope==null) ) sites.add(site); - sites.sort(Comparator.comparing(s -> s._name)); - for( Site site : sites ) { - out.append(indent).append('[').append(site.destination()).append("] ").append(site._name); - if( site._fresh ) { - out.append(" ("); - if( site._bytes<0 ) out.append("dynamic size"); - else out.append(site._bytes).append(" bytes"); - out.append(')'); - } - if( site._frame!=null && site._frame._loop!=null && site._scope!=site._frame ) - out.append("; ").append(site._frame.name()).append(" winner"); - out.append('\n'); - ArrayList edges=new ArrayList<>(); - for( var field : site._fields.entrySet() ) for( Site child : field.getValue() ) - edges.add(indent+" ."+field.getKey()+" --> "+child._name+"\n"); - Collections.sort(edges); - for( String edge : edges ) out.append(edge); - } - } - - private static void printSites(StringBuilder out, String label, HashSet sites) { - printSites(out,label,sites,", "); - } - private static void printSites(StringBuilder out, String label, HashSet sites, String separator) { - out.append(label).append('{'); - ArrayList names=new ArrayList<>(); - for( Site site : sites ) names.add(site._name); - Collections.sort(names); - for( int i=0; i0 ) out.append(separator); - out.append(names.get(i)); - } - out.append("}\n"); - } - - private static void printPorts(StringBuilder out, String label, IdentityHashMap ports) { - out.append(label).append('{'); - ArrayList keys=new ArrayList<>(ports.keySet()); - keys.sort(Comparator.comparingInt(n -> n._nid)); - for( int i=0; i0 ) out.append(", "); - out.append(port.label()).append('#').append(port._nid); - if( port!=value ) out.append(" <- ").append(value.label()).append('#').append(value._nid); - } - out.append("}\n"); - } - - private static void printFrames(StringBuilder out, Summary parent, String indent) { - ArrayList frames=new ArrayList<>(parent._frames); - frames.sort(Comparator.comparingInt(s -> s._loop._nid)); - for( Summary frame : frames ) { - out.append(indent).append("+-- ").append(frame.name()).append(" frame; parent ").append(parent.name()).append('\n'); - printPorts(out,indent+"| entry -> ",frame._entry); - printPorts(out,indent+"| continue values -> ",frame._next); - printSites(out,indent+"| continue refs -> ",frame._continues); - printPorts(out,indent+"| exit values -> ",frame._exit); - printSites(out,indent+"| return refs -> ",frame._returns); - printSites(out,indent+"| retain -> ",frame._retained); - printStorage(out,frame,indent+"| "); - printFrames(out,frame,indent+"| "); - printSites(out,indent+"`-- cleanup on continue and return -> ",frame._scratch); - } - } -} diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java index 42490961..7a0fa4e2 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Allocation2.java @@ -4,7 +4,6 @@ import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.*; -import java.awt.*; import java.util.*; /** Allocation-site points-to analysis of the optimized graph. One object per @@ -13,14 +12,16 @@ import java.util.*; *

* Facts only grow. Reading a fact registers a dependency; changing it * schedules its readers. Loads/stores discover field dependencies as their - * bases grow. Unknown means arbitrary storage, not an empty points-to set. + * bases grow. Unknown denotes storage outside the local Site collection. + * Separate-compilation boundaries are incomplete; these facts must not yet + * authorize storage reclamation. */ public final class Allocation2 { private final CodeGen _code; // --------------------------------- // Things that can be pointed-at; a NewNode allocation or a static pre- - // initialized Constant (basically a NewNode moved to program genysis). + // initialized Constant (basically a NewNode moved to program startup). public static final class Site { public final Node _node; // NewNode or static ConstantNode // Each field has its own set of things it points to. This array is @@ -74,14 +75,6 @@ public final class Allocation2 { return field; } - // Transitively escape - void escapes( HashSet escapes ) { - if( _byFld != null ) - for( Points fld : _byFld ) - if( fld != null ) - throw Utils.TODO(); - } - @Override public String toString() { return str(new SB()).toString(); } public SB str( SB sb ) { TypeStruct ts = type(); @@ -137,7 +130,7 @@ public final class Allocation2 { // // Have a Point, merge the Point._unknown and all Point._sites. // Have a HashSet instead. - // Have a Type, filer by Type. + // Have a Type, filter by Type. // Have a WorkList, add changes if progress. // Merge Site into our existing Sites, return true if progress @@ -164,13 +157,20 @@ public final class Allocation2 { changed(work); } + // TODO: Track field growth after a site first escapes, including fields + // which are still empty. Visiting each site once is not a lifetime proof. boolean mergeTransitive( Points p ) { boolean progress = false; for( Site site : p._sites ) if( _sites.add(site) ) { progress = true; - if( site._byFld != null ) - throw Utils.TODO("transitive"); + if( site._byFld != null ) { + for( int i=0; i { - // FunNode fun = _code.link(init.cu()); - // if( fun==null || fun.summary()!=null ) effects(n,fun); - //} case CallEndNode cend -> cend(cend); + case SummaryNode sum -> escapeCallArgs(sum,sum.in(0),n); case ReturnNode ret -> { - if( reference(ret.expr()._type) ) points(n).merge(read(ret.expr(),n), _work); + if( reference(ret.expr()._type) ) { + Points result = read(ret.expr(),n); + points(n).merge(result, _work); + if( ret.fun().in(1) instanceof StartNode && + _escapes.mergeTransitive(result) ) + _escapes.changed(_work); + } } - //case PtrToIntNode raw -> { - // int[] writes=XInt.EMPTY; - // if( raw.in(1)._type instanceof TypeMemPtr ptr && ptr._obj._fields!=null ) { - // if( ptr._obj.isAry() ) writes=XInt.make(ptr._obj.field("[]")._alias); - // else for( Field field : ptr._obj._fields ) writes=XInt.make(writes,field._alias); - // } else writes=XInt.FULL; - // opaque(n,writes,"raw-address access"); - //} - //case NewNode alloc -> {} // Seeded before solving. case ConstantNode con -> { // Constant static memory already handled assert n._type instanceof TypeMemPtr; + // Constant non-constants are the default argument from an unknown + // caller; means any escaped allocation of the correct type might + // come in here + if( !n._type.isConstant() && points(n).merge(_escapes.addDep(n),((TypeMemPtr)n._type)._obj) ) + points(n).changed(_work); } case PhiNode phi -> { @@ -329,11 +323,13 @@ public final class Allocation2 { assert !phi.region().in(i)._type.isHigh(); if( phi.in(i)._type==Type.NIL ) continue; // null does not point to anything if( phi.in(i)._type.isHigh() ) continue; // Never-exit as a TOP here + // TODO: TypeCheck runs later; malformed programs can still + // supply non-reference actual arguments here. assert reference(phi.in(i)._type); progress |= dst.merge(read(phi.in(i),n)); // If getting from the unknown caller, might get all the escapes if( phi instanceof ParmNode && i==1 && phi.region().in(i) instanceof StartNode ) - progress |= dst.merge(_escapes.addDep(phi),phi._type); + progress |= dst.merge(_escapes.addDep(phi),((TypeMemPtr)phi._type)._obj); } if( progress ) dst.changed(_work); } @@ -365,7 +361,9 @@ public final class Allocation2 { case GuardNode guard -> forward(guard); case ConstructNode con -> forward(con); case InitViewNode view -> forward(view); - //case ConvertNode conv -> forward(conv ,nonNull); + case ConvertNode conv -> { + if( reference(conv.in(1)._type) ) forward(conv); + } case ArrayInitNode init -> points(n).merge(read(init.in(2),n),_work); default -> throw Utils.TODO("transfer: "+n.getClass().getSimpleName()); @@ -378,37 +376,58 @@ public final class Allocation2 { } private void cend(CallEndNode cend) { - assert reference(cend._type); // Only here for calls returning pointers CallNode call = cend.call(); if( Intrinsic.arrayDelete(call) || Intrinsic.pure(call) ) - throw Utils.TODO("untested");//return; + throw Utils.TODO("Allocation2 intrinsic call transfer"); if( !(call.fptr()._type instanceof TypeFunPtr fp) ) throw Utils.TODO("why weak tfp"); - assert !XInt.isHigh(fp.fidxs()); // Again, why any dead calls here? + // Calls unknown functions? + int firstArg = XInt.isHigh(fp.fidxs()) ? 2 : 0; if( !(cend._type instanceof TypeTuple state) ) throw Utils.TODO("why weak return"); Type result = state.ret(); - Points p = points(cend); + // Can be here for Calls returning non-references, but to escaping functions + Points p = reference(result) ? points(cend) : null; boolean progress = false; // Walk target functions for( int fidx = XInt.next(fp.fidxs(),0); fidx>=0; fidx = XInt.next(fp.fidxs(),fidx) ) { FunNode fun = _code.link(fidx); - if( fun==null || fun._extern || fun.summary()!=null ) { - // Might return some unknown allocation - progress |= p.merge(_escapes.addDep(cend), ((TypeMemPtr)result)._obj); - // All arguments escape as well - for( int i=3; i { - if( reference(n._type) || + if( reference(n._type) || n instanceof CallEndNode || n instanceof SummaryNode || (n instanceof StoreNode st && st.val()._type instanceof TypeMemPtr) ) _work.push(n); return null; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java deleted file mode 100644 index 1d22a3b6..00000000 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ArrayDelete.java +++ /dev/null @@ -1,538 +0,0 @@ -package com.seaofnodes.simple.codegen; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; -import com.seaofnodes.simple.util.SB; -import java.util.*; - -/** Demand-driven ownership at a deletion checkpoint. Field queries follow - * memory SSA. Call summaries supply may-stores, returned origins, and exclusive - * outgoing fields at that call's memory output, never at all calls at once. - * Runtime recycling remains separate from these proofs. */ -public final class ArrayDelete { - public record Consume(int arg, List path) { - public Consume { path=List.copyOf(path); } - @Override public String toString() { - SB sb=new SB().p("arg").p(arg); - for( String field : path ) sb.p('.').p(field); - return sb.toString(); - } - } - - // An origin is a local Node, an incoming base.field, a callee allocation, - // or a call's exclusive outgoing base.field. Interned inside this check. - // Node equality/hashing must be identity: Node.hashCode participates in GVN. - private record Ref(Node node, Ref base, String field, Allocation.Site site) { - @Override public int hashCode() { - return System.identityHashCode(node)+31*System.identityHashCode(base)+ - 17*System.identityHashCode(site)+Objects.hashCode(field); - } - @Override public boolean equals(Object o) { - return o instanceof Ref r && node==r.node && base==r.base && site==r.site && Objects.equals(field,r.field); - } - boolean fresh() { return node instanceof NewNode || node instanceof CallNode || node instanceof LoopNode && base!=null; } - } - private static final class Effects { - final IdentityHashMap> values=new IdentityHashMap<>(); - final HashMap>> stores=new HashMap<>(); - final HashSet returns=new HashSet<>(); - boolean building=true; - } - - public final CallNode _call; - public String _reject; - public Node _unique; - public Consume _requirement; - private Ref _owner; - private String _field; - private int _alias; - private final Allocation _allocation; - private final HashMap _origins=new HashMap<>(); - private final IdentityHashMap> _refs=new IdentityHashMap<>(); - private final IdentityHashMap _effects=new IdentityHashMap<>(); - private final IdentityHashMap> _owned=new IdentityHashMap<>(); - private final HashMap> _loopEntries=new HashMap<>(); - private final IdentityHashMap _borrows=new IdentityHashMap<>(); - private final BitSet _active=new BitSet(), _after=new BitSet(); - private final ArrayList _backedges=new ArrayList<>(); - private HashSet _old; - private HashSet _next; - private String _arrayType; - private boolean _deletable; - - ArrayDelete(Allocation allocation, List nodes, CallNode call, int arg) { - this(allocation,nodes,call,new Consume(arg,List.of()),false); - } - ArrayDelete(Allocation allocation, List nodes, CallNode call, Consume consume) { - this(allocation,nodes,call,consume,true); - } - private ArrayDelete(Allocation allocation, List nodes, CallNode call, Consume consume, boolean atCaller) { - _allocation=allocation; _call=call; - if( consume.arg()<2 || consume.arg()>=call.nIns()-1 ) throw new IllegalArgumentException("Not a call argument"); - Node value=call.arg(consume.arg()); - Type type=value._type; - HashSet roots=refs(value); - for( String name : consume.path() ) { - if( roots.size()!=1 || !(type instanceof TypeMemPtr ptr) ) { - reject("ambiguous consuming owner for "+consume); return; - } - Field field=ptr._obj.field(name); - if( field==null ) { reject("missing consuming field ."+name); return; } - _owner=roots.iterator().next(); _field=name; _alias=field._alias; - roots=contents(call.in(1),_owner,name,_alias); - // This checkpoint's next ownership version belongs to the next - // iteration; the entry and other preceding versions are checked here. - roots.remove(ref(call,_owner,name,null)); - type=field._t; - } - if( !(type instanceof TypeMemPtr ptr) || !ptr._obj.isAry() || ptr.nullable() ) { - reject("requires a non-null array"); return; - } - _arrayType=ptr._obj._name; - _deletable=ptr._del; - if( _reject!=null ) return; - if( roots.isEmpty() ) { reject("array has no known origin"); return; } - _old=new HashSet<>(roots); - ArrayDeque entries=new ArrayDeque<>(roots); - while( !entries.isEmpty() ) { - HashSet entry=_loopEntries.get(entries.pop()); - if( entry!=null ) for( Ref r : entry ) if( _old.add(r) ) entries.push(r); - } - for( Ref root : _old ) if( !root.fresh() ) { - Consume incoming=entryPath(root); - if( incoming==null ) { reject("cannot express incoming ownership as an argument field path"); return; } - if( _requirement!=null && !_requirement.equals(incoming) ) { - reject("array has multiple incoming ownership paths"); return; - } - _requirement=incoming; _unique=value; - } - after(call); - // Merges reached after this checkpoint exclude paths that bypassed it. - _refs.clear(); _effects.clear(); _owned.clear(); - - // A unique-entry requirement excludes aliases in the other arguments. - // Callees may rely on this; check the actuals at each consuming caller. - if( atCaller ) for( int i=2; i set(Ref r) { HashSet s=new HashSet<>(); s.add(r); return s; } - private static boolean pointer(Node n) { return n!=null && (n._type instanceof TypeMemPtr || n._type instanceof TypePtr); } - private Type type(Ref r) { - if( r.base!=null && type(r.base) instanceof TypeMemPtr p ) { - Field field=p._obj.field(r.field); - if( field!=null ) return field._t; - } - Type t=r.site!=null && r.site._allocation!=null ? r.site._allocation._type : r.node==null ? TypePtr.PTR : r.node._type; - return t instanceof TypeTuple tt && (r.node instanceof NewNode || r.site!=null && r.site._allocation!=null) ? tt.at(0) : t; - } - private int alias(Ref base, String name) { - if( type(base) instanceof TypeMemPtr p ) { - Field field=p._obj.field(name); - if( field!=null ) return field._alias; - } - return 1; // Unknown base: query the whole-memory slice conservatively. - } - private static Consume entryPath(Ref r) { - if( r.node instanceof ParmNode parm ) return new Consume(parm._idx,List.of()); - if( r.node!=null || r.base==null ) return null; - Consume parent=entryPath(r.base); - if( parent==null ) return null; - ArrayList path=new ArrayList<>(parent.path()); path.add(r.field); - return new Consume(parent.arg(),path); - } - private boolean contains(Node n) { - if( n._type instanceof TypeMemPtr p && p._obj!=TypeStruct.BOT && !p._obj._name.equals(_arrayType) ) return false; - return contains(refs(n)); - } - private boolean contains(HashSet refs) { - for( Ref old : _old ) if( mayAlias(refs,old) ) return true; - return false; - } - private boolean updated(HashSet refs) { - if( _next!=null ) for( Ref r : _next ) if( mayAlias(refs,r) ) return true; - return false; - } - private boolean mayAlias(HashSet refs, Ref base) { - for( Ref r : refs ) { - if( r==base ) return true; - if( r.fresh() || base.fresh() ) continue; - // Literal/static arrays cannot inhabit a deletable array slot. - if( _deletable && r.node instanceof ConstantNode && type(r) instanceof TypeMemPtr p && - p._obj.isAry() && !p._del ) continue; - // A separate array parameter is disjoint under the propagated - // unique-entry requirement, checked against actuals at callers. - // Do not infer that different owner paths are disjoint: two - // wrapper parameters might denote the same wrapper. - if( _requirement!=null && _old!=null && _old.contains(base) && - entryPath(base)!=null && r.node instanceof ParmNode ) continue; - if( type(r) instanceof TypeMemPtr x && type(base) instanceof TypeMemPtr y && - x._obj!=TypeStruct.BOT && y._obj!=TypeStruct.BOT && !x._obj._name.equals(y._obj._name) ) continue; - return true; - } - return false; - } - private boolean unborn(CFGNode effect) { - for( Ref root : _old ) { - CFGNode birth=root.node instanceof NewNode alloc ? (CFGNode)alloc.ctrl() : - root.node instanceof CallNode call ? call : null; - if( birth==null || effect==birth || !effect.dominates(birth,null) ) return false; - } - return true; - } - private HashSet refs(Node n) { - HashSet known=_refs.get(n); - if( known!=null ) return known; - HashSet result=new HashSet<>(); - if( _reject!=null ) return result; - if( _active.get(n._nid) ) { reject("cyclic reference at #"+n._nid); return result; } - _active.set(n._nid); - if( n._type==Type.NIL || n._type.isHigh() ) { - } else if( n instanceof NewNode || n instanceof ParmNode || n instanceof ConstantNode ) result.add(ref(n)); - else if( n instanceof ProjNode proj && proj._idx==0 && proj.in(0) instanceof NewNode ) result.add(ref(proj.in(0))); - else if( n instanceof GuardNode || n instanceof ReadOnlyNode || n instanceof ConstructNode || n instanceof InitViewNode ) - result.addAll(refs(n.in(1))); - else if( n instanceof ArrayInitNode ) result.addAll(refs(n.in(2))); - else if( n instanceof PhiNode phi ) { - for( int i=1; i bases=refs(load.ptr()); - if( bases.size()!=1 ) reject("ambiguous owner of field ."+load._name+" at #"+load._nid); - else result.addAll(contents(load.mem(),bases.iterator().next(),load._name,load._alias)); - } else if( n instanceof ProjNode proj && proj._idx==2 && proj.in(0) instanceof CallEndNode end ) { - // Forwarded arguments need no field substitution, including calls - // which also update memory. Their stores are checked separately. - ArrayList args=_allocation.arrayResult(end.call()); - if( args!=null ) for( Node arg : args ) result.addAll(refs(arg)); - else { - Effects effect=effects(end.call()); - if( effect==null ) reject("untracked returned reference at call #"+end.call()._nid); - else result.addAll(effect.returns); - } - } else reject("untracked reference #"+n._nid+" ("+n.label()+")"); - _active.clear(n._nid); _refs.put(n,result); - return result; - } - - // Unique entry -> unique exit is a strong ownership transfer, even when - // the implementation takes its no-growth path. May-stores remain weak. - private HashSet owned(CallNode call) { - HashSet slots=_owned.get(call); - if( slots!=null ) return slots; - slots=new HashSet<>(); _owned.put(call,slots); - Allocation.Summary sum=_allocation.target(call); - if( sum!=null ) for( Consume consume : sum._consumes ) - if( _allocation.arrayOwned(call,consume) ) { - HashSet bases=refs(call.arg(consume.arg())); - for( int i=0; i next=new HashSet<>(); - for( Ref base : bases ) next.addAll(contents(call.in(1),base,field,alias(base,field))); - bases=next; - } - if( bases.size()==1 ) slots.add(ref(null,bases.iterator().next(),consume.path().getLast(),null)); - } - return slots; - } - - private HashSet substitute(CallNode call, Allocation.Site site, Effects effect) { - HashSet known=effect.values.get(site); - if( known!=null ) return known; - HashSet values=new HashSet<>(); effect.values.put(site,values); - if( site._arg>=2 ) values.addAll(refs(call.arg(site._arg))); - else if( site._arg==-1 ) values.add(ref(CodeGen.CODE._start)); - else if( site._fresh ) values.add(ref(call,null,null,site)); - else if( site._base!=null ) - for( Ref base : substitute(call,site._base,effect) ) - values.addAll(contents(call.in(1),base,site._field,alias(base,site._field))); - else reject("unmapped call storage at #"+call._nid); - return values; - } - - private Effects effects(CallNode call) { - Effects known=_effects.get(call); - if( known!=null ) { - if( known.building ) { reject("cyclic call-field effects at #"+call._nid); return null; } - return known; - } - Allocation.Summary sum=_allocation.target(call); - if( sum==null || !sum.supported() || sum._opaqueEffects || sum._fun._extern ) return null; - Effects effect=new Effects(); _effects.put(call,effect); - HashSet owned=owned(call); - for( Allocation.Site site : sum._sites ) if( !site._fields.isEmpty() ) - for( Ref base : substitute(call,site,effect) ) for( var field : site._fields.entrySet() ) { - HashSet values=effect.stores.computeIfAbsent(base,k -> new HashMap<>()) - .computeIfAbsent(field.getKey(),k -> new HashSet<>()); - if( owned.contains(ref(null,base,field.getKey(),null)) ) values.add(ref(call,base,field.getKey(),null)); - else for( Allocation.Site value : field.getValue() ) values.addAll(substitute(call,value,effect)); - } - for( Allocation.Site site : sum._returns ) effect.returns.addAll(substitute(call,site,effect)); - effect.building=false; - return effect; - } - - private HashSet contents(Node mem, Ref base, String field, int alias) { - return contents(mem,base,field,alias,new BitSet()); - } - private HashSet contents(Node mem, Ref base, String field, int alias, BitSet seen) { - HashSet result=new HashSet<>(); - if( _reject!=null || mem._type.isHigh() || seen.get(mem._nid) ) return result; - // A field query is reachability through memory definitions, with strong - // stores cutting edges. A loop revisit adds no new reachable definition. - seen.set(mem._nid); - if( mem instanceof MemMergeNode merge ) { - if( alias==1 ) { - for( Node slice : merge._inputs ) if( slice!=null ) result.addAll(contents(slice,base,field,alias,seen)); - } else { - Node slice=merge.explicitAlias(alias); - result.addAll(contents(slice==null ? merge.in(1) : slice,base,field,alias,seen)); - } - } else if( mem instanceof StoreNode st ) { - HashSet bases=refs(st.ptr()); - boolean same=(st._alias==alias || st._alias==1 || alias==1) && st._name.equals(field); - boolean exact=same && bases.size()==1 && bases.contains(base); - if( same && mayAlias(bases,base) ) { - if( "[]".equals(field) ) reject("array-element ownership needs an index proof"); - else result.addAll(refs(st.val())); - } - if( !exact ) result.addAll(contents(st.mem(),base,field,alias,seen)); - } else if( mem instanceof EscapeNode esc ) { - HashSet bases=refs(esc.self()); - boolean same=esc.fld()._alias==alias || alias==1; - if( same && mayAlias(bases,base) ) result.addAll(contents(esc.priv(),base,field,alias,seen)); - if( !same || bases.size()!=1 || !bases.contains(base) ) result.addAll(contents(esc.pub(),base,field,alias,seen)); - } else if( mem instanceof PhiNode phi && !(mem instanceof ParmNode) ) { - if( phi.region() instanceof LoopNode loop && inside(_call,loop) && base==_owner && - field.equals(_field) && alias==_alias && type(ref(null,base,field,null)) instanceof TypeMemPtr p && p._obj.isAry() ) { - // A loop header is an ownership boundary, just like a call. - // Keep its entry version distinct from calls on the backedge. - Ref entry=ref(loop,base,field,null); - if( !_loopEntries.containsKey(entry) ) { - _loopEntries.put(entry,new HashSet<>()); - _loopEntries.get(entry).addAll(contents(phi.in(1),base,field,alias,seen)); - } - result.add(entry); - } else for( int i=1; i values=store.getValue().get(field); - if( values!=null ) result.addAll(values); - } - result.addAll(contents(call.in(1),base,field,alias,seen)); - } - } - } else if( mem instanceof ProjNode proj && proj.in(0) instanceof NewNode ) { - } else if( mem instanceof ProjNode proj && proj.in(0) instanceof CLInitNode init && _allocation.arrayBorrow(init) ) { - result.addAll(contents(init.mem(),base,field,alias,seen)); - } else if( mem instanceof ParmNode || mem instanceof ConstantNode || mem instanceof ProjNode proj && proj.in(0) instanceof StartNode ) { - if( !base.fresh() ) result.add(ref(null,base,field,null)); - } else reject("unknown memory #"+mem._nid+" ("+mem.getClass().getSimpleName()+") for ."+field); - return result; - } - - private boolean liveInput(PhiNode phi, int i) { - Node ctrl=phi.region().in(i); - return !ctrl._type.isHigh() && (!_after.get(phi.region()._nid) || _after.get(ctrl._nid)); - } - private void slot(Ref base, String field) { - if( base==_owner && field.equals(_field) ) return; - if( contains(contents(_call.in(1),base,field,alias(base,field))) ) - reject("field ."+field+" still holds the array at deletion"); - } - private boolean borrow(CallNode call) { - Boolean known=_borrows.get(call); - if( known!=null ) return known; - boolean result=Intrinsic.arrayDelete(call) || _allocation.arrayBorrow(call); - _borrows.put(call,result); return result; - } - private static String target(CallNode call) { - return call.fptr()._type instanceof TypeFunPtr fp && fp.isConstant() ? CodeGen.CODE.funcName(fp.fidx()) : "indirect"; - } - private void use(Node value, Node use) { - if( use==null ) { reject("unclassified kept reference #"+value._nid); return; } - if( use==_call ) return; - if( use instanceof PtrToIntNode ) { reject("raw-address borrow of the array at #"+use._nid); return; } - if( use instanceof CallNode call ) { - if( later(call) ) reject("call #"+call._nid+" uses the array after deletion"); - else if( !borrow(call) && effects(call)==null ) reject("call #"+call._nid+" has no borrowing-only contract"); - return; - } - if( use instanceof StoreNode store && store.val()==value ) return; - if( use instanceof EscapeNode || use instanceof NewNode || use instanceof ArrayInitNode ) return; - if( pointer(use) && (use instanceof PhiNode || use instanceof GuardNode || use instanceof ReadOnlyNode || - use instanceof ConstructNode || use instanceof InitViewNode) ) return; - if( use.isFunLeaf() && !(use instanceof ReturnNode) ) return; - if( later(use) ) reject("use #"+use._nid+" ("+use.label()+") survives deletion"); - } - - private void after(CallNode call) { - if( call.cend()==null ) { reject("checkpoint has no continuation"); return; } - ArrayDeque work=new ArrayDeque<>(); - work.push(call.cend()); - while( !work.isEmpty() ) { - CFGNode n=work.pop(); - if( _after.get(n._nid) || n._type.isHigh() ) continue; - _after.set(n._nid); - if( n instanceof ReturnNode ) continue; - for( Node use : n._outputs ) - if( use instanceof CFGNode next && !n.skip(next) ) { - if( next instanceof LoopNode loop && n==loop.back() && inside(call,loop) ) { - if( !_backedges.contains(loop) ) _backedges.add(loop); - } else work.push(next); - } - } - assert !_after.get(call._nid); - } - - private static boolean inside(CFGNode ctrl, LoopNode loop) { - for( CFGNode.LoopTree tree=ctrl._ltree; tree!=null; tree=tree._par ) - if( tree._head==loop ) return true; - return false; - } - - // The backedge is a call to the next iteration. The wrapper passes its - // current field, not a saved copy of its old field. Check explicit Phi - // arguments and invariant references used again, as well as stored copies - // of the replacement. This last check is deliberately conservative: a - // later iteration might kill a stored alias before growing, but we do not - // yet infer that ordering as part of an iteration's entry contract. - private void backedges(List nodes) { - IdentityHashMap controls=new IdentityHashMap<>(); - BitSet active=new BitSet(); - for( LoopNode loop : _backedges ) { - _next=new HashSet<>(); - if( _owner!=null ) for( Node use : loop._outputs ) - if( use instanceof PhiNode phi && phi.region()==loop && phi._type instanceof TypeMem mem && - (mem._alias==_alias || mem._alias==1) ) - _next.addAll(contents(phi.in(2),_owner,_field,_alias)); - // Include eventual exits as well as the next body. An invariant - // saved pointer returned after the loop also crosses this boundary. - BitSet next=new BitSet(); - ArrayDeque work=new ArrayDeque<>(); - work.push(loop); - while( !work.isEmpty() ) { - CFGNode ctrl=work.pop(); - if( next.get(ctrl._nid) || ctrl._type.isHigh() ) continue; - next.set(ctrl._nid); - if( ctrl instanceof ReturnNode ) continue; - for( Node use : ctrl._outputs ) - if( use instanceof CFGNode cfg && !ctrl.skip(cfg) ) work.push(cfg); - } - for( Node n : nodes ) { - if( _reject!=null ) return; - // A helper after grow can retain the replacement through the - // wrapper. That effect precedes the NEXT grow, even though it - // does not precede this iteration's checkpoint. - if( n instanceof CallNode call && call!=_call && later(call) && inside(call,loop) && !borrow(call) ) { - Effects effect=effects(call); - if( effect==null ) reject("call #"+call._nid+" has unknown reference effects across deletion backedge"); - else for( var base : effect.stores.entrySet() ) for( var field : base.getValue().entrySet() ) - if( updated(field.getValue()) && !(base.getKey()==_owner && field.getKey().equals(_field)) ) - reject("replacement array alias stored across deletion backedge at call #"+call._nid); - } - if( n instanceof PhiNode phi && phi.region()==loop && pointer(phi) ) { - HashSet carried=refs(phi.in(2)); - if( contains(phi.in(2)) || updated(carried) ) - reject("array reference crosses deletion backedge at Phi #"+phi._nid); - } - if( n instanceof StoreNode st && pointer(st.val()) && updated(refs(st.val())) ) { - CFGNode ctrl=Allocation.control(st,controls,active); - if( ctrl!=null && inside(ctrl,loop) && - !(refs(st.ptr()).equals(set(_owner)) && st._name.equals(_field)) ) - reject("replacement array alias stored across deletion backedge at #"+st._nid); - } - if( !pointer(n) || !contains(n) ) continue; - CFGNode birth=Allocation.control(n,controls,active); - if( birth!=null && next.get(birth._nid) ) continue; - for( Node use : n._outputs ) { - if( use==null || use.isFunLeaf() ) continue; - CFGNode ctrl=Allocation.control(use,controls,active); - if( ctrl!=null && next.get(ctrl._nid) ) - reject("array reference reused across deletion backedge at #"+use._nid); - } - } - } - _next=null; - } - - // Follow data/memory definitions to their controls. A floating load on - // pre-delete memory may run before delete; a pointer returned afterwards - // is itself a post-delete use. No scheduling or graph mutation is needed. - private boolean later(Node node) { - BitSet seen=new BitSet(); - ArrayDeque work=new ArrayDeque<>(); - work.push(node); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( seen.get(n._nid) ) continue; - seen.set(n._nid); - if( n instanceof CFGNode ) { - if( _after.get(n._nid) ) return true; - continue; - } - if( n instanceof PhiNode phi ) { work.push(phi.region()); continue; } - if( n.isFunLeaf() ) continue; - for( Node in : n._inputs ) if( in!=null ) work.push(in); - } - return false; - } - - @Override public String toString() { - SB sb=new SB().p("delete at call #").p(_call._nid).p(": "); - if( _reject!=null ) return sb.p("REJECT: ").p(_reject).toString(); - if( _unique!=null ) sb.p("requires unique entry ").p(_requirement.toString()).p("; "); - return sb.p("no surviving array access").toString(); - } -} diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java index 302f1491..0585f888 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java @@ -29,7 +29,7 @@ public class CodeGen { IterPostOpto, // Peepholes and inlining using SCCP results FinalizeIR, // Field layout, offset cleanup, function/CU roots LoopTree, // Containing loops for allocation analysis - Allocation, // Symbolic allocation destinations; analysis only + Allocation2, // Allocation-site points-to analysis TypeCheck, // Last check for bad programs Serialize, // Save ideal IR, including opaque class initialization Lower, // Expand checked class initialization to ordinary IR @@ -200,7 +200,7 @@ public class CodeGen { // Field layouts; field symbols become constant offsets step(target, Phase.FinalizeIR, this::finalizeIR, dump); step(target, Phase.LoopTree, this::loopTree, dump); - step(target, Phase.Allocation, this::allocation, dump); + step(target, Phase.Allocation2, this::allocation2, dump); // Final error check - bad programs fail here step(target, Phase.TypeCheck, this::typeCheck, dump); // Save reloadable ideal IR for a later seperate compilation @@ -432,9 +432,6 @@ public class CodeGen { public CodeGen opto() { return phase(Phase.Opto, _phase==Phase.Iter, () -> Opto.opto(this)); } public CodeGen iterPostOpto() { return phase(Phase.IterPostOpto, _phase==Phase.Opto, () -> { - // The call graph is settled. Peepholes can now ask which aliases a - // call preserves; later inlining only removes possible effects. - _effects=FunctionEffects.analyze(this); _iter.iterate(this); }); } @@ -528,21 +525,19 @@ public class CodeGen { // --------------------------- // Last check for bad programs - public Allocation _allocation; - public IdentityHashMap _effects; - public CodeGen allocation() { + public Allocation2 _allocation2; + public CodeGen typeCheck() { + if( _phase==Phase.FinalizeIR || _phase==Phase.LoopTree ) allocation2(); + return phase(Phase.TypeCheck, _phase==Phase.Allocation2, () -> TypeCheck.run(this)); + } + public CodeGen allocation2() { if( _phase==Phase.FinalizeIR ) loopTree(); - return phase(Phase.Allocation, _phase==Phase.LoopTree, () -> { - _effects = FunctionEffects.analyze(this); - _allocation = new Allocation(this); - if( Boolean.getBoolean("simple.alloc.dump") ) System.out.print(_allocation); - if( Boolean.getBoolean("simple.alloc.check") ) _allocation.requireSupported(); + return phase(Phase.Allocation2, _phase==Phase.LoopTree, () -> { + _allocation2 = new Allocation2(this); + if( Boolean.getBoolean("simple.alloc2.dump") ) + System.out.print(_allocation2); }); } - public CodeGen typeCheck() { - if( _phase==Phase.FinalizeIR || _phase==Phase.LoopTree ) allocation(); - return phase(Phase.TypeCheck, _phase==Phase.Allocation, () -> TypeCheck.run(this)); - } // --------------------------- // TypeCheck queued surviving CLInits during its existing error walk. @@ -551,11 +546,10 @@ public class CodeGen { } // --------------------------- - // Build containing loops without changing control flow before TypeCheck - // and serialization. Scheduling adds exits to zero-exit loops later. + // Normalize loops, including synthetic exits, before allocation analysis. public CodeGen loopTree() { return phase(Phase.LoopTree, _phase==Phase.FinalizeIR, - () -> _start.buildLoopTree(_linker,_stop,false)); + () -> _start.buildLoopTree(_linker,_stop)); } // --------------------------- @@ -598,8 +592,8 @@ public class CodeGen { private void unlink(boolean removeImports) { phase(Phase.Unlink, (_phase==Phase.Lower || _phase==Phase.TypeCheck || _phase==Phase.Serialize), () -> { KeepAliveNode.erase(_start); - // Lower can change CFG membership. Rebuild for scheduling, now - // including synthetic exits for loops with no exits at all. + // Lower can change CFG membership. Rebuild for scheduling; + // already-normalized loops keep their existing synthetic exits. _start.rebuildLoopTree(_linker,_stop); _start.setDef(2,null); // Releases the compiler-only escape analysis. if( removeImports ) Unlink.run(this,true); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java index 69e0104d..bff0b0ba 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FinalizeIR.java @@ -3,7 +3,7 @@ package com.seaofnodes.simple.codegen; import com.seaofnodes.simple.node.*; import java.util.Arrays; -// Comnpute field layouts only after SCCP and its peepholes converge. +// Compute field layouts after SCCP settles. // Keep surviving functions rooted without introducing unknown callers. abstract class FinalizeIR { static void run(CodeGen code) { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java deleted file mode 100644 index 9094f635..00000000 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/FunctionEffects.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.seaofnodes.simple.codegen; - -import com.seaofnodes.simple.node.*; -import com.seaofnodes.simple.type.*; -import java.util.*; - -/** Effects introduced by a function, independent of its incoming memory. - * Scan each body once, then union effects along call edges to a fixed point. - * This includes recursion and paths which never reach Return. */ -public final class FunctionEffects { - public int[] _writes; - public boolean _referenceWrites; - public TypeMem _escapes; - private final ArrayList _callees = new ArrayList<>(); - - public FunctionEffects(int[] writes, boolean referenceWrites, TypeMem escapes) { - _writes=writes; _referenceWrites=referenceWrites; _escapes=escapes; - } - private FunctionEffects() { this(XInt.EMPTY,false,TypeMem.START); } - - public static IdentityHashMap analyze(CodeGen code) { - IdentityHashMap effects=new IdentityHashMap<>(); - for( FunNode fun : code._linker ) - if( fun!=null && !fun.isDead() && !fun._type.isHigh() ) { - FunctionEffects effect=fun.summary()==null ? new FunctionEffects() : fun.summary()._effects; - effects.put(fun,effect); - if( fun.summary()==null ) effect.collect(fun); - } - // Sets only grow. Recursive components need no special fallback and - // cannot accidentally prove themselves effect-free before convergence. - boolean changed; - do { - changed=false; - for( FunctionEffects effect : effects.values() ) - for( FunNode callee : effect._callees ) { - FunctionEffects child=effects.get(callee); - changed |= effect.merge(child); - } - } while( changed ); - return effects; - } - - private boolean merge(FunctionEffects other) { - int[] writes=other==null ? XInt.FULL : XInt.meet(_writes,other._writes); - boolean refs=other==null || _referenceWrites || other._referenceWrites; - TypeMem escapes=other==null ? TypeMem.BOT : _escapes.escapes(other._escapes); - boolean changed=writes!=_writes || refs!=_referenceWrites || escapes!=_escapes; - _writes=writes; _referenceWrites=refs; _escapes=escapes; - return changed; - } - - private void collect(FunNode fun) { - BitSet seen=new BitSet(); - ArrayDeque work=new ArrayDeque<>(); - work.push(fun); work.push(fun.ret()); - while( !work.isEmpty() ) { - Node n=work.pop(); - if( seen.get(n._nid) ) continue; - seen.set(n._nid); - if( n instanceof CFGNode cfg && !(cfg instanceof ReturnNode) && - (cfg==fun || !cfg.isFunLeaf()) ) - for( Node use : cfg._outputs ) - if( use instanceof CFGNode next && !cfg.skip(next) && !next._type.isHigh() ) work.push(next); - if( n.isFunLeaf() ) continue; - // Replacing the effect table can enable an alias-preservation peep - // even though no graph type changed. Wake its consumers explicitly. - if( n instanceof LoadNode load && "$init".equals(load._name) ) CodeGen.CODE.add(load); - // Raw addresses can hide a reference in an otherwise scalar store. - // Until raw effects have their own contract, they block ownership proofs. - if( n instanceof PtrToIntNode ) _referenceWrites=true; - if( n instanceof StoreNode st ) { - int alias=st._alias; - if( alias==1 && st.ptr()._type instanceof TypeMemPtr ptr ) { - Field field=ptr._obj.field(st._name); - if( field!=null ) alias=field._alias; - } - _writes=alias==1 ? XInt.FULL : XInt.make(_writes,alias); - if( reference(st.val()._type) ) { - _referenceWrites=true; - expose(st.val()); - } - } - if( n instanceof EscapeNode esc && !esc._borrow ) { - _writes=XInt.make(_writes,esc.fld()._alias); - _referenceWrites |= reference(esc.fld()._t); - } - if( n instanceof CLInitNode init && !init.bypass() ) { - FunNode target=CodeGen.CODE.link(init.cu()); - if( target==null ) merge(null); - else _callees.add(target); - } - if( n instanceof CallNode call ) call(call); - if( n instanceof CallEndNode end ) { work.push(end.call()); continue; } - // Memory walks find even unpinned Stores. Stop at incoming Parms, - // constants, and interprocedural return edges, not their cached types. - for( Node in : n._inputs ) if( in!=null ) work.push(in); - } - } - - private static boolean reference(Type t) { - return !(t instanceof TypeInteger || t instanceof TypeFloat) && !t.isHigh() && t!=Type.NIL; - } - - private void expose(Node value) { - // Incoming references are supplied at each imported call, not frozen - // into a library-wide set of possible callbacks. All reference arguments - // still conservatively escape when applying the summary. - if( value instanceof ParmNode parm && !(parm._idx==2 && parm.fun().isClz()) ) return; - _escapes=_escapes.escapesFrom(value._type); - } - - private void call(CallNode call) { - if( Intrinsic.pure(call) ) return; - // The terminating native has no returning memory effects. - boolean exits=call.cend()._type instanceof TypeTuple tt && tt.mem()==TypeMem.TOP; - TypeFunPtr fp=call.fptr()._type instanceof TypeFunPtr f ? f : null; - boolean unknown=fp==null || XInt.isHigh(fp.fidxs()); - boolean external=unknown; - if( !unknown ) - for( int idx=XInt.next(fp.fidxs(),0); idx>=0; idx=XInt.next(fp.fidxs(),idx) ) { - FunNode target=CodeGen.CODE.link(idx); - if( target==null ) external=true; - else _callees.add(target); - } - if( external && !exits ) { _writes=XInt.FULL; _referenceWrites=true; } - // Simple callees can retain parameters too. Using their actuals keeps - // this conservative without importing the caller's entire memory state. - int first=fp!=null && fp.nargs()>0 && fp.arg(0)==TypePtr.PTR ? 3 : 2; - for( int i=first; i { - - private Node[] _es; - private int _len; - private final BitSet _on; // Bit set if Node._nid is on WorkList - private final Random _R; // For randomizing pull from the WorkList - private final long _seed; - - /* Useful stat - how many nodes are processed in the post parse iterative opt */ - private long _totalWork = 0; - - public WorkList() { this(123); } - WorkList(long seed) { - _es = new Node[1]; - _len=0; - _on = new BitSet(); - _seed = seed; - _R = new Random(); - _R.setSeed(_seed); - } - - /** - * Pushes a Node on the WorkList, ensuring no duplicates - * If Node is null it will not be added. - */ - public E push( E x ) { - if( x==null ) return null; - int idx = x._nid; - if( !_on.get(idx) ) { - _on.set(idx); - if( _len==_es.length ) - _es = Arrays.copyOf(_es,_len<<1); - _es[_len++] = x; - _totalWork++; - } - return x; - } - - public void addAll( Ary ary ) { - for( E n : ary ) - push(n); - } - public void addAll( E[] es ) { - for( E n : es ) - push(n); - } - - - /** - * True if Node is on the WorkList - */ - public boolean on( E x ) { return _on.get(x._nid); } - - /** - * Removes a random Node from the WorkList; null if WorkList is empty - */ - public E pop() { - if( _len == 0 ) return null; - int idx = _R.nextInt(_len); - E x = (E)_es[idx]; - _es[idx] = _es[--_len]; // Compress array - _es[_len] = null; - _on.clear(x._nid); - return x; - } - - public boolean isEmpty() { return _len==0; } - public void clear() { - Arrays.fill(_es,0,_len,null); - _len = 0; - _on.clear(); - _R.setSeed(_seed); - _totalWork = 0; - } - } } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java index f90d8d4e..cdd09c1a 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/ListScheduler.java @@ -1,6 +1,6 @@ package com.seaofnodes.simple.codegen; -import com.seaofnodes.simple.codegen.IterPeeps.WorkList; +import com.seaofnodes.simple.util.WorkList; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; 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 6d653835..4d6fb84d 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Opto.java @@ -2,7 +2,7 @@ package com.seaofnodes.simple.codegen; import com.seaofnodes.simple.node.*; import com.seaofnodes.simple.parser.Parser; -import com.seaofnodes.simple.codegen.IterPeeps.WorkList; +import com.seaofnodes.simple.util.WorkList; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.Ary; 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 c3ae2566..49c11e8c 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/Serialize.java @@ -104,15 +104,8 @@ public class Serialize { BAOS baos = new BAOS(); // A - Print the C0DE header; last byte is the version number. - // Format 2: gradual packed ints, UTF-8 strings, sparse MemMerge edges, - // and wider singleton function IDs. Reject old cached objects clearly. - // Format 3 retains lexical raw-address lifetime endpoints in bodies. - // Format 4 adds the deletable-array capability and allocation flag. - // Format 5 stores per-function effects, not the unit's incoming memory. - // Format 6 adds symbolic allocation contracts beside function effects. - // Format 7 carries consuming argument/field requirements. - // Format 8 marks effects not represented by the allocation field graph. - baos.write('C').write('0').write('D').write('8'); + // Format 10 removes the retired allocation/effect contracts. + baos.write('C').write('0').write('D').write('A'); // Count unique Types var types = new HashMap(); @@ -132,13 +125,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; - TypeMem mem = (TypeMem)state.mem(); - // Only effects introduced by this function and its callees. - // Incoming memory and unrelated exported functions are not effects. - TypeMem escaped = CodeGen.CODE._effects.get(fun)._escapes; - mem=mem.makeFrom(escaped._escFs,escaped._escAs); - state=state.makeFrom(1,mem); + TypeTuple state = fun.returnState(); summaries.put(fun,state); state.gather(types); } @@ -257,14 +244,6 @@ public class Serialize { int[] edges = _init._edgess[fun.sig().fidx()]; baos.packed4(edges==null ? 0 : edges.length); if( edges!=null ) for( int edge : edges ) baos.packed4(edge); - FunctionEffects effect=CodeGen.CODE._effects.get(fun); - baos.packed1(effect._referenceWrites ? 1 : 0); - if( effect._writes==XInt.FULL ) baos.packed4(-1); - else { - baos.packed4(XInt.bitCount(effect._writes)); - for( int alias=XInt.next(effect._writes,0); alias>=0; alias=XInt.next(effect._writes,alias) ) baos.packed4(alias); - } - Allocation.write(baos,CodeGen.CODE._allocation.summary(fun)); } // D - Write the nodes. Since this is expected to be the bulk of the @@ -349,7 +328,7 @@ public class Serialize { Type.TAGOFFS(); // A - Read a header - if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='8' ) + if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='A' ) throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file"); // B - Packed read of #strings, then strings @@ -382,7 +361,7 @@ public class Serialize { String[] strs = elf._strs; if( strs == null ) { // A - Read a header - if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != '8' ) + if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != 'A' ) throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" ); // B - Packed read of #strings, then strings @@ -458,12 +437,7 @@ public class Serialize { int size = bais.packed4(); int[] edges = new int[bais.packed4()]; for( int j = 0; j { if( n instanceof CallEndNode cend ) @@ -156,10 +156,17 @@ abstract class Unlink { }); } - private static void detachEmptyStart(StartCUNode start) { - // An unused unit can lose its outer Stop edge during optimization. - // Detach its empty wrapper from the scheduling root as well. - if( start.in(1) instanceof StopCUNode stop && stop.nIns()==0 ) start.setDef(0,null); + private static void detachUnscheduledStart(StartCUNode start) { + // Empty units and unloaded summaries have no body to schedule. An + // internal imported callee can retain its summary wrapper even after + // losing the outer Stop edge; detach its Start edge as well. + if( !(start.in(1) instanceof StopCUNode stop) ) return; + for( Node n : stop._inputs ) + if( ((ReturnNode)n).fun().summary()==null ) return; + start.setDef(0,null); + for( Node use : stop._outputs.asAry() ) + if( use instanceof StopNode outer ) + outer.delDef(outer._inputs.find(stop)); } private static void restoreRPC(FunNode fun) { 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 7cbf3f9b..ebcec43a 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CFGNode.java @@ -224,10 +224,6 @@ public abstract class CFGNode extends Node { } public void buildLoopTree( Ary funs, StopNode stop) { - buildLoopTree(funs,stop,true); - } - - public void buildLoopTree( Ary funs, StopNode stop, boolean forceExits) { _ltree = stop._ltree = CodeGen.CODE.XCTRL._ltree = new LoopTree((StartNode)this); Ary work = new Ary<>(FunNode.class); @@ -248,11 +244,11 @@ public abstract class CFGNode extends Node { } for( int i=0; i work, boolean forceExits ) { + int _bltWalk( int pre, FunNode fun, StopNode stop, BitSet post, Ary work ) { // Pre-walked? if( _pre!=0 ) return pre; _pre = pre++; @@ -274,7 +270,7 @@ public abstract class CFGNode extends Node { if( skip( usecfg ) ) { if( usecfg._pre==0 && usecfg instanceof FunNode fun2 && fun2.summary()==null ) work.add( fun2 ); } else - pre = usecfg._bltWalk( pre, use instanceof FunNode fuse ? fuse : fun, stop, post, work,forceExits ); + pre = usecfg._bltWalk( pre, use instanceof FunNode fuse ? fuse : fun, stop, post, work ); } // Post-order work: find innermost loop @@ -298,9 +294,7 @@ public abstract class CFGNode extends Node { if( ltree._par == null ) { // This loop never had an If test choose to take its // exit, i.e. it is a no-exit infinite loop. - // Analysis needs its nesting, but a synthetic exit - // must not change nonreturning summaries in .simple. - if( forceExits ) ltree._head.forceExit(fun,stop); + ltree._head.forceExit(fun,stop); ltree._par = fun._ltree; } ltree = ltree._par; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java index a8a6151c..c7dcb128 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/EscapeNode.java @@ -66,8 +66,8 @@ public class EscapeNode extends TypeNode { 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( 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; @@ -83,24 +83,31 @@ public class EscapeNode extends TypeNode { assert !(mpub._t instanceof TypeStruct); // Never expect this, but if it starts to happen, need to optimize Type tpub = mpub._t; + // A partially complete object + if( _borrow ) { + Type bound = fld._t; + if( bound instanceof TypeMemPtr ptr && TypeMemPtr.mayBePartial(tpriv) ) + bound = ptr.withPartial(true).partialBound(); + // 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 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. + return TypeMem.make(fld._alias,t,false,false,false,mpub._escFs,mpub._escAs); + } + // 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); - int[] fidxes = XInt.meet(mpriv._escFs, mpub._escFs); - int[] aliases = XInt.meet(mpriv._escAs, mpub._escAs); - // Keep escapes from the actual private value before narrowing it to - // the declaration. Selecting its Store from a MemMerge must preserve - // this result, including Scalar.BOT's unknown pointer escapes. - TypeMem defaults = CodeGen.CODE._phase.ordinal() strs, HashMap types, IdentityHashMap anodes ) { @@ -104,8 +110,15 @@ public class FunNode extends RegionNode { // uniform call syntax, including callbacks forwarded by another class. public Type defaultArg(int idx) { Type t = sig().arg(idx); + // Default private construction memory publishes no identities. Keep + // its unknown contents and the broad signature for actual callers. + if( t instanceof TypeMem mem && mem._one ) + return mem.makeFrom(XInt.EMPTY,XInt.EMPTY); + // Partial objects have stronger constraints if( t instanceof TypeMemPtr ptr && ptr._partial && - !(idx==0 && sig().nargs()>1 && sig().arg(1) instanceof TypeMem) ) return ptr.partialBound(); + !(idx==0 && sig().nargs()>1 && sig().arg(1) instanceof TypeMem) ) + return ptr.partialBound(); + // Normal default args just use the signature if( idx!=0 || t!=TypePtr.PTR ) return t; TypeStruct clz = (TypeStruct)Parser.TYPES.get(TypeStruct.addClzPrefix(_compunit._cname)); assert clz!=null; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java index 740b0895..9ef20c77 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/GlobalEscapeNode.java @@ -18,18 +18,13 @@ public class GlobalEscapeNode extends Node { @Override public TypeMem compute() { TypeMem xmem = TypeMem.START; for( CallNode call : CodeGen.CODE._calls ) - if( !call.isDead() ) { + if( !call.isDead() ) xmem = xmem.escapes(call.exposed(this)); - } for( FunNode fun : CodeGen.CODE._linker ) - if( fun!=null && fun.summary()!=null && !fun.summary().isDead() ) { + if( fun!=null && fun.summary()!=null && !fun.summary().isDead() ) xmem = xmem.escapes(fun.summary().exposed(this)); - // A reachable unloaded body can call these targets, including - // private initializers. Its arguments are unavailable here. - if( fun._type==Type.CONTROL ) - for( int fidx : fun.summary()._classDependencyFIDXs ) - if( fidx!=0 ) xmem = xmem.makeFrom(XInt.meet(xmem._escFs,XInt.make(fidx)),xmem._escAs); - } + // Do not follow class-init dependencies; class A might trigger class B + // to init, but this does not escape class B directly. return xmem; } } 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..877eb48d 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/InitViewNode.java @@ -15,7 +15,7 @@ public class InitViewNode extends TypeNode { if( ptr.isHigh() || mem.isHigh() ) return Type.TOP; if( !(ptr instanceof TypeMemPtr p) ) return ptr; TypeStruct state = mem instanceof TypeMem m && m._one && m._t instanceof TypeStruct ts - ? ts : p._obj.makeInit(); + ? ts : p._obj.makeInit(false); // 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/KeepAliveNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java index 7db31fe3..f9263fc7 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/KeepAliveNode.java @@ -7,7 +7,7 @@ import java.util.BitSet; import java.util.ArrayDeque; /** A lexical lifetime endpoint. This is a control use, not a machine operand. - * Kept values may be raw addresses; Allocation follows them back to storage. + * Kept values may be raw addresses; their storage remains reachable through the conversion. * Retained in .simple and through inlining; erased before scheduling. */ public class KeepAliveNode extends CFGNode { public KeepAliveNode(Node ctrl, Node value) { super(ctrl,value); } 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 52dbfa8e..287ae8c8 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java @@ -260,30 +260,6 @@ public class LoadNode extends MemOpNode { 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); - FunNode target=CodeGen.CODE.link(init.cu()); - if( target!=null ) { - addDep(target); - SummaryNode summary=target.summary(); - if( summary!=null && !XInt.bit(summary._effects._writes,_alias) ) - ready=classInitialized(init.mem(),active); - } - } - else if( mem instanceof ProjNode proj && proj._idx==1 && proj.in(0) instanceof CallEndNode end ) { - addDep(end); - if( end.in(0) instanceof CallNode call ) { - Type ftype=addDep(call.fptr())._type; - FunNode target=ftype instanceof TypeFunPtr fp && fp.isConstant() ? CodeGen.CODE.link(fp.fidx()) : null; - var effects=CodeGen.CODE._effects; - if( target!=null && effects!=null ) { - addDep(target); - var effect=effects.get(target); - if( effect!=null && !XInt.bit(effect._writes,_alias) ) - ready=classInitialized(call.mem(),active); - } - } - } 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); 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..1f821246 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoopNode.java @@ -51,6 +51,7 @@ public class LoopNode extends RegionNode { CProjNode f = new CProjNode(iff,1,"False").init(); 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); 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 a077e14b..d79473c7 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java @@ -131,7 +131,6 @@ public class MemMergeNode extends Node { } } return TypeMem.makePrivate(ts); - } // Normal public memory; meet across escaped inputs diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java index 88a1242a..8ce9d6e2 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/NewNode.java @@ -44,12 +44,13 @@ public class NewNode extends Node implements MultiNode { @Override public TypeTuple compute() { if( ctrl()._type.isHigh() ) return TypeTuple.DEAD_NEW; - TypeStruct ts = _ts.isAry() ? _ts : _ts.makeInit(); + boolean opto = CodeGen.CODE._phase.ordinal() >= CodeGen.Phase.Opto.ordinal(); + TypeStruct ts = _ts.isAry() ? _ts : _ts.makeInit(opto); + // Arrays get pre-zeroed by constructor. Object fields start at + // Scalar.BOT during parsing, Scalar.TOP during Opto; declaration + // defaults are explicit Stores. This is + // private memory, so no aliases escape yet. return TypeTuple.make(TypeMemPtr.make(_ts).withDelete(_deletable), - // Arrays get pre-zeroed by constructor. - // Object fields start at Scalar.BOT; declaration - // defaults are explicit Stores. This is private - // memory, so no aliases escape yet. TypeMem.make(1,ts,true,false,false,null,null)); } 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..d76aa201 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._semanticReturn!=null && _fun._semanticReturn.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/SummaryNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java index ea2bdf03..4ebdd156 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SummaryNode.java @@ -9,22 +9,12 @@ import java.util.HashMap; public class SummaryNode extends CFGNode implements MultiNode { public TypeTuple _state; - public final FunctionEffects _effects; - public final Allocation.Summary _allocation; // Callees and touched class initializers, by FIDX, for class-init cycle checks. public final int[] _classDependencyFIDXs; public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, Node... inputs) { - this(state,classDependencyFIDXs,new FunctionEffects(XInt.FULL,true,state.mem()),inputs); - } - public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, FunctionEffects effects, Node... inputs) { - this(state,classDependencyFIDXs,effects,null,inputs); - } - public SummaryNode(TypeTuple state, int[] classDependencyFIDXs, FunctionEffects effects, Allocation.Summary allocation, Node... inputs) { super(inputs); _state = state; - _effects = effects; - _allocation = allocation; _classDependencyFIDXs = classDependencyFIDXs; CodeGen.CODE.add(CodeGen.CODE._globalEscapes); } @@ -36,10 +26,8 @@ public class SummaryNode extends CFGNode implements MultiNode { if( in(0)._type.isHigh() ) return TypeTuple.STATE.dual(); // 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; - if( _effects._writes!=XInt.EMPTY || _state.mem()._one ) - mem = (TypeMem)mem.meet(_state.mem()); - else mem = mem.escapes(_state.mem()); - for( int i = firstArgument(); i0 && sig.arg(0)==TypePtr.PTR ? 3 : 2; + return fun.isClz() || (sig.nargs()>0 && sig.arg(0)==TypePtr.PTR) ? 3 : 2; } @Override boolean _upgradeType(HashMap types) { TypeTuple state = (TypeTuple)_state.upgradeType(types); 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 8dad94ec..0ddd3a31 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Allocations.java @@ -16,13 +16,8 @@ final class Allocations { Node parseNew() { P._lexer.skipWhiteSpace(); Lexer site=P.loc(); - Type t = P.types.parseType(); - if( t==null ) { - String tname = P._lexer.matchId(); - if( tname==null || Parser.KEYWORDS.contains(tname) ) - throw Parser.error("Expected a type after 'new'",site); - t = P.types.forwardRefType(tname); - } + Type t = P.types.parseType(true); + if( t==null ) throw Parser.error("Expected a type after 'new'",site); // Parse ary[ length_expr ] if( P.match("[") ) { boolean readonly = P.match("~"); 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 5064c479..00ea624c 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java @@ -119,7 +119,7 @@ final class Functions { Type t = P.types.parseType(); // Arg type if( t==null ) break; P._lexer.skipWhiteSpace(); - Lexer qualifier=P.loc(); + Lexer qualifier = P.loc(); if( P.match("^") ) { if( !(t instanceof TypeMemPtr ptr) || ptr._obj.isAry() ) throw Parser.error("'^' requires a struct parameter",qualifier); @@ -128,7 +128,7 @@ final class Functions { } finals.set(ids.size(),P.declarations.bindingFinal(t)); P._lexer.skipWhiteSpace(); - Lexer nameLoc=P.loc(); + Lexer nameLoc = P.loc(); String id = P.requireId(); // Older free functions may explicitly name a source argument // "self". It shadows the implicit class receiver, not its ABI slot. 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 f4103fe6..1f896f03 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java @@ -34,7 +34,7 @@ final class References { P.ctrl(),P.mem(),receiver,P.fldoff(receiver,name))); } - // Resolve a primary name, retaining its use site before speculative type lookup. + // Resolve a primary name, retaining its use site before class lookup. Node parseName(String id, int pre, int pos, int pos2) { Lexer site=P.loc(); site._position=pos; @@ -42,29 +42,16 @@ final class References { // Attempt a local var lookup first Var var = P._scope.lookup(id); if( var==null ) { - // Not a local var, try again as a type name - P.pos(pos); - Lexer nameLoc = P.loc(); - Type t = P.types.parseType(); - if( t!=null ) { - // Static typename lookup - if( P.peek('.') ) // type.fld, which is really a field lookup in the class object - return P.expressions.parsePostfix(P.con(t)); - // Direct reference to a type. Convert the instance - // type to a class type name - if( !(t instanceof TypeMemPtr tmp) ) { - //return new FRefNode(addClzPrefix(tmp._obj._name), loc()).peephole(); - // Not a local var, but yes a bare type... disallow a local - // FREF and return null, not-a-primary parse. - P.pos(pos); - return null; - } - } + // A class name is a value here. Resolve only this identifier; + // every following dot is a Load, never part of a type parse. + String name = P.types.knownTypeName(id); + Type clz0 = name==null ? null : Parser.TYPES.get(TypeStruct.addClzPrefix(name)); // Insert FREF outside enclosing Kind.Func scope. P.pos(pos2); - t = FRefNode.FREF_TYPE; + Type t = FRefNode.FREF_TYPE; // Check if this is a class. + // Even a known module needs an FRef so ParseAll records its dependency. CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,id); if( cu!=null ) { // Must be a final class-type @@ -73,9 +60,10 @@ final class References { if( clz == null ) Parser.TYPES.put(clzName,clz = TypeStruct.make(clzName,true)); t = TypeMemPtr.make((byte)2,clz,true); - } + } else if( clz0 instanceof TypeStruct clz ) + return P.expressions.parsePostfix(P.con(TypeMemPtr.make((byte)2,clz,true))); // Define the FRef - var = P._scope.defineFRef(id,t,true,nameLoc); + var = P._scope.defineFRef(id,t,true,site); P.references._frefs.push((FRefNode)P._scope.in(var)); } @@ -187,7 +175,7 @@ final class References { } } - boolean arrayMethod="del".equals(name) && (ts==null || ts.isAry()); + boolean arrayMethod = "del".equals(name) && (ts==null || ts.isAry()); Field fld = ts==null ? null : ts.field(name); if( fld==null && ts!=null && !TypeStruct.startsClzPrefix(ts._name) ) { Type clz0 = Parser.TYPES.get(TypeStruct.addClzPrefix(ts._name)); 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 92117531..48383a48 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java @@ -21,7 +21,11 @@ final class Types { // Will also match external names like "sys.io" or "externModule.subtype.subtype" - Type parseType() { + Type parseType() { return parseType(false); } + + // After new, a type needs no following binding. In a declaration/parameter + // an unknown name is only a type when followed by a binding name. + Type parseType(boolean allocation) { if( P.peek('{') ) return parseFunctionType(); int old1 = P.pos(); @@ -30,19 +34,14 @@ final class Types { String tname = P._lexer.matchId(); if( tname==null ) return P.posT(old1); + Ary forwards = new Ary<>(String.class); Type t0 = Parser.TYPES.get(tname); if( Parser.KEYWORDS.contains(tname) ) { if( t0==null ) return P.posT(old1); } else { if( t0==Type.BOTTOM || t0==Type.TOP ) return t0; // var/val - tname = typeName(tname).intern(); + tname = typeName(tname,forwards).intern(); t0 = Parser.TYPES.get(tname); - // Bare forward types use the same file-relative name as `new`. - // A later sibling declaration must complete this very type. - if( t0 == null && tname.indexOf('.') == -1 ) { - tname = fullTypeName(tname); - t0 = Parser.TYPES.get(tname); - } } Type t1 = t0==null ? TypeStruct.forward(tname) : t0; @@ -78,36 +77,31 @@ final class Types { break; } - // Check no forward ref - if( t0 != null ) return t2; // Check valid forward ref, after parsing all the type extra bits. // Cannot check earlier, because cannot find required 'id' until after "[]?" syntax - int old2 = P.pos(); - P.match("^"); // Constructor parameter qualifier; parsed by Functions. - if( !P.match("!") ) P.match("~"); - String id = P._lexer.matchId(); - if( !(P.peek(',') || P.peek(';') || P.peek('=') || P.match("->")) || id==null ) - return P.posT(old1); // Reset lexer to reparse - P.pos(old2); // Reset lexer to reparse - // Yes a forward ref, so declare it - forwardRefType(tname,(TypeStruct)((TypeMemPtr)t1)._obj); + if( t0==null && !allocation ) { + int old2 = P.pos(); + P.match("^"); // Constructor parameter qualifier; parsed by Functions. + if( !P.match("!") ) P.match("~"); + String id = P._lexer.matchId(); + if( !(P.peek(',') || P.peek(';') || P.peek('=') || P.match("->")) || id==null ) + return P.posT(old1); // Reset lexer to reparse + P.pos(old2); // Reset lexer to reparse + } + // Commit only after recognizing a type, never during expression lookahead. + for( String name : forwards ) + forwardRefType(name,TypeStruct.forward(name)); // Return the (array, final) type return t2; } - TypeMemPtr forwardRefType( String tname, TypeStruct tself ) { + private void forwardRefType( String tname, TypeStruct tself ) { Parser.TYPES.put(tname,tself); String clzName = TypeStruct.addClzPrefix( tname ); // Only a struct declaration publishes an instance initializer. A // forward type may name a file with just , so do not invent // a constructor field (or overwrite an already parsed class). Parser.TYPES.putIfAbsent(clzName,TypeStruct.make(clzName,true)); - return TypeMemPtr.make(tself); - } - - TypeMemPtr forwardRefType( String tname ) { - tname = fullTypeName(tname); - return forwardRefType(tname,TypeStruct.forward(tname)); } String fullTypeName( String tname ) { @@ -197,57 +191,52 @@ final class Types { return fld; } - // typeName: walk known local types first, then enclosing namespaces, then - // file modules. A missing suffix of a known type belongs to field parsing. - private String typeName(String name) { - if( Parser.TYPES.containsKey(name) ) return dottedName(name,false); + // TODO: Backport qualified-name parsing to Chapters 28a-32. + // Resolve only the first component. Expression lookup uses this without + // consuming member access; type lookup then consumes the qualified tail. + String knownTypeName(String name) { + if( Parser.TYPES.containsKey(name) || Parser.TYPES.containsKey(TypeStruct.addClzPrefix(name)) ) return name; String root = P._nestedType; int dot = root.indexOf('.'); if( dot!=-1 ) root = root.substring(0,dot); - if( name.equals(root) ) return rootedName(name); + if( name.equals(root) ) return name; for( String nest = P._nestedType; ; ) { String full = nest+"."+name; - if( Parser.TYPES.containsKey(full) ) return dottedName(full,false); + if( Parser.TYPES.containsKey(full) || Parser.TYPES.containsKey(TypeStruct.addClzPrefix(full)) ) return full; int idx = nest.lastIndexOf('.'); if( idx==-1 ) break; nest = nest.substring(0,idx); } - CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,name); - return dottedName(cu==null ? name : cu._cname,true); + return null; } - private String dottedName(String name, boolean forward) { + private String typeName(String id, Ary forwards) { + String name = knownTypeName(id); + if( name==null ) { + CompUnit cu = ParseAll.findCompUnit(P._code,P._ref,id); + name = cu==null ? fullTypeName(id) : cu._cname; + } + if( !Parser.TYPES.containsKey(name) ) forwards.push(name.intern()); while( true ) { int old = P.pos(); if( !P.match(".") ) return name; String part = P.matchId(); - if( part==null || (!forward && !Parser.TYPES.containsKey(name+"."+part)) ) { + if( part==null ) { P.pos(old); return name; } - name += "."+part; - } - } - - // A root-qualified name may introduce an as-yet-undeclared nested type - // inside the current lexical namespace. Once forward, keep its full tail. - private String rootedName(String name) { - boolean forward = false; - while( true ) { - int old = P.pos(); - if( !P.match(".") ) return name; - String part = P.matchId(); - if( part==null ) { P.pos(old); return name; } String full = name+"."+part; - boolean known = Parser.TYPES.containsKey(full); - if( !known && !forward && - !(P._nestedType.equals(name) || P._nestedType.startsWith(name+".")) ) { + Type parent = Parser.TYPES.get(name); + // Closed types can still be followed by an allocation's member + // access, e.g. new Counter.step(). Open types admit nested names, + // whether they are forward refs or definitions still being parsed. + if( !Parser.TYPES.containsKey(full) && parent instanceof TypeStruct ts && !ts._open ) { P.pos(old); return name; } - name = full; - forward |= !known; + name = full.intern(); + if( !Parser.TYPES.containsKey(name) ) forwards.push(name); } } 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 1c83ddd7..05fd1795 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMem.java @@ -97,7 +97,7 @@ public class TypeMem extends Type { } // Existing escapes plus `t` escapes public TypeMem escapesFrom(Type t) { - return make(_alias,_t,_one,_clz,_final, escapeFIDX(_escFs,t), escapeAlias(_escAs,t)); + return escapes(t); } // An opaque external object can expose the public interface and whatever // private values have already escaped. It cannot invent access to other @@ -184,6 +184,17 @@ public class TypeMem extends Type { @Override Type _upgradeType(HashMap TYPES) { return make(_alias,_t._upgradeType(TYPES),_one,_clz,_final,_escFs,_escAs); } + @Override public TypeMem upgradeType(HashMap TYPES) { + TypeMem mem = (TypeMem)super.upgradeType(TYPES); + Type t = mem._t; + // The recursive upgrade has finished; reset the escape set from FULL + // to what can be locally seen now + 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 (XInt.EMPTY,t), + escapeAlias(XInt.EMPTY,t)); + return mem; + } @Override int hash() { return 9876543 + _alias + _t.hashCode() + (_one ? 8196 : 0) + (_clz ? 4098 : 0) + (_final ? 16392 : 0) + XInt.hash(_escFs) + XInt.hash(_escAs); } @@ -270,7 +281,7 @@ public class TypeMem extends Type { case TypeFunPtr tfp -> XInt.meet(xs,tfp.fidxs()); case TypeMem mem -> XInt.meet(xs,mem._escFs); // An abstract pointer or scalar can refine to a concrete escaped - // object or function. Until then it must allow all of their bits. + // object or function. Until then, it must allow all of their bits. case TypePtr ptr -> ptr.isHigh() ? xs : XInt.FULL; case Type tt -> tt == BOTTOM || tt == TypeScalar.BOT ? XInt.FULL : xs; }; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java index 02d26a1e..6695bc81 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeMemPtr.java @@ -101,7 +101,7 @@ public class TypeMemPtr extends TypeNil { // A partial declaration promises no initialized slots. Actual callers may // supply a sharper shape; the declaration must not manufacture those facts. - public TypeMemPtr partialBound() { return _partial ? makeFrom(_obj.makeInit()) : this; } + public TypeMemPtr partialBound() { return _partial ? makeFrom(_obj.makeInit(false)) : this; } // Project field initialization onto declared field types, not stored // constants. A pointer field being set does not complete its referent. 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 d1586547..2a6bb203 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java @@ -149,11 +149,10 @@ public class TypeStruct extends Type { Field.make("[]" ,con ,bodyAlias,true)); } - public TypeStruct makeInit() { + public TypeStruct makeInit(boolean opto) { Field[] fs = new Field[_fields.length]; for( int i=0; i<_fields.length; i++ ) { - if( _fields[i]._extern ) { fs[i] = _fields[i]; continue; } - fs[i] = _fields[i].makeFrom(TypeScalar.BOT); + fs[i] = _fields[i]._extern ? _fields[i] : _fields[i].makeFrom(opto ? TypeScalar.TOP : TypeScalar.BOT); } return make(_name,_open,_fref,fs); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/util/WorkList.java b/chapter33/src/main/java/com/seaofnodes/simple/util/WorkList.java new file mode 100644 index 00000000..a4330df7 --- /dev/null +++ b/chapter33/src/main/java/com/seaofnodes/simple/util/WorkList.java @@ -0,0 +1,78 @@ +package com.seaofnodes.simple.util; + +import com.seaofnodes.simple.node.Node; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Random; + +/** Deduplicated node worklist with seeded random removal. Membership uses + * Node IDs, never Node.hashCode (which participates in GVN). + * Use pop() for iterative solvers and popOnce() for graph traversals. */ +public class WorkList { + private Node[] _es; + private int _len; + private final BitSet _on; // Queued nodes, plus visited nodes with popOnce(). + private final Random _R; + private final long _seed; + private long _totalWork = 0; + + public WorkList() { this(123); } + public WorkList(long seed) { + _es = new Node[1]; + _on = new BitSet(); + _seed = seed; + _R = new Random(seed); + } + + /** Add a node unless already marked. Null is ignored. */ + public E push(E x) { + if( x==null ) return null; + int idx = x._nid; + if( !_on.get(idx) ) { + _on.set(idx); + if( _len==_es.length ) + _es = Arrays.copyOf(_es,_len<<1); + _es[_len++] = x; + _totalWork++; + } + return x; + } + + public void addAll(Ary ary) { + for( E n : ary ) push(n); + } + public void addAll(E[] es) { + for( E n : es ) push(n); + } + + /** Queued membership; popOnce() also retains already-visited membership. */ + public boolean on(E x) { return _on.get(x._nid); } + + /** Remove a random node and allow it to be queued again. Null when empty. */ + public E pop() { + E x = popOnce(); + if( x!=null ) _on.clear(x._nid); + return x; + } + + /** Remove a random node, retaining its mark to prevent revisits in cyclic + * graph walks. clear() starts a fresh traversal. Null when empty. */ + @SuppressWarnings("unchecked") + public E popOnce() { + if( _len==0 ) return null; + int idx = _R.nextInt(_len); + E x = (E)_es[idx]; + _es[idx] = _es[--_len]; + _es[_len] = null; + return x; + } + + public boolean isEmpty() { return _len==0; } + public void clear() { + Arrays.fill(_es,0,_len,null); + _len = 0; + _on.clear(); + _R.setSeed(_seed); + _totalWork = 0; + } +} -- cgit v1.2.3