summaryrefslogtreecommitdiff
path: root/src/main/java/com
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/com')
-rw-r--r--src/main/java/com/seaofnodes/simple/README.md2
-rw-r--r--src/main/java/com/seaofnodes/simple/codegen/CodeGen.java2
-rw-r--r--src/main/java/com/seaofnodes/simple/codegen/IFG.java96
-rw-r--r--src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java17
-rw-r--r--src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java7
-rw-r--r--src/main/java/com/seaofnodes/simple/codegen/Serialize.java33
-rw-r--r--src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java12
-rw-r--r--src/main/java/com/seaofnodes/simple/node/CallNode.java20
-rw-r--r--src/main/java/com/seaofnodes/simple/node/IfNode.java4
-rw-r--r--src/main/java/com/seaofnodes/simple/node/LoopNode.java4
-rw-r--r--src/main/java/com/seaofnodes/simple/node/MemMergeNode.java117
-rw-r--r--src/main/java/com/seaofnodes/simple/node/PhiNode.java20
-rw-r--r--src/main/java/com/seaofnodes/simple/node/RegionNode.java7
-rw-r--r--src/main/java/com/seaofnodes/simple/node/SummaryNode.java15
-rw-r--r--src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java7
-rw-r--r--src/main/java/com/seaofnodes/simple/parser/README.md2
-rw-r--r--src/main/java/com/seaofnodes/simple/parser/package-info.java2
-rw-r--r--src/main/java/com/seaofnodes/simple/type/Type.java12
-rw-r--r--src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java5
-rw-r--r--src/main/java/com/seaofnodes/simple/type/TypeStruct.java8
-rw-r--r--src/main/java/com/seaofnodes/simple/util/BAOS.java45
21 files changed, 280 insertions, 157 deletions
diff --git a/src/main/java/com/seaofnodes/simple/README.md b/src/main/java/com/seaofnodes/simple/README.md
index a8916aa8..cb5fbdd7 100644
--- a/src/main/java/com/seaofnodes/simple/README.md
+++ b/src/main/java/com/seaofnodes/simple/README.md
@@ -2,7 +2,7 @@
| Directory | Contents |
| --- | --- |
-| `parser/` | Recursive-descent grammar routines, lexing, name resolution, and construction of the initial IR. `Var` describes a lexical binding. See the [grammar map](../../../../../../docs/chapter31/31-grammar.md). |
+| `parser/` | Recursive-descent grammar routines, lexing, name resolution, and construction of the initial IR. `Var` describes a lexical binding. See the [grammar map](../../../../../../docs/chapter32/32-grammar.md). |
| `node/` | Sea-of-Nodes IR nodes: graph edges, type computation, and local peephole rewrites. |
| `node/cpus/` | Machine-specific nodes and instruction selection support for `arm`, `riscv`, and `x86_64_v2`. |
| `codegen/` | Compilation driver and passes: module loading, optimization, scheduling, register allocation, serialization, and machine-code emission. `IterPeeps` runs the peephole worklist. |
diff --git a/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java b/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
index 8618b47b..51a6a197 100644
--- a/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
+++ b/src/main/java/com/seaofnodes/simple/codegen/CodeGen.java
@@ -51,7 +51,7 @@ public class CodeGen {
// -Dsimple.assert.expensive=0 disables these checks
// -Dsimple.assert.expensive=1 checks every step
// -Dsimple.assert.expensive=N checks once every 1<<N steps
- private static final int EXPENSIVE_ASSERT_LOG = Integer.getInteger("simple.assert.expensive",8);
+ private static final int EXPENSIVE_ASSERT_LOG = Integer.getInteger("simple.assert.expensive",10);
public static boolean expensiveAssert() { return EXPENSIVE_ASSERT_LOG > 0; }
public static boolean expensiveAssert( int trip ) {
if( EXPENSIVE_ASSERT_LOG <= 0 ) return false;
diff --git a/src/main/java/com/seaofnodes/simple/codegen/IFG.java b/src/main/java/com/seaofnodes/simple/codegen/IFG.java
index 6ad7c0ad..a027263f 100644
--- a/src/main/java/com/seaofnodes/simple/codegen/IFG.java
+++ b/src/main/java/com/seaofnodes/simple/codegen/IFG.java
@@ -8,18 +8,20 @@ import java.util.BitSet;
import java.util.IdentityHashMap;
// Interference Graph
-abstract public class IFG {
+public class IFG {
// Interference Graph Support
+ // Scratch for one function, reused across its spill retries.
// Map from a Basic Block to Live-Out: {a map from a Live Range to a Def}
- private static final IdentityHashMap<CFGNode,IdentityHashMap<LRG,Node>> BBOUTS = new IdentityHashMap<>();
- static void resetBBLiveOut() {
- for( IdentityHashMap<LRG,Node> bbout : BBOUTS.values() )
+ private final IdentityHashMap<CFGNode,IdentityHashMap<LRG,Node>> _bbouts = new IdentityHashMap<>();
+ private void resetBBLiveOut() {
+ for( IdentityHashMap<LRG,Node> bbout : _bbouts.values() )
bbout.clear();
}
- static final IdentityHashMap<LRG,Node> TMP = new IdentityHashMap<>();
+ private final IdentityHashMap<LRG,Node> _tmp = new IdentityHashMap<>();
- // Inteference Graph: Array of Bitsets
+ // Interference Graph: Array of Bitsets. Reuse capacity across functions;
+ // these contain only live-range numbers, not references to the graph.
static final Ary<BitSet> IFG = new Ary<>(BitSet.class);
static void resetIFG() {
for( BitSet bs : IFG )
@@ -42,10 +44,10 @@ abstract public class IFG {
}
- private static final Ary<CFGNode> WORK = new Ary<>(CFGNode.class);
- static void pushWork(CFGNode bb) {
- if( WORK.find(bb) == -1 )
- WORK.push(bb);
+ private final Ary<CFGNode> _work = new Ary<>(CFGNode.class);
+ private void pushWork(CFGNode bb) {
+ if( _work.find(bb) == -1 )
+ _work.push(bb);
}
// ------------------------------------------------------------------------
@@ -65,20 +67,20 @@ abstract public class IFG {
// - At block head, "push" the new live-out to prior blocks.
// - - If they pick up new live-outs, put them on the worklist.
- public static boolean build( int round, RegAlloc alloc ) {
+ public boolean build( int round, RegAlloc alloc ) {
// Reset all to empty
resetBBLiveOut();
resetIFG();
- WORK.clear();
+ _work.clear();
// Last block has nothing live out
for( CFGNode bb : alloc._cfg )
if( bb.blockHead())
- WORK.push( bb );
+ _work.push( bb );
// Process blocks until no more changes
- while( !WORK.isEmpty() )
- do_block(round,alloc,WORK.pop());
+ while( !_work.isEmpty() )
+ do_block(round,alloc,_work.pop());
if( alloc.success() )
convert2DAdjacency(alloc);
@@ -86,12 +88,12 @@ abstract public class IFG {
}
// Walk one block backwards, compute live-in from live-out, and build IFG
- static void do_block( int round, RegAlloc alloc, CFGNode bb ) {
+ private void do_block( int round, RegAlloc alloc, CFGNode bb ) {
assert bb.blockHead();
- IdentityHashMap<LRG,Node> live_out = BBOUTS.get(bb);
- TMP.clear();
+ IdentityHashMap<LRG,Node> live_out = _bbouts.get(bb);
+ _tmp.clear();
if( live_out != null )
- TMP.putAll(live_out); // Copy bits to temp
+ _tmp.putAll(live_out); // Copy bits to temp
// A backwards walk over instructions in the basic block
for( int inum = bb.nOuts()-1; inum >= 0; inum-- ) {
@@ -118,14 +120,14 @@ abstract public class IFG {
mergeLiveOut(alloc,bb,0);
}
- private static void do_node(RegAlloc alloc, Node n) {
+ private void do_node(RegAlloc alloc, Node n) {
// Defining means killing live LRG
LRG lrg = alloc.lrg(n);
if( lrg != null ) {
// Check for def-side self-conflict live ranges. These must split,
// and only happens during the first round a particular LRG splits.
selfConflict(alloc,n,lrg);
- TMP.remove(lrg); // Kill def
+ _tmp.remove(lrg); // Kill def
}
// Phis use and define the same live range, i.e. these LRGs already
@@ -141,7 +143,7 @@ abstract public class IFG {
// Interfere n with all live
if( lrg!=null ) {
// Interfere n with all live
- for( LRG tlrg : TMP.keySet() ) {
+ for( LRG tlrg : _tmp.keySet() ) {
assert tlrg.leader();
// Skip self
if( lrg != tlrg &&
@@ -177,7 +179,7 @@ abstract public class IFG {
selfConflict(alloc,def,lrg1);
// All operands are live together, regardless of their input order.
- TMP.put(lrg1,def);
+ _tmp.put(lrg1,def);
}
// Check fixed-register uses after gathering every operand. An indirect
@@ -191,9 +193,9 @@ abstract public class IFG {
RegMask ni_mask = m.regmap(i);
if( ni_mask!=null && ni_mask.size1() ) { // Must-use single register
// Search all current live
- for( LRG tlrg : TMP.keySet() ) {
+ for( LRG tlrg : _tmp.keySet() ) {
assert tlrg.leader();
- Node live = TMP.get(tlrg);
+ Node live = _tmp.get(tlrg);
if( live != def && live instanceof MachNode lmach && lmach.outregmap().overlap(ni_mask) ) {
// Deny the register, since it absolutely must be used here
if( !tlrg.clr(ni_mask.firstReg()) )
@@ -210,15 +212,15 @@ abstract public class IFG {
// Single-register defines *must* have their register; other live ranges
// *must* avoid this register, so instead of interfering we remove the
// single register from the other rmask.
- private static void kills( RegAlloc alloc, MachNode m ) {
+ private void kills( RegAlloc alloc, MachNode m ) {
RegMask killMask = m.killmap();
if( killMask==null ) return;
// Kill registers with all live
- for( LRG tlrg : TMP.keySet() ) {
+ for( LRG tlrg : _tmp.keySet() ) {
assert tlrg.leader();
// Always, tlrg cannot use kills
if( tlrg._mask.overlap(killMask) ) {
- Node live = TMP.get(tlrg);
+ Node live = _tmp.get(tlrg);
// Disallow clone-ables from living across killed registers.
// Fail them and let splitting re-clone closer to the target use.
if( live instanceof MachNode mach && mach.isClone() )
@@ -231,8 +233,8 @@ abstract public class IFG {
// Check for self-conflict live ranges. These must split, and only happens
// during the first round a particular LRG splits.
- private static void selfConflict(RegAlloc alloc, Node n, LRG lrg) {
- selfConflict(alloc,n,lrg,TMP.get(lrg));
+ private void selfConflict(RegAlloc alloc, Node n, LRG lrg) {
+ selfConflict(alloc,n,lrg,_tmp.get(lrg));
}
private static void selfConflict(RegAlloc alloc, Node n, LRG lrg, Node prior) {
if( prior!=null && prior != n ) {
@@ -242,17 +244,17 @@ abstract public class IFG {
}
}
- // Merge TMP into bb's live-out set; if changes put bb on WORK
- private static void mergeLiveOut( RegAlloc alloc, CFGNode priorbb, int i ) {
+ // Merge _tmp into bb's live-out set; if changes put bb on _work
+ private void mergeLiveOut( RegAlloc alloc, CFGNode priorbb, int i ) {
CFGNode bb = priorbb.cfg(i);
if( bb == null ) return; // Start has no prior
while( !bb.blockHead() ) bb = bb.cfg0();
// Lazy get live-out set for bb
- IdentityHashMap<LRG, Node> lrgs = BBOUTS.computeIfAbsent( bb, k -> new IdentityHashMap<>() );
+ IdentityHashMap<LRG, Node> lrgs = _bbouts.computeIfAbsent( bb, k -> new IdentityHashMap<>() );
- for( LRG lrg : TMP.keySet() ) {
- Node def = TMP.get(lrg);
+ for( LRG lrg : _tmp.keySet() ) {
+ Node def = _tmp.get(lrg);
// Effective def comes from phi input from prior block
if( def instanceof PhiNode phi && phi.cfg0()==priorbb ) {
assert i!=0;
@@ -306,6 +308,9 @@ abstract public class IFG {
// If there's no spare color we'll have to spill this at-risk live range.
public static boolean color(int round, RegAlloc alloc) {
+ // Coalescing is finished; splitting may change this area next round.
+ FunNode fun = alloc._cfg.at(0).fun();
+ int functionArea = functionArea(fun,alloc);
int maxlrg = alloc._LRGS.length, nlrgs=0;
for( int i=1; i<maxlrg; i++ )
if( alloc._LRGS[i] != null )
@@ -325,6 +330,7 @@ abstract public class IFG {
for( int i=0, j=0; i<maxlrg; i++ ) {
LRG lrg = alloc._LRGS[i];
if( lrg==null ) continue; // Unified lrgs are null here
+ assert lrg._fun==fun;
color_stack[j++] = lrg;
if( lrg.lowDegree() ) swap(color_stack, swork++, j-1);
}
@@ -332,7 +338,7 @@ abstract public class IFG {
// Pull all lrgs from IFG, in trivial order if possible
while( sptr < color_stack.length ) {
// Swap best color up front
- pickColor(color_stack,sptr,swork,alloc);
+ pickColor(color_stack,sptr,swork,functionArea);
// Pick a trivial lrg, and (temporarily) remove from the IFG.
LRG lrg = color_stack[sptr++];
@@ -388,10 +394,10 @@ abstract public class IFG {
}
// Pick LRG from color stack
- private static void pickColor(LRG[] color_stack, int sptr, int swork, RegAlloc alloc) {
+ private static void pickColor(LRG[] color_stack, int sptr, int swork, int functionArea) {
// Out of trivial colorable, pick an at-risk to pull
if( sptr==swork )
- swap(color_stack,sptr,pickRisky(color_stack,sptr,alloc));
+ swap(color_stack,sptr,pickRisky(color_stack,sptr,functionArea));
// When coloring, we'd like to give more choices; so when coloring we'd
// like to see the single-def first (since no choices anyway), then
// non-split related (so more live ranges get colored), then
@@ -426,12 +432,12 @@ abstract public class IFG {
// Pick a live range that hasn't already spilled, or has a single-def-
// single-use that are not adjacent.
- private static int pickRisky( LRG[] color_stack, int sptr, RegAlloc alloc ) {
+ private static int pickRisky( LRG[] color_stack, int sptr, int functionArea ) {
int best=sptr;
- int bestScore = pickRiskyScore(color_stack[best],alloc);
+ int bestScore = pickRiskyScore(color_stack[best],functionArea);
for( int i=sptr+1; i<color_stack.length; i++ ) {
if( bestScore == 1000000 ) return best; // Already max score
- int iScore = pickRiskyScore(color_stack[i],alloc);
+ int iScore = pickRiskyScore(color_stack[i],functionArea);
if( iScore > bestScore )
{ best = i; bestScore = iScore; }
}
@@ -446,16 +452,16 @@ abstract public class IFG {
//
// Picking a live range that is very close to coloring might allow it to
// color despite being risky.
- private static int pickRiskyScore( LRG lrg, RegAlloc alloc ) {
+ private static int pickRiskyScore( LRG lrg, int functionArea ) {
// Callee-save live ranges cover the whole function and are cheap to
// split. Rank scheduled area recovered against the loop-scaled cost
// of the def- and use-side moves.
if( lrg._machDef instanceof CalleeSaveNode )
- return areaScore(functionArea(lrg._fun,alloc),
+ return areaScore(functionArea,
splitCost((Node)lrg._machDef,(Node)lrg._machUse));
if( lrg._splitDef != null && lrg._splitDef. in(1) instanceof CalleeSaveNode &&
lrg._splitUse != null && lrg._splitUse.out(0) instanceof ReturnNode )
- return areaScore(functionArea(lrg._fun,alloc),
+ return areaScore(functionArea,
splitCost(lrg._splitDef,lrg._splitUse));
// Pick single-def clonables that are not right next to their single-use.
@@ -465,7 +471,7 @@ abstract public class IFG {
Node use = ((Node)lrg._machUse);
CFGNode cfg = def.cfg0();
int area = cfg != use.cfg0()
- ? functionArea(lrg._fun,alloc)
+ ? functionArea
: cfg._outputs.find(use)-cfg._outputs.find(def)-1;
// A single-use function address can move next to its use without
// adding an instruction. Prefer that to saving a callee-save
diff --git a/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java b/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
index f4acb729..fe935a69 100644
--- a/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
+++ b/src/main/java/com/seaofnodes/simple/codegen/IterPeeps.java
@@ -95,6 +95,9 @@ public class IterPeeps {
code.addAll(defer);
defer.clear();
}
+ // Check the completed fixed point, not every intermediate inline batch.
+ // Periodic progress checks still verify scheduling during the run.
+ assert !CodeGen.expensiveAssert(0) || schedulableUses(code);
}
// Run all the code-reduction and type-lifting peeps as possible
@@ -122,7 +125,13 @@ public class IterPeeps {
// A self-returning peephole can have rewritten its input
// edges. The new defs gained a user and may have
// backwards, user-sensitive peepholes of their own.
- for( Node z : x._inputs ) _work.push(z);
+ boolean edited = x!=n || x.isUnlocked();
+ for( Node z : x._inputs )
+ // A type-only update adds no users. A stable memory
+ // Phi has no backwards rewrite based on user types.
+ // Keep first-use and edited/unprocessed Phis queued.
+ if( edited || !(z instanceof MemPhiNode) || z.nOuts()<=1 || z.isUnlocked() )
+ _work.push(z);
// If the result is not self, revisit all inputs (because
// there's a new user), and replace in the graph.
if( x != n ) {
@@ -143,8 +152,6 @@ public class IterPeeps {
}
if( obs != null ) obs.after(n, x!=null ? x : unused ? n : null, true);
}
- assert !CodeGen.expensiveAssert(0) || schedulableUses(code);
-
}
// Visit ALL nodes and confirm the invariant:
@@ -236,7 +243,9 @@ public class IterPeeps {
}
return found;
}
- return CFGNode.safeCFG(use);
+ // A memory op can execute after its control (e.g. a range check).
+ // Like schedEarly, include its data inputs before constraining its defs.
+ return use instanceof MemOpNode ? CFGNode.earlyCFG(use,earlyCache,VISIT) : CFGNode.safeCFG(use);
}
private static String badSchedule(Node n, CFGNode early, CFGNode lca) {
diff --git a/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java b/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
index 303fd355..c3be4b71 100644
--- a/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
+++ b/src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java
@@ -213,8 +213,9 @@ public class RegAlloc {
}
private void allocateFunction() {
+ IFG ifg = new IFG();
_deferredLoopSelf.clear();
- for( byte round=0; !graphColor(round); round++ ) {
+ for( byte round=0; !graphColor(round,ifg); round++ ) {
split(round);
if( round >= 10 ) {
FunNode fun = _cfg.at(0).fun();
@@ -281,7 +282,7 @@ public class RegAlloc {
return cfg==null ? null : cfg.fun();
}
- private boolean graphColor(byte round) {
+ private boolean graphColor(byte round, IFG ifg) {
_failed.clear();
_lrgs.clear();
_lrg_num = 1;
@@ -291,7 +292,7 @@ public class RegAlloc {
// Build Live Ranges
BuildLRG.run(round,this) && // if no hard register conflicts
// Build Interference Graph
- IFG.build(round,this) && // If no self conflicts or uncolorable
+ ifg.build(round,this) && // If no self conflicts or uncolorable
// Conservative coalesce copies
Coalesce.coalesce(round,this) &&
// Color attempt
diff --git a/src/main/java/com/seaofnodes/simple/codegen/Serialize.java b/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
index b168c4af..9c43e029 100644
--- a/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
+++ b/src/main/java/com/seaofnodes/simple/codegen/Serialize.java
@@ -103,8 +103,10 @@ public class Serialize {
Type startType = TypeTuple.make(Type.CONTROL,stopType.mem(),((StartNode)nodes.at(0)).arg());
BAOS baos = new BAOS();
- // A - Print the C0DE header. The format is not versioned yet.
- baos.write('C').write('0').write('D').write('E');
+ // 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.
+ baos.write('C').write('0').write('D').write('2');
// Count unique Types
var types = new HashMap<Type,Integer>();
@@ -265,8 +267,11 @@ public class Serialize {
}
// Write out the input indices packed.
for( Node n : nodes ) {
- for( int j=0; j<n.nIns(); j++ ) {
+ int count = n.nIns();
+ for( int j=0; j<count; j++ ) {
if( !writeInput(n,j,anodes) ) continue;
+ if( n instanceof MemMergeNode mem && j>=2 )
+ baos.packed2(mem.aliasAt(j));
Node def = n.in(j);
Integer idx = def==null ? Integer.valueOf(0) : anodes.get(def);
// Imported function constants retain their symbol, not a body.
@@ -330,7 +335,7 @@ public class Serialize {
Type.TAGOFFS();
// A - Read a header
- if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='E' )
+ if( bais.read()!='C' || bais.read()!='0' || bais.read()!='D' || bais.read()!='2' )
throw new IllegalArgumentException("Unsupported serialized IR format; rebuild the object file");
// B - Packed read of #strings, then strings
@@ -363,7 +368,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() != 'E' )
+ if( bais.read() != 'C' || bais.read() != '0' || bais.read() != 'D' || bais.read() != '2' )
throw new IllegalArgumentException( "Unsupported serialized IR format; rebuild the object file" );
// B - Packed read of #strings, then strings
@@ -500,19 +505,17 @@ public class Serialize {
// Node edges
for( Node n : nodes ) {
- int len = n.nIns();
+ int len = n instanceof MemMergeNode mem ? mem.readSize() : n.nIns();
for( int i = 0; i<len; i++ ) {
+ int fileAlias = n instanceof MemMergeNode && i>=2 ? bais.packed2() : 0;
int idx = bais.packed2();
Node def = idx==0 ? null : nodes.at(idx-1);
- // MemMerge precise aliases are encoded by their input slot.
- // Remap populated file-local slots into this compilation's
- // local alias numbering; null holes carry no identity.
- int local = i;
- if( n instanceof MemMergeNode && i >= GlobalBits.RESERVED ) {
- if( def == null ) continue;
- local = aliases.map(fileAliases,i);
- }
- n.setDefX(local,def);
+ // Remap only explicit slices; omitted aliases use the default.
+ if( n instanceof MemMergeNode mem && i>=2 ) {
+ if( def==null ) continue;
+ int alias = aliases.map(fileAliases,fileAlias);
+ mem.alias(alias,def);
+ } else n.setDefX(i,def);
// Call's output[0] is always the CallEnd
if( n instanceof CallEndNode cend && i==0 ) {
var outs = cend.call()._outputs;
diff --git a/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java b/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
index b49163e7..f4d1e195 100644
--- a/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/BulkMemPhiNode.java
@@ -118,7 +118,7 @@ public class BulkMemPhiNode extends PhiNode {
} else if( m instanceof MemMergeNode mmm &&
mmm.in(1) instanceof BulkMemPhiNode bulk &&
bulk._aliases.get(alias) &&
- (alias >= mmm.nIns() || mmm.in(alias)==null) )
+ mmm.explicitAlias(alias)==null )
return false;
return true;
}
@@ -187,11 +187,9 @@ public class BulkMemPhiNode extends PhiNode {
// First explicit MemMerge slice still covered by this Phi. A user's slice
// may point to this Phi after a precise Phi folds; splitting is still valid.
private int missingAlias( MemMergeNode mmm ) {
- for( int alias=2; alias<mmm.nIns(); alias++ )
- if( mmm.in(alias)!=null &&
- mmm.alias(alias)!=mmm.in(1) &&
- !_aliases.get(alias) )
- return alias;
+ for( int i=2; i<mmm.nIns(); i++ )
+ if( mmm.in(i)!=null && mmm.in(i)!=mmm.in(1) && !_aliases.get(mmm.aliasAt(i)) )
+ return mmm.aliasAt(i);
return 0;
}
@@ -310,7 +308,7 @@ public class BulkMemPhiNode extends PhiNode {
static boolean checkMerge(MemMergeNode mmm) {
if( !(mmm.in(1) instanceof BulkMemPhiNode bulk) ) return true;
for( int alias = bulk._aliases.nextSetBit(0); alias >= 0; alias = bulk._aliases.nextSetBit(alias+1) )
- if( alias >= mmm.nIns() || mmm.in(alias)==null )
+ if( mmm.explicitAlias(alias)==null )
return false;
return true;
}
diff --git a/src/main/java/com/seaofnodes/simple/node/CallNode.java b/src/main/java/com/seaofnodes/simple/node/CallNode.java
index 9030d43d..5506621b 100644
--- a/src/main/java/com/seaofnodes/simple/node/CallNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/CallNode.java
@@ -102,10 +102,13 @@ public class CallNode extends CFGNode {
if( !external() ) return TypeMem.START;
Type input = dep.addDepForwards(mem())._type;
TypeMem escaped = input instanceof TypeMem m ? m : input.isHigh() ? TypeMem.TOP : TypeMem.BOT;
- TypeMem outside = CodeGen.CODE._start.outside(dep);
- // A class receiver belongs to the callee; the caller does not expose its class.
- for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ )
- escaped = escaped.escapesFrom(dep.addDepForwards(arg(i))._type,outside);
+ // The class-receiver slot is absent from the ABI. The callee supplies
+ // its own singleton, so passing a callback does not expose our class.
+ for( int i = tfp.nargs()>0 && tfp.arg(0)==TypePtr.PTR ? 3 : 2; i<nIns()-1; i++ ) {
+ Type arg = dep.addDepForwards(arg(i))._type;
+ TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(dep) : TypeMem.BOT;
+ escaped = escaped.escapesFrom(arg,outside);
+ }
return TypeMem.make(1,Type.BOTTOM,false,false,false,escaped._escFs,escaped._escAs);
}
@@ -182,7 +185,10 @@ public class CallNode extends CFGNode {
CodeGen.CODE.add(fun).addDef(this);
for( Node use : fun._outputs )
if( use instanceof ParmNode parm ) {
- // Match the callee's declared receiver view, including forward fields.
+ // A class function's receiver belongs to the callee, even
+ // when a different class or an instance forwards its callback.
+ // Match its declared view: before SCCP, forward fields can
+ // still differ from the completed class layout.
Node def = parm._idx==0 ? ConstantNode.seed(cend()._rpc).peephole()
: parm._idx==2 && fun.sig().arg(0)==TypePtr.PTR
? ConstantNode.seed(parm._declaredType).peephole() : arg(parm._idx);
@@ -214,7 +220,9 @@ public class CallNode extends CFGNode {
assert linked(fun);
for( Node use : fun._outputs )
if( use instanceof ParmNode )
- use.delDef(path);
+ // Removing an argument unlocks the Parm even if its type stays
+ // unchanged. Revisit it without relying on unrelated fanout.
+ CodeGen.CODE.add(use).delDef(path);
fun.delDef(path);
CodeGen.CODE.add(fun);
CallEndNode cend = cend();
diff --git a/src/main/java/com/seaofnodes/simple/node/IfNode.java b/src/main/java/com/seaofnodes/simple/node/IfNode.java
index c83c81d0..ad8de653 100644
--- a/src/main/java/com/seaofnodes/simple/node/IfNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/IfNode.java
@@ -56,7 +56,9 @@ public class IfNode extends CFGNode implements MultiNode {
public Node idealize() {
// Hunt up the immediate dominator tree. If we find an identical if
// test on either the true or false branch, that side wins.
- if( !pred()._type.isHighOrConst() )
+ // Known branches fold through CProj; they need no dominator search
+ // or subscriptions to changes higher up the control flow.
+ if( _type==TypeTuple.IF_BOTH )
for( CFGNode dom = idom(), prior=this; dom!=null; prior = dom, dom = dom.idom() )
if( addDep(dom) instanceof IfNode iff &&
prior instanceof CProjNode prj &&
diff --git a/src/main/java/com/seaofnodes/simple/node/LoopNode.java b/src/main/java/com/seaofnodes/simple/node/LoopNode.java
index c4d55335..2ab76429 100644
--- a/src/main/java/com/seaofnodes/simple/node/LoopNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/LoopNode.java
@@ -60,12 +60,12 @@ 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);
- Node memout = new MemMergeNode();
+ MemMergeNode memout = new MemMergeNode();
memout.addDef(f); // placeholder for control
memout.addDef(top);
for( Node u : _outputs )
if( u instanceof PhiNode phi && phi._type.isa(TypeMem.BOT) )
- memout.addDef(phi);
+ memout.alias(memout.nIns(),phi);
memout.init();
Node ctrl = ret.ctrl(), mem = ret.mem(), expr = ret.expr();
diff --git a/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java b/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
index 19420839..a077e14b 100644
--- a/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/MemMergeNode.java
@@ -8,30 +8,75 @@ import com.seaofnodes.simple.codegen.CodeGen;
import com.seaofnodes.simple.util.BAOS;
import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Utils;
+import com.seaofnodes.simple.util.AryInt;
+import com.seaofnodes.simple.util.IntHashMap;
import java.util.*;
/**
- * Memory Merge - a merge of many aliases into a "fat memory". All aliases
- * are here, but most will be lazy - take the default fat memory.
+ * Memory merge: default bulk memory plus dense inputs for explicit alias slices.
*/
public class MemMergeNode extends Node {
public MemMergeNode( Node ...nodes) { super(nodes); _type = TypeMem.BOT; }
- public MemMergeNode(MemMergeNode mem) { super(mem); }
+ // Inputs 0/1 are control/default; the remaining inputs are dense precise slices.
+ // Keep alias order so graph walks retain the old sparse representation's order.
+ private AryInt _aliases;
+ private IntHashMap _aliasToInput;
+ private int _readSize;
+ // Retain the old sparse extent for fold eligibility, without its holes.
+ private int _aliasLimit=2;
+
+ public MemMergeNode(MemMergeNode mem) { super(mem); copyAliases(mem); _aliasLimit=mem._aliasLimit; }
+
+ private void copyAliases(MemMergeNode mem) {
+ if( mem._aliases==null ) return;
+ _aliases = new AryInt().addAll(mem._aliases);
+ _aliasToInput = new IntHashMap(0);
+ reindex();
+ }
+
+ @Override protected Object clone() throws CloneNotSupportedException {
+ MemMergeNode copy = (MemMergeNode)super.clone();
+ copy.copyAliases(this);
+ return copy;
+ }
+
+ public int aliasAt(int input) { return _aliases.at(input-2); }
+
+ // Explicit input, or null when the default supplies this alias.
+ public Node explicitAlias(int alias) {
+ int input = _aliasToInput==null ? 0 : _aliasToInput.get(alias);
+ return input==0 ? null : in(input);
+ }
+
+ // The reader has not wired the dense inputs yet.
+ public int readSize() { return _readSize; }
+
+ private void reindex() {
+ _aliasToInput.clear();
+ for( int i=0; i<_aliases.len(); i++ ) _aliasToInput.put(_aliases.at(i),i+2);
+ }
+
+ private void removeAlias(int input) {
+ setDef(input,null);
+ _inputs.remove(input);
+ _aliases.remove(input-2);
+ reindex();
+ }
@Override public Tag serialTag() { return Tag.MemMerge; }
public void packed( BAOS baos, HashMap<String,Integer> strs, HashMap<Type,Integer> types, IdentityHashMap<Node, Integer> anodes ) {
- // A memory merge always has inputs. Zero escapes a wide alias table,
- // preserving every existing nonzero single-byte count.
- assert nIns()>0;
- baos.packed1(nIns()<=255 ? nIns() : 0);
- if( nIns()>255 ) baos.packed4(nIns());
+ // Keep the extent even if its last precise slice was removed. Edges
+ // are dense: control/default followed by explicit (alias,input) pairs.
+ baos.packed4(_aliasLimit);
+ baos.packed2(nIns());
}
static Node make( BAOS bais ) {
- int count=bais.packed1();
- if( count==0 ) count=bais.packed4();
- Node mem=new MemMergeNode();
- mem.setDefX(count-1,null);
+ int limit=bais.packed4(), count=bais.packed2();
+ assert 2<=count && count<=limit;
+ MemMergeNode mem=new MemMergeNode(null,null);
+ mem._readSize=count;
+ mem._aliasLimit=limit;
return mem;
}
@@ -42,7 +87,7 @@ public class MemMergeNode extends Node {
protected ExprPrinter<Node> _print1(ExprPrinter<Node> p) {
p.p("MEM[ ");
for( int j=2; j<nIns(); j++ ) {
- p.p(j);
+ p.p(aliasAt(j));
p.p(":");
Node n = in(j);
while( n instanceof ScopeNode loop ) {
@@ -93,7 +138,7 @@ public class MemMergeNode extends Node {
TypeMem mem = defmem;
for( int i=2; i<nIns(); i++ ) {
// Has this alias escaped?
- if( XInt.bit(mem._escAs,i) &&
+ if( XInt.bit(mem._escAs,aliasAt(i)) &&
in(i) != null && !in(i)._type.isHigh() ) {
mem = (TypeMem)mem.meet(in(i)._type);
}
@@ -104,11 +149,13 @@ public class MemMergeNode extends Node {
@Override public Node idealize() {
assert nIns() != 0 && in(1)!=null; // Always have a default. if( nIns()==0 ) return null;
- // Fold defaults into the default
- boolean progress=false, allDefault=true;
+ // Preserve the existing fold rule for this storage experiment: every alias
+ // slot must explicitly equal the default. Do not also change which empty
+ // aggregates fold away; that changes optimization order and spill decisions.
+ boolean progress=false, allDefault=nIns()==_aliasLimit;
for( int i=2; i<nIns(); i++ ) {
- if( in(1) == in(i) ) { setDef(i,null); progress=true; }
- else { allDefault=false; }
+ if( in(1)==in(i) ) { removeAlias(i--); progress=true; }
+ else allDefault=false;
}
// If not merging any memory (all memory is just the default)
@@ -124,8 +171,9 @@ public class MemMergeNode extends Node {
for( int i=2; i<mem.nIns(); i++ ) {
if( mem.in(i) != null ) {
// deeper default mem has a non-default
- if( i>=nIns() || in(i)==null )
- setDefX(i,mem.in(i));
+ int alias = mem.aliasAt(i);
+ if( explicitAlias(alias)==null )
+ alias(alias,mem.in(i));
}
}
CodeGen.CODE.add(mem.in(1));
@@ -140,12 +188,33 @@ public class MemMergeNode extends Node {
public Node in( Var v ) { return in(v._idx); }
public Node alias( int alias ) {
- assert !(in(1) instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) &&
- (alias >= nIns() || in(alias)==null));
- return alias < nIns() && in(alias)!=null ? in(alias) : in(1);
+ Node precise = explicitAlias(alias);
+ assert !(in(1) instanceof BulkMemPhiNode bulk && bulk.isSplit(alias) && precise==null);
+ return precise==null ? in(1) : precise;
}
- public Node alias( int alias, Node st ) { return setDefX(alias,st); }
+ public Node alias( int alias, Node st ) {
+ if( alias==1 ) return setDef(1,st);
+ assert alias>1;
+ _aliasLimit=Math.max(_aliasLimit,alias+1);
+ int input = _aliasToInput==null ? 0 : _aliasToInput.get(alias);
+ if( st==null ) {
+ if( input!=0 ) removeAlias(input);
+ return st;
+ }
+ if( input!=0 ) return setDef(input,st);
+ if( _aliases==null ) {
+ _aliases = new AryInt();
+ _aliasToInput = new IntHashMap(0);
+ }
+ int pos = Arrays.binarySearch(_aliases._es,0,_aliases.len(),alias);
+ assert pos<0;
+ pos = -pos-1;
+ _aliases.insert(pos,alias);
+ for( int i=pos; i<_aliases.len(); i++ ) _aliasToInput.put(_aliases.at(i),i+2);
+ insertDef(pos+2,st);
+ return st;
+ }
// Now one-time do a useless-phi removal
void _useless( ) {
diff --git a/src/main/java/com/seaofnodes/simple/node/PhiNode.java b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
index af24a94b..94376086 100644
--- a/src/main/java/com/seaofnodes/simple/node/PhiNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/PhiNode.java
@@ -148,6 +148,9 @@ public class PhiNode extends Node {
return null;
if( !(r.in(3-nzIdx) instanceof CProjNode z && z._idx==1 && z.ctrl()==iff) )
return null;
+ // A rewritten predicate can make this guard match without changing the Phi inputs.
+ addDep(iff);
+ addDep(iff.pred()); // subsume wakes the replaced predicate's dependents.
// Predicate was guarded?
Node n = cast.in(1), tested = null;
while( true ) {
@@ -159,23 +162,23 @@ public class PhiNode extends Node {
return tested!=null && (early==null || early.dominates(r,this)) ? n : null;
}
- // View x<<1 as x+x only while matching mixed Phi arms. Do not
- // expand the graph into Adds that would immediately strength-reduce again.
+ // View x<<1 as x+x when factoring mixed Add/Shl arms. Do not expand the
+ // graph: Add would immediately strength-reduce it again. If all arms are
+ // shifts, keep the ordinary shift factoring (including arbitrary counts).
private Node factoringOp() {
Node op = in(1);
if( doubled(op) )
for( int i=2; i<nIns(); i++ )
- if( in(i) instanceof AddNode add && add._mode==1 ) return in(i);
+ if( in(i) instanceof AddNode add && add._mode==1 ) return add;
return op;
}
private boolean doubled(Node n) {
- return n instanceof ShlNode &&
- addDep(n.in(2))._type instanceof TypeInteger con && con.isConstant() && con.value()==1;
+ return n instanceof ShlNode && addDep(n.in(2))._type==TypeInteger.TRUE;
}
private static Node factoringInput(Node op, Node n, int j) {
- return op instanceof AddNode && !(n instanceof AddNode) ? n.in(1) : n.in(j);
+ return n instanceof ShlNode && op instanceof AddNode ? n.in(1) : n.in(j);
}
// Same op on all Phi paths; all ops have only the Phi as a use.
@@ -197,9 +200,10 @@ public class PhiNode extends Node {
Node busy = null;
for( int i=1; i<nIns(); i++ ) {
Node n = in(i);
+ boolean same = op.getClass()==n.getClass() && op.eq(n);
+ if( !same && op instanceof AddNode add && add._mode==1 ) same = doubled(n);
if( addDep(region().in(i))._type==Type.XCONTROL ||
- !((op.getClass()==n.getClass() && op.eq(n)) || (op instanceof AddNode add && add._mode==1 && doubled(n))) ||
- n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
+ !same || n.nIns()!=op.nIns() || n.in(0)!=null ) return false;
if( n instanceof MemOpNode mem && !mem.canDrop((MemOpNode)op,this) ) return false;
// Moving a Store must remove the old effect, not duplicate it.
// Allow one shared arm: the other arms disappear into the single
diff --git a/src/main/java/com/seaofnodes/simple/node/RegionNode.java b/src/main/java/com/seaofnodes/simple/node/RegionNode.java
index 3ed63862..17126f27 100644
--- a/src/main/java/com/seaofnodes/simple/node/RegionNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/RegionNode.java
@@ -68,6 +68,7 @@ public class RegionNode extends CFGNode {
for( Node use : _outputs ) {
if( use instanceof PhiNode phi ) {
PhiNode phi2 = phi.in(i) instanceof PhiNode phi2x && phi2x.region()==region ? phi2x : null;
+ // New users can require a bulk-memory input to split.
for( int j=1; j<region.nIns(); j++ )
phi.addDef(CodeGen.CODE.add(phi2==null ? phi.in(i) : phi2.in(j)));
CodeGen.CODE.add(phi);
@@ -109,7 +110,11 @@ public class RegionNode extends CFGNode {
nouts = nOuts();
for( int i=0; i<nOuts(); i++ )
if( out(i) instanceof PhiNode phi && phi.nIns()==nIns() ) {
- CodeGen.CODE.addAll(phi.in(path)._outputs);
+ // Removing a constant argument cannot enable a use-count
+ // rewrite in its other users. Shared constants can have
+ // callers throughout the program; only this Phi changed.
+ if( phi.in(path) instanceof ConstantNode ) CodeGen.CODE.add(phi);
+ else CodeGen.CODE.addAll(phi.in(path)._outputs);
CodeGen.CODE.addAll(phi.delDef(path)._outputs);
}
}
diff --git a/src/main/java/com/seaofnodes/simple/node/SummaryNode.java b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
index d0da3250..5b945457 100644
--- a/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
+++ b/src/main/java/com/seaofnodes/simple/node/SummaryNode.java
@@ -26,8 +26,12 @@ public class SummaryNode extends CFGNode implements MultiNode {
// A library summary does not forget escapes already present in the caller.
TypeMem mem = in(1)._type instanceof TypeMem m ? m : in(1)._type.isHigh() ? TypeMem.TOP : TypeMem.BOT;
mem = (TypeMem)mem.meet(_state.mem());
- TypeMem outside = CodeGen.CODE._start.outside(this);
- for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(in(i)._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) {
+ Type arg = in(i)._type;
+ // Only opaque arguments can hide identities supplied by outside code.
+ TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(this) : TypeMem.BOT;
+ mem = mem.escapesFrom(arg,outside);
+ }
return TypeTuple.make(_state.ctl(),mem,_state.ret());
}
@Override public Node idealize() { return null; }
@@ -35,8 +39,11 @@ public class SummaryNode extends CFGNode implements MultiNode {
dep.addDepForwards(this);
if( dep.addDepForwards(in(0))._type.isHigh() ) return TypeMem.START;
TypeMem mem = (TypeMem)_state.mem();
- TypeMem outside = CodeGen.CODE._start.outside(dep);
- for( int i = firstArgument(); i<nIns(); i++ ) mem = mem.escapesFrom(dep.addDepForwards(in(i))._type,outside);
+ for( int i = firstArgument(); i<nIns(); i++ ) {
+ Type arg = dep.addDepForwards(in(i))._type;
+ TypeMem outside = TypeMem.opaque(arg) ? CodeGen.CODE._start.outside(dep) : TypeMem.BOT;
+ mem = mem.escapesFrom(arg,outside);
+ }
return TypeMem.make(1,Type.BOTTOM,false,false,false,mem._escFs,mem._escAs);
}
// A class receiver is supplied by the callee, not exposed by its caller.
diff --git a/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java b/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
index d4714953..9e0d864a 100644
--- a/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
+++ b/src/main/java/com/seaofnodes/simple/node/cpus/x86_64_v2/x86_64_v2.java
@@ -5,7 +5,7 @@ import com.seaofnodes.simple.node.*;
import com.seaofnodes.simple.type.*;
import com.seaofnodes.simple.util.Utils;
import com.seaofnodes.simple.util.Ary;
-import java.util.IdentityHashMap;
+import java.util.BitSet;
public class x86_64_v2 extends Machine {
public x86_64_v2( CodeGen code ) {}
@@ -461,12 +461,13 @@ public class x86_64_v2 extends Machine {
if( load.nOuts()!=1 ) return false;
Ary<Node> writers=load.antiDeps(new Ary<>(Node.class));
if( writers.isEmpty() ) return true;
- var seen=new IdentityHashMap<Node,Boolean>();
+ var seen=new BitSet();
Ary<Node> work=new Ary<>(Node.class);
work.push(value);
while( !work.isEmpty() ) {
Node n=work.pop();
- if( seen.put(n,Boolean.TRUE)!=null ) continue;
+ if( seen.get(n._nid) ) continue;
+ seen.set(n._nid);
if( writers.find(n)!=-1 ) return false;
for( Node def : n._inputs ) if( def!=null ) work.push(def);
}
diff --git a/src/main/java/com/seaofnodes/simple/parser/README.md b/src/main/java/com/seaofnodes/simple/parser/README.md
index 48cf13c8..a474eb17 100644
--- a/src/main/java/com/seaofnodes/simple/parser/README.md
+++ b/src/main/java/com/seaofnodes/simple/parser/README.md
@@ -2,7 +2,7 @@
The parser builds Sea-of-Nodes IR directly. Each component shares the cursor,
active scope, and compilation state through its `Parser P` reference; there is no intermediate
-AST. The [grammar map](../../../../../../../docs/chapter31/31-grammar.md) connects language
+AST. The [grammar map](../../../../../../../docs/chapter32/32-grammar.md) connects language
productions to their entry points.
| File | Responsibility |
diff --git a/src/main/java/com/seaofnodes/simple/parser/package-info.java b/src/main/java/com/seaofnodes/simple/parser/package-info.java
index 73ebec2e..828ac6d9 100644
--- a/src/main/java/com/seaofnodes/simple/parser/package-info.java
+++ b/src/main/java/com/seaofnodes/simple/parser/package-info.java
@@ -7,7 +7,7 @@
* use-side name/field resolution; Allocations, ControlFlow, and Conversions
* contain their shared IR construction. Lexer also supplies location snapshots.
*
- * <p>See {@code chapter31/docs/31-grammar.md} for the production-to-method map.
+ * <p>See {@code chapter32/docs/32-grammar.md} for the production-to-method map.
* Evaluation order and scope lifetimes are explicit: loop updates and declared
* constructor bodies are the two deferred source fragments. There is no AST.
*/
diff --git a/src/main/java/com/seaofnodes/simple/type/Type.java b/src/main/java/com/seaofnodes/simple/type/Type.java
index 2e228494..221de04c 100644
--- a/src/main/java/com/seaofnodes/simple/type/Type.java
+++ b/src/main/java/com/seaofnodes/simple/type/Type.java
@@ -401,10 +401,6 @@ public class Type /*implements Cloneable*/ {
return rez;
}
- // Read-only recursive visits do not *make* cyclic types and so the cleanup
- // is much easier.
- static boolean recurClose(boolean rez) { VISIT.clear(); return rez; }
-
final Type tern() {
if( _terned ) return this;
if( !BITS.get(_uid) ) {
@@ -464,8 +460,9 @@ public class Type /*implements Cloneable*/ {
}
// Strict constant values, things on the lattice centerline.
- // Excludes both high and low values
- public final boolean isConstant() { return recurClose(recurOpen()._isConstant()); }
+ // Excludes both high and low values. Pointers check their own identity,
+ // not their referents, so aggregate checks do not follow type cycles.
+ public final boolean isConstant() { return _isConstant(); }
boolean _isConstant() { return _type==TNIL; }
// Are all reachable struct Fields are final?
@@ -473,7 +470,8 @@ public class Type /*implements Cloneable*/ {
// Otherwise an alias could insert a readonly pointer into a writable slot.
public boolean accessISA(Type dst) { return true; }
- public final boolean isFinal() { return recurClose(recurOpen()._isFinal()); }
+ // Pointer finality comes from its access qualifier, not its referent.
+ public final boolean isFinal() { return _isFinal(); }
boolean _isFinal() { assert is_nokids(); return true; }
public final Type makeRO() {
diff --git a/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java b/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
index 19ec5019..c6f53022 100644
--- a/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
+++ b/src/main/java/com/seaofnodes/simple/type/TypeFunPtr.java
@@ -248,7 +248,7 @@ public class TypeFunPtr extends TypeNil {
@Override int TAGOFF() { return 8; }
@Override public void packed( BAOS baos, HashMap<String,Integer> strs ) {
assert _open; // Open: Passing extra args is fine, and extras ignored.
- if( _nil==2 && nargs()<6 && nfcns() == 1 && fidx() < 64 ) {
+ if( _nil==2 && nargs()<6 && nfcns() == 1 && fidx()<=65535 ) {
baos.write(TAGOFFS[_type] + nargs());
baos.packed2(fidx());
} else {
@@ -259,8 +259,7 @@ public class TypeFunPtr extends TypeNil {
}
static TypeFunPtr packed( int tag, BAOS bais ) {
if( tag < 6 ) {
- int fidx = bais.read();
- assert fidx < 64; // Need a larger fidx space
+ int fidx = bais.packed2();
return malloc((byte)2,true,new Type[tag],null, XInt.make(fidx));
}
byte nil = (byte)(tag==6 ? 2 : 3);
diff --git a/src/main/java/com/seaofnodes/simple/type/TypeStruct.java b/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
index 11ba3cc4..d1586547 100644
--- a/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
+++ b/src/main/java/com/seaofnodes/simple/type/TypeStruct.java
@@ -399,9 +399,7 @@ public class TypeStruct extends Type {
@Override boolean _isConstant() {
assert !_open; // who is asking about constant open structs? if( _open ) return false; // Infinite BOT fields
- assert !VISIT.containsKey(_uid); //expect constants to not include self-cycles. if( VISIT.containsKey(_uid) ) return true; // Cycles assume constant
- VISIT.put(_uid,this);
- // Check all fields for being constant
+ // Check field values; pointers do not recurse into their referents.
for( Field field : _fields )
if( !field._isConstant() )
return false;
@@ -411,9 +409,7 @@ public class TypeStruct extends Type {
// All fields are final
@Override boolean _isFinal() {
if( _open ) return false; // May have more non-final fields
- if( VISIT.containsKey(_uid) ) // Test: been here before?
- return true; // Cycles assume final
- VISIT.put(_uid,this); // Set: don't do this again
+ // Pointer fields check their access qualifier without following cycles.
for( Field fld : _fields )
if( !fld._isFinal() )
return false;
diff --git a/src/main/java/com/seaofnodes/simple/util/BAOS.java b/src/main/java/com/seaofnodes/simple/util/BAOS.java
index 61ce7387..c47d386c 100644
--- a/src/main/java/com/seaofnodes/simple/util/BAOS.java
+++ b/src/main/java/com/seaofnodes/simple/util/BAOS.java
@@ -1,7 +1,8 @@
package com.seaofnodes.simple.util;
-import java.util.HashMap;
+//import java.util.HashMap;
import java.util.Arrays;
+import java.nio.charset.StandardCharsets;
// "ByteArrayOutputStream", and Input Stream and not synchronized and has
// matching pack/unpack strategies.
@@ -96,12 +97,12 @@ public class BAOS {
}
// -----------------------------------------------------------------------
- // Write a packed integer to the BAOS. Track a histogram to make more
- // intelligent choices in the future.
- private static final HashMap<Long,Integer> PACKED_HISTOGRAM = new HashMap<>();
+ // Optional profiling for choosing smaller packed representations. Leave
+ // disabled during normal compilation; re-enable when studying .simple size.
+ //private static final HashMap<Long,Integer> PACKED_HISTOGRAM = new HashMap<>();
private BAOS histo(long x) {
- Integer cnt = PACKED_HISTOGRAM.get(x);
- PACKED_HISTOGRAM.put(x,cnt==null ? 1 : cnt+1);
+ //Integer cnt = PACKED_HISTOGRAM.get(x);
+ //PACKED_HISTOGRAM.put(x,cnt==null ? 1 : cnt+1);
return this;
}
@@ -125,15 +126,29 @@ public class BAOS {
return x==0xFF ? read2() : x;
}
- // Write a packed i32
+ // Signed zigzag varint: -64..63 use one byte, -8192..8191 two,
+ // and the full int range needs at most five. Seven payload bits per byte.
public void packed4(int x) {
- ((-127 <= x && x <= 127 ) ? write(x) : write(-128).write4(x)).histo(x);
+ histo(x);
+ int bits = (x<<1) ^ (x>>31);
+ while( (bits & ~127)!=0 ) {
+ write((bits & 127) | 128);
+ bits >>>= 7;
+ }
+ write(bits);
}
// Read a packed i32
public int packed4() {
- int x = _buf[_len++]; // Signed byte read
- return x== -128 ? read4() : x;
+ int bits=0;
+ for( int shift=0; shift<32; shift+=7 ) {
+ int b = read();
+ if( shift==28 && (b & 0xF0)!=0 )
+ throw new IllegalArgumentException("Packed int overflow");
+ bits |= (b & 127)<<shift;
+ if( (b & 128)==0 ) return (bits>>>1) ^ -(bits & 1);
+ }
+ throw new IllegalArgumentException("Unterminated packed int");
}
// Write a packed i64
@@ -148,14 +163,16 @@ public class BAOS {
}
public void packedS(String s) {
- packed4(s.length());
- for( int i=0; i<s.length(); i++ )
- packed4(s.charAt(i));
+ // Strings are bytes, not signed packed integers. Keep ASCII at one
+ // byte per character and agree on the representation of non-ASCII.
+ byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
+ packed4(utf8.length);
+ write(utf8);
}
public String packedS() {
int len = packed4();
- String s = new String(_buf,_len,len).intern();
+ String s = new String(_buf,_len,len,StandardCharsets.UTF_8).intern();
_len += len;
return s;
}