diff options
| author | Cliff Click <cliffc@acm.org> | 2026-12-05 09:08:46 -0800 |
|---|---|---|
| committer | Cliff Click <cliffc@acm.org> | 2026-12-05 09:08:46 -0800 |
| commit | bbe824d4c5c998ad76ff685d9be67838c7ce86a8 (patch) | |
| tree | 4310c46c039d001d77ede25eb8c65292fd14e3ff | |
| parent | b1cf31c5fcc15ba0d8a5af7834f3f67d647f4a84 (diff) | |
| download | Simple-bbe824d4c5c998ad76ff685d9be67838c7ce86a8.tar.gz Simple-bbe824d4c5c998ad76ff685d9be67838c7ce86a8.zip | |
Unify class and instance initialization through field memory
Emit initializer stores in source order so helpers observe prior writes and their updates remain visible. Remove deferred class-field stores and preserve guards for reloaded fields.
Fix exposed load, Phi, shift, and register-allocation cases. Preserve CallEnd memory bounds before finite targets link, without imposing peephole ordering. Use identity comparisons for interned class and field names.
Add initializer and CallEnd regressions, keep historical SSA tests explicitly local, and document initialization and formatting rules. Full make -j8 -k tests passes, including native, fuzzer, and lattice checks.
36 files changed, 238 insertions, 109 deletions
diff --git a/chapter33/docs/33-grammar.md b/chapter33/docs/33-grammar.md index 7e9ef8cd..2de46bb9 100644 --- a/chapter33/docs/33-grammar.md +++ b/chapter33/docs/33-grammar.md @@ -256,8 +256,12 @@ one-pass IR builder: `Declarations` and `Types` use speculative parsing and cursor restore; qualified type lookup also stops before a suffix that belongs to an expression. - `References` resolves bare fields through their receiver, so assignments, - reads, and updates share the field-access path. Locals use SSA; class - initializer declarations retain their Scope values until initializer exit. + reads, and updates share the field-access path, including inside the owning + initializer. Both class and instance declarations emit Stores in source + order; helper calls see the preceding writes and subsequent reads see the + helpers' effects. Instance defaults run once per instance. Class fields use + public alias memory; an instance under construction uses its private memory. + Lexically local bindings use SSA; file-level bindings are class fields. Global functions receive their owning class singleton as `self`, including when invoked through a callback. Instance methods receive their object. - `for` updates are scanned first and parsed after the body, where their effects @@ -265,8 +269,9 @@ one-pass IR builder: discovery, so later fields have local slots. Both use `Lexer.skipTo`, which ignores delimiters inside comments and quoted text. - `Structs.parseInitializer` parses a file or struct body as a function while - discovering fields. `Functions.parseBody` still owns function scope/return - construction; moving it does not change constructor or memory semantics. + discovering fields. `declareField` emits both kinds of field initialization; + `finishInitializer` closes their types without emitting deferred Stores. + `Functions.parseBody` owns function scope/return construction. The syntax chart does not describe all name/type restrictions. In particular, prefix updates require an already-known non-pointer binding, and a private-class diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java index c3be4b71..585cdbf1 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java @@ -338,7 +338,10 @@ public class RegAlloc { if( splitEmptyMaskByUse(round,lrg) ) return true; } - if( lrg._mask.isEmpty() && lrg._multiDef && lrg._1regUseCnt > 1 && lrg._1regDefCnt <= 1 ) { + // Several call results can share this Phi web (all defined in RAX), + // while its arguments require different registers. Isolate those uses + // even when there is more than one constrained definition. + if( lrg._mask.isEmpty() && lrg._multiDef && lrg._1regUseCnt > 1 ) { if( splitEmptyMaskSingleUses(round,lrg) ) return true; } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java b/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java index 3d3a40dd..55abab52 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/codegen/StaticData.java @@ -129,7 +129,7 @@ public final class StaticData { if( f._extern ) continue; int off=ts.offset(idx); while( bits.size()<obj.offset+off ) bits.write(0); - if( f._fname.equals("[]") ) ((TypeConAry)f._t).write(bits); + if( f._fname=="[]" ) ((TypeConAry)f._t).write(bits); else { Type value=f._t.isConstant() ? f._t : f._t.makeZero(); int log=f._t.log_size(); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java index cb56c9b6..8943a7af 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/CallEndNode.java @@ -114,8 +114,11 @@ public class CallEndNode extends CFGNode implements MultiNode { // This also covers invalid calls (e.g. wrong arity), which never link. // SCCP links valid finite targets as soon as they become known, before // computing their CallEnd, so this check does not trigger during SCCP. + // Specializing an outside call can reveal finite targets before their + // Return edges are linked. Retain the memory bound already established + // for the broader target set; missing edges do not invalidate it. if( nIns()-1 < tfp.nfcns() ) - return TypeTuple.make(Type.CONTROL,TypeMem.BOT,tfp.ret()); + return TypeTuple.make(Type.CONTROL,_type instanceof TypeTuple old ? old.mem() : TypeMem.BOT,tfp.ret()); // Start at a high tuple (matching Returns' tuple) TypeTuple state = TypeTuple.STATE.dual(); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java index 9e130bb4..befd9f4e 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/ConFldOffNode.java @@ -76,7 +76,7 @@ public class ConFldOffNode extends ConstantNode { @Override public boolean eq(Node n) { ConFldOffNode off = (ConFldOffNode)n; // Invariant - return _ts._name==off._ts._name && _fname.equals(off._fname) && super.eq(n); + return _ts._name==off._ts._name && _fname==off._fname && super.eq(n); } @Override int hash() { return super.hash() * _ts._name.hashCode() * _fname.hashCode(); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java index 93f2baf9..119e0300 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FldOffNode.java @@ -43,7 +43,7 @@ public class FldOffNode extends TypeNode { @Override public boolean eq(Node n) { FldOffNode off = (FldOffNode)n; // Invariant - return _fname.equals(off._fname) && super.eq(n); + return _fname==off._fname && super.eq(n); } @Override int hash() { return super.hash() * _fname.hashCode(); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java index d34b342d..558ad0f4 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/FormatNode.java @@ -18,7 +18,7 @@ public final class FormatNode extends Node { if( t instanceof TypeInteger ) return 2; if( t instanceof TypeFloat ) return 3; if( t instanceof TypeMemPtr p && !p.nullable() && p._obj.isAry() && - p._obj._name.equals("[]u8") ) return 4; + p._obj._name=="[]u8" ) return 4; return 0; } @Override public Type compute() { diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java index 7c6d6b56..0e56245e 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/LoadNode.java @@ -98,13 +98,13 @@ public class LoadNode extends MemOpNode { t = mem._alias==_alias ? mem._t : actual==null ? TypeScalar.BOT : actual._t; } else if( mem._alias==_alias ) t = t.join(mem._t); - // A final method's identity comes from its declaration, not from an - // unknown outside writer. It remains callable on a local object even - // when that function has never escaped to outside code. + // Final function fields retain their declared targets, including a + // choice between several private functions. Outside memory cannot + // overwrite them or remove targets which have not escaped. if( !mem._one ) { Type declared = Parser.TYPES.get(tmp._obj._name); Field field = declared instanceof TypeStruct obj ? obj.field(_name) : null; - if( !(field != null && field._final && field._t instanceof TypeFunPtr fun && fun.isConstant()) ) + if( !(field != null && field._final && field._t instanceof TypeFunPtr) ) t = mem.outside(t); } // Store forwarding is also a value fact during SCCP. Waiting for the @@ -143,7 +143,7 @@ public class LoadNode extends MemOpNode { // Null checks are handled by types. Array elements retain control for // range checks, but reading an array's length has no index to check. if( in(0)!=null && ptr._type instanceof TypeMemPtr tmp && - (!tmp._obj.isAry() || _name.equals("#")) ) { + (!tmp._obj.isAry() || _name=="#") ) { setDef(0,null); return this; } @@ -154,7 +154,8 @@ public class LoadNode extends MemOpNode { (fld=tmp._obj.field(_name)) != null && _alias != fld._alias) { assert _alias==1 || _alias == fld._alias; - assert !tmp._obj._open && !tmp._obj._fref; + // Field aliases are fixed as declarations are discovered; the + // containing initializer can still be open at this point. unlock(); // Alias participates in GVN semantics _alias = fld._alias; return this; @@ -166,7 +167,7 @@ public class LoadNode extends MemOpNode { // Whole-memory parameters lose individual alias types. Recover the // class flag from every caller without moving a load across a call. // SCCP must have finished discovering callers before we remove it. - if( "$init".equals(_name) && ptr._type instanceof TypeMemPtr clz && + if( _name=="$init" && ptr._type instanceof TypeMemPtr clz && TypeStruct.startsClzPrefix(clz._obj._name) && CodeGen.CODE._phase.ordinal()>=CodeGen.Phase.IterPostOpto.ordinal() && classInitialized(mem,new BitSet()) ) @@ -207,7 +208,7 @@ public class LoadNode extends MemOpNode { // val = ptr.x; ptr.x = val; if( mem() instanceof PhiNode memphi && !(memphi instanceof ParmNode) && (memphi instanceof MemPhiNode || (memphi._type instanceof TypeMem tm && tm._one)) && - memphi.region()._type == Type.CONTROL && memphi.nIns()== 3 && + memphi.region()._type == Type.CONTROL && memphi.nIns()>2 && // Retain control on both copies only if it dominates both paths. // The Region itself, or a later range check, cannot move to its inputs. (in(0)==null || cfg0().domLCA(memphi.region().idom(this),this)==cfg0()) && @@ -220,8 +221,10 @@ public class LoadNode extends MemOpNode { // is also loop invariant. A pointer Phi may select another object. Node stop = memphi.region() instanceof LoopNode && !(ptr instanceof PhiNode p && p.region()==memphi.region()) ? memphi : null; - if( find(memphi.in(2),ptr,stop,new BitSet())!=null || - (!(memphi.region() instanceof LoopNode) && find(memphi.in(1),ptr,null,new BitSet())!=null) ) { + boolean folds = false; + for( int i=memphi.region() instanceof LoopNode ? 2 : 1; i<memphi.nIns(); i++ ) + folds |= find(memphi.in(i),ptr,stop,new BitSet())!=null; + if( folds ) { // Integer loop Phis widen to i64. Keep the load's declared // width at the result, as for ordinary typed loop variables. if( _type instanceof TypeInteger && !declaredType().isa(_type) ) return null; @@ -232,7 +235,8 @@ public class LoadNode extends MemOpNode { phi.addDef(load(memphi.in(i),p,stop,phi)); } CodeGen.CODE.add(phi.unkeep()); - return _type instanceof TypeInteger ? new ConvertNode(declaredType(),phi) : phi; + Node value = phi.peephole(); + return _type instanceof TypeInteger ? new ConvertNode(declaredType(),value) : value; } } @@ -302,8 +306,8 @@ public class LoadNode extends MemOpNode { // Alias 1 is still unresolved, not a proven different field. if( st._alias==1 ) return null; addDep(st.ptr()); - if( alias==st._alias && (ptr==address(st.ptr()) || ptr==address(st.nnptr())) && - (!_name.equals("[]") && _name.equals(st._name) || off()==st.off() || + if( alias==st._alias && (sameAddress(ptr,address(st.ptr())) || sameAddress(ptr,address(st.nnptr()))) && + (_name!="[]" && _name==st._name || off()==st.off() || addDep(off())._type.isConstant() && off()._type==addDep(st.off())._type) ) { // Forwarding must preserve the pointer type already seen // by users: completion, read-only view, and recursive shape. @@ -316,6 +320,7 @@ public class LoadNode extends MemOpNode { // A full-width load cannot narrow the forwarded value. if( declaredType() instanceof TypeInteger ti && ti.log_size()==3 && !addDep(st.val())._type.isa(expected) ) return null; + if( expected instanceof TypeFloat && !addDep(st.val())._type.isa(expected) ) return null; return st; } if( (external || alias==st._alias) && (external || !neverAlias(ptr,address(st.ptr()))) && @@ -373,10 +378,10 @@ public class LoadNode extends MemOpNode { return CodeGen.CODE.add(phi.unkeep().peephole()); } Node fold=folded(win); - if( fold!=null ) return fold.peephole(); + if( fold!=null ) return fold._type==null ? fold.peephole() : fold; } LoadNode ld=new LoadNode(_loc,_name,_alias,in(0),mem,ptr,off()); - return ld.peephole(); + return ld.init(); } // Type views preserve the address. Keep the actual Load pointer qualified @@ -398,6 +403,14 @@ public class LoadNode extends MemOpNode { return ptr; } + // A class has one address even while parsing extends its declared shape. + // Constants for successive shapes need not yet have the same GVN node. + private static boolean sameAddress(Node a, Node b) { + return a==b || a._type instanceof TypeMemPtr x && b._type instanceof TypeMemPtr y && + x._one && y._one && x.notNull() && y.notNull() && + TypeStruct.startsClzPrefix(x._obj._name) && x._obj._name==y._obj._name; + } + private static boolean neverAlias( Node ptr1, Node ptr2 ) { return ptr1.in(0) != ptr2.in(0) && // Unrelated allocations @@ -406,6 +419,9 @@ public class LoadNode extends MemOpNode { } private static boolean hoistPtr(Node ptr, PhiNode memphi ) { + // Constants are available in every function; their Start input is a + // graph-walking edge, not a control dependence. + if( ptr.isConst() ) return true; // Can I hoist ptr above the Region? if( !(memphi.region() instanceof RegionNode r) ) return false; // Dead or dying Region/Phi @@ -445,6 +461,7 @@ public class LoadNode extends MemOpNode { // A typed load can already know its width while the stored value is // still unresolved. Do not replace it with an untyped shift/and chain. if( !(val._type instanceof TypeInteger) ) { addDep(val); return null; } + if( addDep(val)._type.isa(ti) ) return val; if( ti._min==0 ) // Unsigned return new AndNode(null,val,con(ti._max)); // Signed extension diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java index 94376086..f559c52e 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/PhiNode.java @@ -5,6 +5,7 @@ import com.seaofnodes.print.ExprPrinter; import com.seaofnodes.simple.*; import com.seaofnodes.simple.codegen.Serialize; +import com.seaofnodes.simple.codegen.CodeGen; import com.seaofnodes.simple.type.*; import com.seaofnodes.simple.util.*; import java.util.HashMap; @@ -264,6 +265,9 @@ public class PhiNode extends Node { for( Node in : x._inputs ) if( in!=null ) in.addUse(x); x = x.peephole(); + // The trial Phi had no users during its first peephole. + // Revisit it after the factored operation is connected. + CodeGen.CODE.add(x); cp._inputs.set(j,x); } if( x!=null ) x.addUse(cp); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java index 854a0d9b..21a8ebc2 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/SarNode.java @@ -30,9 +30,9 @@ public class SarNode extends ArithNode { int shift = (int)(i.value()&63); if( shift==0 ) return lhs; // A value already in the signed range needs no further extension. - if( lhs instanceof ShlNode && lhs.in(2)._type instanceof TypeInteger j && + if( lhs instanceof ShlNode && addDep(lhs.in(2))._type instanceof TypeInteger j && j.isConstant() && (j.value()&63)==shift ) { - Node value = lhs.in(1); + Node value = addDep(lhs.in(1)); if( value._type instanceof TypeInteger && value._type==_type ) return value; } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java index 511afa4e..def65cab 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/node/StoreNode.java @@ -116,7 +116,7 @@ public class StoreNode extends MemOpNode { // Allocation uses a private TypeMem and nothing else does. This // memory is truly private; a temporary singleton until it escapes - // which is never does in a constructor. - if( !_name.equals("[]") && mem._one ) + if( _name!="[]" && mem._one ) // Just track the stored value return TypeMem.make(_alias,val,true,false,fld==null ? _init : fld._final,null,null).escapesFrom(val,outside); @@ -132,7 +132,9 @@ public class StoreNode extends MemOpNode { Type t = val.meet(tfld); // Bulk memory's final bit describes its conservative remainder, not // this newly precise slice. Slice finality comes from the field. - boolean xfinal = fld != null && fld._final; + // An open receiver may still carry a provisional forward field. + // Finality falls in the lattice, so do not promise mutability yet. + boolean xfinal = ptr._obj._open || (fld != null && fld._final); return TypeMem.make(_alias,t,mem._one,mem._clz,xfinal,mem._escFs,mem._escAs).escapesFrom(val,outside); } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java index 6c626669..0a306d0f 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/ControlFlow.java @@ -70,7 +70,6 @@ final class ControlFlow { // control, memory and locals just as an explicit else arm does. if( doRHS || fside.equals("||") ) fScope = P._scope; - pred.unkeep(); // Check the trinary widening int/flt if( !fside.equals("else") ) { @@ -86,6 +85,8 @@ final class ControlFlow { tScope.balanceIf(fScope); // Merge results + boolean trueExits = tScope.ctrl()._type==Type.XCONTROL; + boolean falseExits = fScope.ctrl()._type==Type.XCONTROL; RegionNode r = P.ctrl(tScope.mergeScopes(fScope,P.loc())); Node ret = P.peep(new PhiNode("",r,lhs.unkeep(),rhs.unkeep())); // Immediately fail e.g. `arg ? 7 : ptr` @@ -93,6 +94,12 @@ final class ControlFlow { if( !fside.equals("else") && (err = ret.err()) !=null ) throw Parser.error(err.getMessage(),site); ret.keep(); r.peephole(); + // Locals retain their guarded values in Scope. Fields are loaded + // again, so retain the surviving branch's facts as well. A write or + // call changes the memory input and prevents reuse of a guarded Load. + if( trueExits != falseExits ) + P._scope.addGuards((CFGNode)P.ctrl(),pred,trueExits); + pred.unkill(); return ret.unkeep(); } } diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java index a7726521..cc5e3144 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Functions.java @@ -238,7 +238,7 @@ final class Functions { // - - If isInit, also incrementally extend the self-type. // If isInit // - upgrade and close the self-type - // - Store class singleton fields; instance Stores already exist + // - Field Stores already exist at their source positions // - <init> and user constructors return their current private memory // Unstack the {break,continue,return} scopes. @@ -297,16 +297,14 @@ final class Functions { // Last expression is the return if( P.ctrl()._type==Type.CONTROL ) { // Constructors get special return types - if( fun.isClz() ) { - assert last!=null; - } else if( isCtor ) { + if( isCtor && !fun.isClz() ) { last = P.construction.selfMem(); } addReturn(last); // exit path is now dead (nothing live after a "return") } if( isInit ) - P.structs.finishInitializer(typeName,fun.isClz(),self); + P.structs.finishInitializer(typeName,self); // Build a return from the _returnScope. // Can be no returns for never-exit functions @@ -385,15 +383,12 @@ final class Functions { expr.keep(); // Force the pending lazy bulk-memory Phi. P.mem(); // Force a pending lazy bulk-memory Phi - // Class fields are still stored at exit. Instance fields already - // travel in expr's private memory; only their scope layout is retained. + // Both initializers already carry their field Stores in memory. + // Retain only the declaration layout across early-return scopes. int lexN = P._scope.enclosingFuncOrDecl(); Kind.Func k = (Kind.Func)P._scope._kinds.at(lexN); if( FunNode.isInit(k._name) ) { int nestedLexSize = lexN+1 < P._scope.depth() ? P._scope._kinds.at(lexN+1)._lexSize : P._scope.nIns(); - if( k._name.endsWith(".<clinit>") ) - for( int i = k._lexSize; i<nestedLexSize; i++ ) - P._scope.update(P._scope.var(i),null); if( _returnScope != null ) { Var vexpr = _returnScope._vars.pop(); Node oldX = _returnScope.removeLast(); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java index 4796995f..5deb799c 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/References.java @@ -74,7 +74,13 @@ final class References { if( var._fref ) return P.expressions.parsePostfix(rvalue); Node fieldSelf = fieldSelf(var); - if( fieldSelf!=null ) return parseField(fieldSelf,id,pre); + if( fieldSelf!=null ) { + int afterName=P.pos(); + char ch=pre==0 ? P._lexer.matchOperAssign() : (char)pre; + P.pos(afterName); + if( ch!=0 ) checkAssignment(var,site); + return parseField(fieldSelf,id,pre); + } int kx = P._scope.kindx(var); int fx = P._scope.enclosingFunction(); @@ -244,6 +250,9 @@ final class References { if( fld!=null && decl==Type.BOTTOM && !ts._fref ) throw Parser.error( "'" + ts._name + "' is not fully initialized, field '" + fld._fname + "' needs to be set in a constructor",site ); Node op = P.expressions.opAssign(ch,load, decl ).keep(); + // The RHS may itself write fields or call a helper. Preserve its + // memory effects before storing this update's result. + mem = P.construction.storeMemory(expr); mem.keep(); if( !P.construction.own(expr) && expr._type instanceof TypeMemPtr view && view._ro && P.ctrl()._type!=Type.XCONTROL ) throw Parser.error("Cannot modify final field '"+name+"'",site); @@ -263,24 +272,25 @@ final class References { Node defaultSelf() { int selfx = P._scope._kinds.at(P._scope.enclosingFuncOrDecl())._lexSize; - return P._scope.in(P._scope.update(P._scope.var(selfx),null)); + Node self = P._scope.in(P._scope.update(P._scope.var(selfx),null)); + // A singleton's declarations extend its shape while parsing. Instance + // receivers instead keep their construction/access-qualified view. + if( self._type instanceof TypeMemPtr ptr && ptr._one && Parser.TYPES.get(ptr._obj._name) instanceof TypeStruct shape ) + return P.peep(new ConvertNode(ptr.makeFrom(shape),self)); + return self; } - // Find the receiver for a field lvalue. Instance initializers use memory; - // class declarations retain their Scope values until initializer exit. + // Fields use their receiver's memory, including inside their own initializer. Node fieldSelf(Var var) { int kx = P._scope.kindx(var); ScopeNode.Kind kind = P._scope._kinds.at(kx); if( !(kind instanceof Kind.Func owner) || !FunNode.isInit(owner._name) || var._idx<owner._lexSize+2 ) return null; - // Class declarations still accumulate their initial values in Scope. - // This also preserves declaration-time struct default expressions. - if( FunNode.isClz(owner._name) && P._scope.enclosingFunction()==kx ) return null; // Nested functions have their own receiver parameter. Resolve fields // through it even across intervening function and block scopes. Node self = defaultSelf(); Var receiver = P._scope.var(owner._lexSize); if( self._type instanceof TypeMemPtr ptr && receiver.type() instanceof TypeMemPtr declared && - ptr._obj._name.equals(declared._obj._name) ) return self; + ptr._obj._name==declared._obj._name ) return self; // An instance method can also name fields of its enclosing class. // Use that declaration's receiver; normal folding handles its identity. if( !FunNode.isClz(owner._name) ) return null; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java index 0c2a25f7..e72a11b2 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Statements.java @@ -194,7 +194,6 @@ final class Statements { P.ctrl(ifT.unkeep()); // set ctrl token to ifTrue projection P._scope.addGuards(ifT,pred.unkeep(),false); // Up-cast predicate parseStatement().isKill(); // Parse loop body - P._scope.removeGuards(ifT); // Merge the loop bottom into other continue statements if (_continueScope != null) { @@ -212,6 +211,9 @@ final class Statements { throw P.errorSyntax( "Unexpected code after expression" ); P.pos(old); } + // The condition also guards the for-update. Reloaded fields need + // these facts just as locals do; stores still change their memory. + P._scope.removeGuards(ifT); // The true branch loops back, so whatever is current _scope.ctrl gets // added to head loop as input. endLoop() updates the head scope, and diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java index 3a3d894c..55bc2946 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Structs.java @@ -194,7 +194,7 @@ final class Structs { return nvar; } - void finishInitializer( String typeName, boolean isClz, ParmNode self ) { + void finishInitializer( String typeName, ParmNode self ) { int lex = P._scope.klast()._lexSize; assert P._scope.var(lex)._name=="self"; TypeStruct tself = (TypeStruct)Parser.TYPES.get(typeName); @@ -222,57 +222,25 @@ final class Structs { // Improve the receiver type in scope. // Class self-type is a singleton pointer. Instance <init> receives the // broad allocation pointer, while private memory tracks initialized fields. - self._declaredType = self._type = isClz ? TypeMemPtr.make((byte)2,tself,true) : TypeMemPtr.make(constructorRecv(tself)).withPartial(true); FunNode fun = self.fun(); + self._declaredType = self._type = fun.isClz() ? TypeMemPtr.make((byte)2,tself,true) : TypeMemPtr.make(constructorRecv(tself)).withPartial(true); + P._code.addAll(self._outputs); + self.moveDepsToWorklist(); fun.setSig(fun.sig().makeFrom(self._type,0)); - - // When can _returnScope be null here? A never-exit constructor will - // not have any returns, and thus no need to gather values and store - // them into the (never) constructed object - if( P.functions._returnScope==null ) - return; - - // Class singleton fields retain their store-at-exit path. Instance - // initializers already returned their current private memory. - if( !isClz ) return; // Instance fields already have their Stores. - Node mmm = P.functions._returnScope.mem(1); - - // Store constructor results into fields - for( int i = 0; i<tself.nkids(); i++ ) { - Field fld = tself._fields[i]; - int vidx = fieldVarIdx(base,fld._fname); - if( vidx == -1 ) - continue; - Var v = P._scope.var(vidx); - if( v._fref || v._extern!=0 ) continue; // C storage has no Simple initializer - Node val = P.functions._returnScope.in(vidx); - // A numeric merge can still be untyped while parsing. Retain its - // declared conversion at the helper boundary, as assignments do. - if( fld._t instanceof TypeInteger || fld._t instanceof TypeFloat ) - val = P.conversions.convertExpr(val,fld._t); - // Store value into extended struct - Node prior = mmm.keep(); - Node st = P.peep(new StoreNode(null, fld._fname, fld._alias, fld._t, null, prior, self, ConFldOffNode.make(tself,fld._fname), val, fld._final)); - mmm = P.mergeAlias(prior,fld._alias,st); - prior.unkeep(); - } - mmm = mmm.peephole(); - - P.functions._returnScope.mem(mmm); } - // Instance declarations establish field metadata and emit their default + // Initializer declarations establish field metadata and emit their default // Stores immediately. Required fields emit no Store until assigned. void declareField(Var var, Node value, boolean uninit) { - if( !(P._scope.klast() instanceof Kind.Func kind) || !FunNode.isInstance(kind._name) ) return; - TypeStruct self = P._scope.constructorSelf(); + if( !(P._scope.klast() instanceof Kind.Func kind) || !FunNode.isInit(kind._name) ) return; + TypeStruct self = ((TypeMemPtr)P._scope.var(kind._lexSize).type())._obj; TypeStruct shape = (TypeStruct)Parser.TYPES.get(self._name); Field old = shape.field(var._name); Field fld = old==null ? Field.make(var._name,var.type(),P._code.alias(P._ref._cname),var._final) : old.makeFrom(var.type()); Parser.TYPES.put(shape._name,shape = shape.addOrUpdate(fld)); if( uninit || var._extern!=0 ) return; Node ptr = P.references.defaultSelf(); - Node mem = P.construction.selfMem().keep(); + Node mem = P.construction.memory(ptr).keep(); Node st = new StoreNode(var._loc,fld._fname,fld._alias,fld._t,P.ctrl(),mem,ptr, ConFldOffNode.make(shape,fld._fname),value,true).peephole(); P.construction.store(ptr,fld._alias,st,mem); diff --git a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java index 8c19e897..d30ca21d 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/parser/Types.java @@ -137,7 +137,7 @@ final class Types { TypeStruct self = P._scope.constructorSelf(); // Function types without a body must allow for writes. Function // expressions can infer a weaker requirement in MethodAccess. - return self == null ? TypePtr.PTR : TypeMemPtr.make(self); + return self == null ? TypePtr.PTR : TypeMemPtr.make(latestStruct(self)); } // A function type is `{ type... -> type }` or `{ type }`. diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java b/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java index beaa719c..5b661e73 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/Field.java @@ -115,7 +115,7 @@ public class Field extends Type { int hash() { return _fname.hashCode() ^ _t.hashCode() ^ _alias ^ (_final ? 1024 : 0) ^ (_extern ? 2048 : 0); } private boolean static_eq( Field f ) { - return _fname.equals(f._fname) && _alias==f._alias && _final==f._final && _extern==f._extern && _t !=null && f._t !=null; + return _fname==f._fname && _alias==f._alias && _final==f._final && _extern==f._extern && _t !=null && f._t !=null; } @Override boolean eq( Type t ) { Field f = (Field)t; diff --git a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java index 026a4018..86728184 100644 --- a/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java +++ b/chapter33/src/main/java/com/seaofnodes/simple/type/TypeStruct.java @@ -338,7 +338,7 @@ public class TypeStruct extends Type { int len = Math.min(_fields.length,that._fields.length); for( int i=0; i<len; i++ ) { Field f0 = _fields[i], f1 = that._fields[i]; - if( !f0._fname.equals(f1._fname) || f0._alias != f1._alias || f0._extern != f1._extern ) + if( f0._fname!=f1._fname || f0._alias != f1._alias || f0._extern != f1._extern ) return BOT; } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java b/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java index 26e479b2..058e385b 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/CallEndTest.java @@ -145,6 +145,31 @@ public class CallEndTest { } } + // A callback can become finite before Call idealize links its Returns. + // Computing CallEnd first must preserve the outside call's memory bound. + @Test public void testSpecializedUnlinkedCallRetainsMemory() { + CodeGen code = new CodeGen("return 0;").driver(CodeGen.Phase.Opto); + code._phase = CodeGen.Phase.IterPostOpto; + TypeFunPtr unknown = TypeFunPtr.make(false,TypeFunPtr.TEMPTY,TypeInteger.I32); + Node fptr = ConstantNode.raw(unknown); + CallNode call = new CallNode(null,ConstantNode.raw(Type.CONTROL), + ConstantNode.raw(TypeMem.START),fptr).init(); + CallEndNode end = new CallEndNode(call,TypeRPC.BOT); + TypeTuple outside = (TypeTuple)end.compute(); + end.setType(outside); + assertNotSame(TypeMem.BOT,outside.mem()); + + fptr._type = TypeFunPtr.make1((byte)2,true,TypeFunPtr.TEMPTY,TypeInteger.BOOL,100); + assertTrue(fptr._type.isa(unknown)); + TypeTuple finite = (TypeTuple)end.compute(); + assertTrue(finite.isa(outside)); + assertSame(outside.mem(),finite.mem()); + assertSame(TypeInteger.BOOL,finite.ret()); + end.setType(finite); + assertSame(finite,end.compute()); + assertEquals("compute must not link Returns",1,end.nIns()); + } + @Test public void testExternalTargets() { CodeGen code = new CodeGen("return 0;").parse(); code.externFunc(100,"first"); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java index 9f733da5..89b0553d 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter05Test.java @@ -58,13 +58,16 @@ else public void testIfMergeB() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a=arg+1; int b=0; if( arg==1 ) b=a; else b=a+1; -return a+b;"""); +return a+b; +} +"""); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return ((((Phi(Region,arg,(((arg+1)<<32)>>32))+1)<<32)>>32)+Sar);", code.print()); } @@ -73,13 +76,16 @@ return a+b;"""); public void testIfMerge2() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a=arg+1; int b=arg+2; if( arg==1 ) b=b+a; else a=b+1; -return a+b;"""); +return a+b; +} +"""); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return ((((Phi(Region,arg,(((arg+2)<<32)>>32))+1)<<32)>>32)+(((Phi(Region,(((arg+1)<<32)>>32),2)+Phi(Region,Sar,arg))<<32)>>32));", code.print()); } @@ -108,6 +114,7 @@ return a; public void testMerge4() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a=0; int b=0; if( arg ) @@ -115,6 +122,7 @@ if( arg ) if( arg==0 ) b=2; return arg+a+b; +} """); code.driver(CodeGen.Phase.FinalizeIR); String ir = code.print(); @@ -127,12 +135,14 @@ return arg+a+b; public void testMerge5() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a=arg==2; if( arg==1 ) { a=arg==3; } return a; +} """); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return (arg==Phi(Region,3,2));", code.print()); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java index d1af5d14..39809ae0 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter06Test.java @@ -246,6 +246,7 @@ return a+b; @Test public void testDemo2NonConst() { CodeGen code = new CodeGen(""" +{ // Local SSA regression; file-level bindings are class fields. int a = 0; int b = 1; int c = 0; @@ -256,6 +257,7 @@ if( arg ) { else b = 3; } return a+b+c; +} """); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return Phi(Region,6,1,5);", code.print()); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java index 20786571..6b53c394 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter07Test.java @@ -42,6 +42,7 @@ return a; public void testWhileNested() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int sum = 0; int i = 0; while(i < arg) { @@ -53,6 +54,7 @@ while(i < arg) { } } return sum; +} """); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return Phi(Loop,0,Phi(Loop,Phi_sum,(((Phi_sum+Phi(Loop,0,(((Phi_j+1)<<32)>>32)))<<32)>>32)));", code.print()); @@ -62,6 +64,7 @@ return sum; public void testWhileScope() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a = 1; int b = 2; while(a < 10) { @@ -69,6 +72,7 @@ while(a < 10) { else b = 4; } return b; +} """); code.parse(); assertEquals("return Phi(Loop,2,Phi(Region,Phi_b,4));", code.print()); @@ -131,9 +135,11 @@ return a; public void testWhile2() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a = 1; while(arg) a = 2; return a; +} """); code.parse(); assertEquals("return Phi(Loop,1,2);", code.print()); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java index 249beb11..d88016b9 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter08Test.java @@ -34,6 +34,7 @@ return arg; public void testEx5() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a = 1; while(arg < 10) { arg = arg + 1; @@ -44,7 +45,8 @@ while(arg < 10) { a = a + 1; } return a; - """); +} +"""); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return Phi(Loop,1,Phi(Region,Phi_a,(((Phi_a+1)<<32)>>32),Phi_a));", code.print()); assertTrue(code.ctrl() instanceof CProjNode); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java index 13950789..8d9b5b85 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter10Test.java @@ -105,6 +105,7 @@ public class Chapter10Test { public void testFuzzer() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a = arg/3; int b = arg*5; int x = arg*7; @@ -121,6 +122,7 @@ if( (arg/13)==0 ) { } int r = g+h; return p-r; +} """); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return 0;", code.print()); @@ -386,16 +388,16 @@ return ret.v0; CodeGen code = new CodeGen( """ int cnt = 1; -// cnt is incremented exactly once, it is not part of s0 constructor -// hence s0.x is always 1, and cnt remains at 2 +// Each instance initializer increments the class field. struct s0 { int x = cnt++; }; s0 a = new s0(); s0 b = new s0(); -// a.x==1, b.x==1, cnt==2 +// a.x==1, b.x==2, cnt==3 return a.x * 100 + b.x * 10 + cnt; """); code.driver(CodeGen.Phase.FinalizeIR); - assertEquals("Stop[ return 112; return Test.s0; ]", code.print()); + assertEquals("Stop[ return 123; return Test.s0; ]", code.print()); + assertEquals("123",Eval2.eval(code,0)); } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java index b2d773ee..7f2fa6a1 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter13Test.java @@ -11,6 +11,7 @@ public class Chapter13Test { public void testPrimes() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. if( arg < 2 ) return 0; int primeCount = 1; int prime = 3; @@ -33,6 +34,7 @@ while( prime <= arg ) { prime = prime + 2; } return primeCount; +} """); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return Phi(Region,0,Phi(Loop,1,Phi(Region,Phi_primeCount,Phi_primeCount,(((Phi_primeCount+1)<<32)>>32))));", code.print()); @@ -143,6 +145,7 @@ return i; public void testAntiDeps5() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. struct _S { int f; }; !_S !v = new _S; while(1) { @@ -151,9 +154,10 @@ while(1) { v.f = 2; } return v.f; +} """); code.driver(CodeGen.Phase.FinalizeIR); - assertEquals("return ((Phi(Loop,0,2)<<32)>>32);", code.print()); + assertEquals("return Phi(Loop,0,2);", code.print()); for( int arg : new int[]{-1,0,1,3,100} ) assertEquals("0",Eval2.eval(code,arg)); } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java index bc2ad8d3..640416ff 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter14Test.java @@ -55,9 +55,11 @@ return b; public void testU8While() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. u8 b = 123; while( b ) b = b + 456;// Truncate return b; +} """); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return 0;", code.print()); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java index 8a66dcc5..2cd7cbd8 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter17bTest.java @@ -482,10 +482,12 @@ return sum; @Test public void testFor1() { CodeGen code = new CodeGen(""" +{ // Local SSA regression; file-level bindings are class fields. int sum=0, i=0; for( ; i<arg; i++ ) sum += i; return sum; +} """); code.driver(CodeGen.Phase.FinalizeIR); assertEquals("return Phi(Loop,0,(((Phi_sum+Phi(Loop,0,(((Phi_i+1)<<32)>>32)))<<32)>>32));", code.print()); @@ -588,7 +590,8 @@ for( ; ptr; ptr = ptr.next ) return sum; """); code.driver(CodeGen.Phase.FinalizeIR); - assertEquals("return Phi(Loop,0,(((Phi_sum+.i)<<32)>>32));", code.print()); + // Class fields can retain constructor bodies; inspect this entry's return. + assertEquals("return Phi(Loop,0,(((Phi_sum+.i)<<32)>>32));", code.link(code.compunit()).ret().toString()); assertEquals("45", Eval2.eval(code, 10)); } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java index 50fecdfd..0d97a91c 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter19Test.java @@ -294,13 +294,16 @@ return a;"""); public void testIfMerge2() { CodeGen code = new CodeGen( """ +{ // Local SSA regression; file-level bindings are class fields. int a=arg+1; int b=arg+2; if( arg==1 ) b=b+a; else a=b+1; -return a+b;"""); +return a+b; +} +"""); code.driver(Phase.LocalSched,"x86_64_v2", "SystemV"); assertEquals("return (add,(sari,(shli,(inc,Phi(Region,arg,(sari,(shli,(addi,arg))))))),(sari,(shli,(add,Phi(Region,(sari,(shli,(inc,arg))),2),Phi(Region,sari,arg)))));", code.print()); } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java index 008902c5..bf4ec581 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter20Test.java @@ -158,6 +158,7 @@ return _sqrt(x) + _sqrt(y); public void testNewtonFloat() { String src = """ +{ // Local SSA regression; file-level bindings are class fields. val _test_sqrt_noInline = { flt x -> flt epsilon = 1e-15; flt guess = x; @@ -169,6 +170,7 @@ val _test_sqrt_noInline = { flt x -> } }; flt farg = arg; return _test_sqrt_noInline(farg) + _test_sqrt_noInline(farg+2.0); +} """; testCPU(src,"x86_64_v2", "SystemV",40,null); testCPU(src,"riscv" , "SystemV",17,null); @@ -213,6 +215,7 @@ flt farg = arg; return _test_sqrt_noInline(farg) + _test_sqrt_noInline(farg+2.0) public void testArray1() { String src = """ +{ // Local SSA regression; file-level bindings are class fields. int[] !ary = new int[arg]; // Fill [0,1,2,3,4,...] for( int i=0; i<ary#; i++ ) @@ -221,9 +224,10 @@ for( int i=0; i<ary#; i++ ) for( int i=0; i<ary#-1; i++ ) ary[i+1] += ary[i]; return ary[1] * 1000 + ary[3]; // 1 * 1000 + 6 +} """; testCPU(src,"x86_64_v2", "SystemV",-1,"return (add,.[],(muli,.[]));"); - testCPU(src,"riscv" , "SystemV",9,"return (add,.[],(mul,.[],1000));"); + testCPU(src,"riscv" , "SystemV",7,"return (add,.[],(mul,.[],1000));"); testCPU(src,"arm" , "SystemV",13,"return (add,.[],(mul,.[],1000));"); } diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java index 7a59adb0..77fb0377 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter21Test.java @@ -315,6 +315,7 @@ return new _s0.v1; public void testArray1() { String src = """ +{ // Local SSA regression; file-level bindings are class fields. int[] !ary = new int[arg]; // Fill [0,1,2,3,4,...] for( int i=0; i<ary#; i++ ) @@ -323,9 +324,10 @@ for( int i=0; i<ary#; i++ ) for( int i=0; i<ary#-1; i++ ) ary[i+1] += ary[i]; return ary[1] * 1000 + ary[3]; // 1 * 1000 + 6 +} """; testCPU(src,"x86_64_v2", "SystemV",-1,"return (add,.[],(muli,.[]));"); - testCPU(src,"riscv" , "SystemV",9,"return (add,.[],(mul,.[],1000));"); + testCPU(src,"riscv" , "SystemV",7,"return (add,.[],(mul,.[],1000));"); testCPU(src,"arm" , "SystemV",13,"return (add,.[],(mul,.[],1000));"); } @@ -430,6 +432,7 @@ val hashCode = { !String self -> @Test public void testLoop2() { String src = """ +{ // Local SSA regression; file-level bindings are class fields. int i = 0; while(true) { i += 1; @@ -439,6 +442,7 @@ while(true) { continue; } return i; +} """; testCPU(src,"x86_64_v2", "win64" ,0,"return (!=0)(sari,(shli,(inc,Phi(Loop,0,Phi(Region,(!=0),(!=0),0)))));"); testCPU(src,"riscv" , "SystemV",0,"return (!=0)( ( ( Phi(Loop,0,Phi(Region,(!=0),(!=0),0)) + #1 ) << #32 ) >> #1056 );"); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java index 8fb781f9..8115747b 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter23Test.java @@ -226,6 +226,7 @@ return (x == 0 && y == 1 && z==-1) && switch && g @Test public void testFuncCall() throws IOException { String src = """ +{ // Local SSA regression; file-level bindings are class fields. int a = 1; int b = 1; var sq_noInline = { int x -> @@ -234,8 +235,9 @@ var sq_noInline = { int x -> return (a && sq_noInline(0)) ? 1 // Error : 0; // Expected +} """; - TestC.runSF( src, "and3", "", 2); + TestC.runSF( src, "and3", "", 0); // Evaluate on RISC5 emulator EvalRisc5 R5 = TestRisc5.build( src, "and3", 0, 2, false); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java b/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java index f4c4f12f..93eb35ff 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/Chapter24Test.java @@ -99,6 +99,7 @@ return (10 < something_specific < 20) @Test public void testStack3() throws IOException { String src =""" +{ // Local SSA regression; file-level bindings are class fields. var sq_noInline = { int x -> x*x; }; @@ -106,6 +107,7 @@ int score = 4; return (sq_noInline(2) <= score < sq_noInline(3)) ? 0 // Expected : 1; // Error +} """; TestC.runSF( src, "stacked_r_3", "",0); diff --git a/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java b/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java index 51ed10c6..ba8c721e 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/GlobalAssignmentTest.java @@ -37,8 +37,9 @@ public class GlobalAssignmentTest { val constructed=new Writer(13); if( value!=13 || constructed.seen!=13 ) return 8; val initialized=new InitWriter; - // Default expressions run at declaration time, not per instance. - if( value!=13 || initialized.seen!=17 ) return 9; + // Default expressions run in the instance initializer, including + // their writes to class fields. + if( value!=17 || initialized.seen!=17 ) return 9; return 0; }; return main(); @@ -46,7 +47,29 @@ public class GlobalAssignmentTest { @Test public void storesGlobalMemory() throws Exception { assertEquals("0",Eval2.eval(new CodeGen(SOURCE).driver(CodeGen.Phase.TypeCheck),0)); - TestC.runSF(SOURCE,"global_assignment","",-1); + // The native entry calls main itself, after initializing the class. + TestC.runSF(SOURCE.replace("return main();",""),"global_assignment","",-1); + } + + @Test public void initializerHelpersShareMemory() throws Exception { + String src=""" + int value=7; + val read_noInline={ -> value; }; + val write_noInline={ int n -> value=n; return value; }; + int first=read_noInline(); + value=9; + int second=read_noInline(); + int returned=write_noInline(11); + int third=value; + if( first!=7 || second!=9 || returned!=11 || third!=11 ) return 1; + for( int i=0; i<3; i++ ) { + value+=2; + if( read_noInline()!=13+2*i ) return 2; + } + return value!=17; + """; + assertEquals("0",Eval2.eval(new CodeGen(src).driver(CodeGen.Phase.TypeCheck),0)); + TestC.runSF(src,"initializer_helpers","",-1); } @Test public void rejectsFinalGlobal() { diff --git a/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java b/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java index be20b41d..f7dd0d0b 100644 --- a/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java +++ b/chapter33/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java @@ -10,6 +10,21 @@ import org.junit.Test; import static org.junit.Assert.*; public class SeparateCompilationTest { + @Test public void testGlobalReadAfterImportedInitializer() throws Exception { + Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"global-read-"); + var paths=new Ary<>(new String[]{lib.toString()}); + new CodeGen(null,lib.toString(),paths,"Library", + "val number_noInline={ ->7; };",123,true,TypeInteger.BOT) + .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false); + CodeGen code=new CodeGen(null,lib.toString(),paths,"Client",""" + var value=Library.number_noInline(); + val read_noInline={ ->value; }; + value=4294967297; + return read_noInline(); + """,123,true,TypeInteger.BOT).driver(CodeGen.Phase.TypeCheck); + assertEquals("4294967297",Eval2.eval(code,0)); + } + @Test public void testInferredImportedFieldStoreWidth() throws Exception { Path lib=Files.createTempDirectory(Files.createDirectories(Path.of("build/objs/separate")),"inferred-store-"); new CodeGen(null,lib.toString(),null,"Library", diff --git a/skills/chapter25-codex-notes.md b/skills/chapter25-codex-notes.md index 08bfa885..62f9a4e7 100644 --- a/skills/chapter25-codex-notes.md +++ b/skills/chapter25-codex-notes.md @@ -115,7 +115,11 @@ Useful implementation facts: Keep arithmetic compact, but space assignments, compound assignments, and relational operators. Preserve deliberate column alignment above other spacing -rules. Time values use `_ms`/`_msec` suffixes; timer IDs have a smaller unsigned +rules. Align parallel statements into columns so their similarities and +differences stand out (Cliff's 2-D or rectangular coding). For example, pad +`trueExits` by one space to align its assignment and RHS with `falseExits`. +Always parenthesize groups when an expression mixes `&&` and `||`; never rely +on their implicit precedence. Time values use `_ms`/`_msec` suffixes; timer IDs have a smaller unsigned type. Prefer named bounds and products of time units to large magic numbers. Build and test from the chapter directory using the existing Java harness; |
