summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCliff Click <cliffc@acm.org>2026-08-10 11:11:18 -0700
committerCliff Click <cliffc@acm.org>2026-11-16 16:23:52 -0800
commit0b263f550d5e54d050f58f6b315b092944c9eff9 (patch)
treeaff564cf11711c41a6f94f17ffbc480e1b228da1
parent790268f4a1f6122376c34059f1633c1017436363 (diff)
downloadSimple-linear-chapter32.tar.gz
Simple-linear-chapter32.zip
Chapter 32: Compiler Internal Speedupslinear-chapter32linear
Co-authored-by: Hsiang-Ying Fu <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: fuhsnn <66062782+fuhsnn@users.noreply.github.com> Co-authored-by: Symious <14933944+symious@users.noreply.github.com> Co-authored-by: Jun Kawasaki <jun784@gmail.com> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
-rw-r--r--Makefile83
-rw-r--r--README.ja.md2
-rw-r--r--README.md2
-rw-r--r--chapter32.iml (renamed from chapter31.iml)4
-rw-r--r--docs/chapter32/32-grammar.ja.md182
-rw-r--r--docs/chapter32/32-grammar.md275
-rw-r--r--docs/chapter32/README.ja.md43
-rw-r--r--docs/chapter32/README.md212
-rw-r--r--docs/chapter32/examples/A_helloWorld.smp2
-rw-r--r--docs/chapter32/examples/Breakout.smp369
-rw-r--r--docs/chapter32/examples/BubbleSort.smp38
-rw-r--r--docs/chapter32/examples/Capitalize.smp23
-rw-r--r--docs/chapter32/examples/Clock.smp128
-rw-r--r--docs/chapter32/examples/Dijkstra.smp71
-rw-r--r--docs/chapter32/examples/FileIO.smp52
-rw-r--r--docs/chapter32/examples/Graphics.smp26
-rw-r--r--docs/chapter32/examples/README.md119
-rw-r--r--docs/chapter32/examples/TicTacToe.smp132
-rw-r--r--docs/chapter32/examples/TicTacToeGraphical.smp169
-rw-r--r--src/main/c/simple_graphics.c2
-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
-rw-r--r--src/main/smp/sys/audio.md6
-rw-r--r--src/main/smp/sys/draw/README.md4
-rw-r--r--src/main/smp/sys/gfx.md12
-rw-r--r--src/main/smp/sys/time/README.md6
-rw-r--r--src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java28
-rw-r--r--src/test/java/com/seaofnodes/simple/BAOSTest.java58
-rw-r--r--src/test/java/com/seaofnodes/simple/CallEndTest.java24
-rw-r--r--src/test/java/com/seaofnodes/simple/Chapter05Test.java31
-rw-r--r--src/test/java/com/seaofnodes/simple/Chapter10Test.java8
-rw-r--r--src/test/java/com/seaofnodes/simple/Chapter13Test.java4
-rw-r--r--src/test/java/com/seaofnodes/simple/Chapter21Test.java4
-rw-r--r--src/test/java/com/seaofnodes/simple/Chapter23Test.java2
-rw-r--r--src/test/java/com/seaofnodes/simple/EscapeFlowTest.java31
-rw-r--r--src/test/java/com/seaofnodes/simple/MemMergeTest.java83
-rw-r--r--src/test/java/com/seaofnodes/simple/ModTest.java27
-rw-r--r--src/test/java/com/seaofnodes/simple/SchedulingTest.java39
-rw-r--r--src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java36
-rw-r--r--src/test/java/com/seaofnodes/simple/StringFormatTest.java113
-rw-r--r--src/test/java/com/seaofnodes/simple/TestWorkspace.java54
-rw-r--r--src/test/java/com/seaofnodes/simple/TypeTest.java140
-rw-r--r--src/test/java/com/seaofnodes/simple/WorklistTest.java49
-rw-r--r--src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java6
-rw-r--r--src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java20
64 files changed, 2863 insertions, 293 deletions
diff --git a/Makefile b/Makefile
index 6dba57fa..d91f59e0 100644
--- a/Makefile
+++ b/Makefile
@@ -15,9 +15,7 @@ test_raw_sys := 25
# Convert chapter numbers to test files
test_raw0 := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_nums0))
test_raw1 := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_nums1))
-# TimeTest uses sys and compiles a wide library. Keep it out of the catch-all
-# JVM, whose accumulated pooled types can exhaust this snapshot's 16-bit IDs.
-test_sys := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_sys) ) com.seaofnodes.simple.TimeTest
+test_sys := $(patsubst %,com.seaofnodes.simple.Chapter%Test,$(test_raw_sys) )
# All the 'src/test/java' files ending in 'Test'
test_cp0 := $(patsubst $(TST)/$(SIMPLE)/%.java,com.seaofnodes.simple.%,$(wildcard $(TST)/$(SIMPLE)/*Test.java))
# Minus raw0, raw1, alone tests
@@ -27,6 +25,37 @@ test_cp3 := $(filter-out $(test_alone),$(test_cp2))
test_cp4 := $(filter-out com.seaofnodes.simple.Chapter25Test,$(test_cp3))
test_cp := $(filter-out $(test_sys) ,$(test_cp4))
+# Measured groups keep class fixtures together. New tests join group 7 rather
+# than silently falling out of the suite. Each group has private native outputs.
+test_group0 := com.seaofnodes.simple.DrawTest
+test_group1 := com.seaofnodes.simple.GraphicsTest
+test_group2 := $(addprefix com.seaofnodes.simple.,TimeTest MemoryEncodingTest ChainedComparisonTest ParserTest Chapter28bTest)
+test_group3 := $(addprefix com.seaofnodes.simple.,StringFormatTest StaticDataTest PhaseTest FinalConstructionTest PartialReadTest EscapeFlowTest CallEndTest BulkMemPhiTest)
+test_group4 := $(addprefix com.seaofnodes.simple.,BreakoutTest ConvertNodeTest ArithNodeTest MethodAccessTest Int32Test MinusNodeTest ConstructorCompletionTest)
+test_group5 := $(addprefix com.seaofnodes.simple.,TerminalInputTest ParserDiagnosticTest ArrayInitTest MethodFieldsTest ConstantArrayTest BoundaryTest IntegerLiteralTest ConstructionRequirementsTest)
+test_group6 := $(addprefix com.seaofnodes.simple.,AssemblyDumpTest AudioTest MathTest TicTacToeTest ModTest SelectiveLoadingTest FloatComparisonNativeTest SchedulingTest SeparateCompilationTest ConstructionGroupTest CompoundAssignmentTest)
+test_group7 := $(filter-out $(test_group0) $(test_group1) $(test_group2) $(test_group3) $(test_group4) $(test_group5) $(test_group6),$(test_cp))
+test_groups := $(addprefix tests_group,0 1 2 3 4 5 6 7)
+
+# Fast compiler checks retain the full lattice, chapter/backend regressions,
+# fuzzer regression seeds, and focused compiler tests. Library/application and
+# CLI integration remains in `tests`. New compiler tests join sanity group 2.
+sanity_omit := $(addprefix com.seaofnodes.simple.,DrawTest GraphicsTest TimeTest StringFormatTest BreakoutTest TerminalInputTest AudioTest MathTest TicTacToeTest StreamIOTest RuntimeArgsTest NativeExecutionTest ParserDiagnosticTest)
+sanity_cp := $(filter-out $(sanity_omit),$(test_cp))
+sanity_group0 := $(addprefix com.seaofnodes.simple.,ClassInitDependenciesTest ConvertNodeTest ArithNodeTest MemoryEncodingTest ModTest IntrinsicTest AssemblyDumpTest)
+sanity_group1 := $(addprefix com.seaofnodes.simple.,StaticDataTest FloatComparisonNativeTest ArrayInitTest ConstantArrayTest BoundaryTest Int32Test ReceiverTest GlobalAssignmentTest IncrementalBuildTest SeparateCompilationTest)
+sanity_group2 := $(filter-out $(sanity_group0) $(sanity_group1),$(sanity_cp))
+sanity_groups := $(addprefix sanity_group,0 1 2)
+
+# Size each test JVM for a share of the machine, instead of giving every JVM
+# JIT and GC pools sized for all cores. Absolute paths also serve child JVMs
+# launched from a group's private working directory (native Java on Windows).
+TEST_JAVA_OPTS ?= -XX:ActiveProcessorCount=2
+test_path = $(if $(filter Windows_NT,$(OS)),$(shell cygpath -m "$(abspath $(1))"),$(abspath $(1)))
+test_classpath := $(subst $(space),$(SEP),$(foreach path,$(CLZDIR)/main $(libs) $(CLZDIR)/test,$(call test_path,$(path))))
+TEST_JVM = nice java -ea $(TEST_JAVA_OPTS) -cp "$(test_classpath)"
+fuzzer: private JVM = $(TEST_JVM)
+
# Default Simple .o target is build/objs which is where all the test .o's get
# dumped. The default sys search needs to NOT include all the dumped test
# files; move it down into lib/
@@ -98,41 +127,67 @@ tests_nographics:
#######################################################
# Base launch line for JVM tests
+.PHONY: tests_raw0 tests_raw1 tests_alone tests_programs tests_sys $(test_groups) tests_lattice0 tests_lattice1 tests_lattice2 tests_lattice3
# Tests that do NOT need sys.smp
tests_raw0: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(RELEASE_CRT)
@echo "testing " $(test_raw0)
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
- @$(JVM) org.junit.runner.JUnitCore $(test_raw0)
+ @$(TEST_JVM) org.junit.runner.JUnitCore $(test_raw0)
tests_raw1: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag $(RELEASE_CRT)
@echo "testing " $(test_raw1)
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
- @$(JVM) org.junit.runner.JUnitCore $(test_raw1)
+ @$(TEST_JVM) org.junit.runner.JUnitCore $(test_raw1)
# Larger regressions, including BrainFuck's standard-library buffer variant.
-tests_alone: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
- @echo "testing " $(test_alone)
+tests_alone: tests_programs tests_lattice0 tests_lattice1 tests_lattice2 tests_lattice3
+tests_programs: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
+ @echo "testing " $(filter-out com.seaofnodes.simple.TypeTest,$(test_alone))
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
- @$(JVM) org.junit.runner.JUnitCore $(test_alone)
+ @$(TEST_JVM) org.junit.runner.JUnitCore $(filter-out com.seaofnodes.simple.TypeTest,$(test_alone))
+
+# Partition the lattice's outer type loop across processes: type interning and
+# cyclic traversal scratch state are shared mutable data within a JVM. Part 0
+# runs the other TypeTest methods too; direct JUnit/IDE runs still check it all.
+tests_lattice0: $(test_classes)
+ @echo "testing lattice part 0/4 and other type checks"
+ @$(TEST_JVM) -Dsimple.lattice.parts=4 -Dsimple.lattice.part=0 org.junit.runner.JUnitCore com.seaofnodes.simple.TypeTest
+tests_lattice1 tests_lattice2 tests_lattice3: tests_lattice%: $(test_classes)
+ @echo "testing lattice part $*/4"
+ @$(TEST_JVM) -Dsimple.lattice.parts=4 -Dsimple.lattice.part=$* com.seaofnodes.simple.TestRunner TypeTest testLatticeTheory
# Tests that DO need sys.smp
tests_sys: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
@echo "testing " $(test_sys)
@[ -d $(OBJS) ] || mkdir -p $(OBJS)
- @$(JVM) org.junit.runner.JUnitCore $(test_sys)
+ @$(TEST_JVM) org.junit.runner.JUnitCore $(test_sys)
+
+$(test_groups): tests_group%: $(test_classes) $(TEST_SYS) $(RELEASE_SYS) $(RELEASE_CRT)
+ @$(TEST_JVM) com.seaofnodes.simple.TestWorkspace $@ $(CPU_ABI)
+ @echo "testing $@: $(test_group$*)"
+ @cd build/tests/$@ && $(TEST_JVM) org.junit.runner.JUnitCore $(test_group$*)
+
+.PHONY: sanity $(sanity_groups)
+$(sanity_groups): sanity_group%: $(test_classes) $(TEST_SYS) $(RELEASE_SYS) $(RELEASE_CRT)
+ @$(TEST_JVM) com.seaofnodes.simple.TestWorkspace $@ $(CPU_ABI)
+ @echo "testing $@: $(sanity_group$*)"
+ @cd build/tests/$@ && $(TEST_JVM) org.junit.runner.JUnitCore $(sanity_group$*)
+
+sanity: $(sanity_groups) tests_raw0 tests_raw1 fuzzer tests_lattice0 tests_lattice1 tests_lattice2 tests_lattice3
+ @echo "All sanity checks passed"
# One test method (or the whole class when METHOD is omitted).
CLASS ?= Chapter25Test
METHOD ?=
.PHONY: test
test: $(main_classes) $(test_classes) $(RELEASE_SYS) $(RELEASE_CRT)
- @$(JVM) com.seaofnodes.simple.TestRunner "$(CLASS)" "$(METHOD)"
+ @$(TEST_JVM) com.seaofnodes.simple.TestRunner "$(CLASS)" "$(METHOD)"
-tests: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag tests_raw0 tests_raw1 tests_alone tests_sys fuzzer
- @echo "All tests"
- @[ -d $(OBJS) ] || mkdir -p $(OBJS)
- @$(JVM) org.junit.runner.JUnitCore $(test_cp)
+# At -j8, start the remaining chapter cohorts before the short lattice parts
+# so their native links overlap the earlier groups instead of forming a tail.
+tests: $(test_groups) tests_sys fuzzer tests_raw1 tests_raw0 tests_alone
+ @echo "All tests passed"
# Build a Simple jar and release stdlib
diff --git a/README.ja.md b/README.ja.md
index 2cccb6fe..11c56dfd 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -71,7 +71,7 @@ Simple 言語のスタイルは、C または Java のサブセットに倣っã�
* [第29章](docs/chapter29/README.ja.md):技術的負債の整理
* [第30章](docs/chapter30/README.ja.md):テキスト整形と診断
* [第31章](docs/chapter31/README.ja.md):ソフトウェア描画、ゲーム、ライブラリ
-* 第32章:コンパイラ内部の高速化(作業中)
+* [第32章](docs/chapter32/README.ja.md):コンパイラ内部の高速化(作業中)
付録:[ネイティブライブラリ](docs/appendices/native-libraries.md)、
[最適化とバックエンドの調整](docs/appendices/optimizer-tuning.ja.md)。
diff --git a/README.md b/README.md
index d8e4190f..9d09c399 100644
--- a/README.md
+++ b/README.md
@@ -85,7 +85,7 @@ The Simple language is styled after a subset of C or Java.
* [Chapter 29](docs/chapter29/README.md): Tech Debt Cleanup, Partial Objects
* [Chapter 30](docs/chapter30/README.md): Text Formatting and Diagnostics
* [Chapter 31](docs/chapter31/README.md): Software Drawing, Games, and Libraries
-* Chapter 32: Compiler Internal Speedups (work in progress)
+* [Chapter 32](docs/chapter32/README.md): Compiler Internal Speedups (work in progress)
Appendices: [Native libraries](docs/appendices/native-libraries.md),
[optimizer and backend tuning](docs/appendices/optimizer-tuning.md).
diff --git a/chapter31.iml b/chapter32.iml
index f4007a98..a192e0bc 100644
--- a/chapter31.iml
+++ b/chapter32.iml
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="false">
- <output url="file://$MODULE_DIR$/../build/idea/production/chapter31" />
- <output-test url="file://$MODULE_DIR$/../build/idea/test/chapter31" />
+ <output url="file://$MODULE_DIR$/../build/idea/production/chapter32" />
+ <output-test url="file://$MODULE_DIR$/../build/idea/test/chapter32" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
diff --git a/docs/chapter32/32-grammar.ja.md b/docs/chapter32/32-grammar.ja.md
new file mode 100644
index 00000000..227ce6e1
--- /dev/null
+++ b/docs/chapter32/32-grammar.ja.md
@@ -0,0 +1,182 @@
+# 第32章の文法
+
+[English](32-grammar.md) | 日本語
+
+```antlrv4
+grammar SimpleLanguage;
+
+// Name lookup, assignable operands, type compatibility, and access permissions
+// are checked by the compiler in addition to these syntax rules.
+// A file is a compilation unit; its path supplies its namespace.
+// Qualified names resolve nested types and other units without an import keyword.
+program : statement* EOF ;
+
+block : '{' statement* '}' ;
+
+statement
+ : block
+ | returnStatement
+ | ifStatement
+ | whileStatement
+ | forStatement
+ | breakStatement
+ | continueStatement
+ | structDeclaration
+ | declaration ';'
+ | assignment ';'
+ | ';'
+ ;
+
+returnStatement : 'return' assignment ';' ;
+ifStatement : 'if' '(' assignment ')' statement ('else' statement)? ;
+whileStatement : 'while' '(' assignment ')' statement ;
+breakStatement : 'break' ';' ;
+continueStatement : 'continue' ';' ;
+
+forStatement
+ : 'for' '(' (declaration | assignment)? ';' assignment? ';' assignment? ')' statement
+ ;
+
+structDeclaration : 'struct' IDENTIFIER '{' structMember* '}' ';' ;
+structMember : constructorDeclaration | methodDeclaration | statement ;
+
+// The constructor name must match the enclosing struct's name.
+constructorDeclaration : 'new' IDENTIFIER '=' constructorExpression ';' ;
+constructorExpression : '{' constructorParameterList? '->' statement* '}' ;
+constructorParameterList : (constructorParameter ','?)+ ;
+constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
+// ^ accepts an unfinished struct reference; ? independently permits null.
+// Only self may be read while incomplete; ^ arguments may be stored/forwarded.
+// A new result is incomplete iff an actual argument is. See ../../chapter29/README.md#incomplete-types.
+
+// A method is an ordinary fixed function binding in a struct definition.
+// The compiler supplies self; it is not written in parameterList.
+// Function types and expressions both receive their implicit receiver here.
+methodDeclaration : 'val' bindingModifier? IDENTIFIER '=' functionExpression ';' ;
+
+declaration : declarationType binding (',' binding)* ;
+declarationType : type | 'var' | 'val' ;
+binding : bindingModifier? IDENTIFIER ('=' initializer)? ;
+bindingModifier : '!' | '~' ;
+// A declaration initializer consisting of the string "C" declares an extern
+// symbol: a function, or explicit numeric native storage. Ordinary strings
+// elsewhere are array-valued expressions.
+initializer : assignment ;
+
+// The prefix qualifies the named struct reference, not an enclosing array.
+// Each [] / [~] suffix qualifies its own array layer. ? requires a reference.
+type
+ : functionType
+ | primitiveType typeSuffix*
+ | accessModifier? typeName typeSuffix*
+ ;
+accessModifier : '!' | '~' ;
+typeSuffix : '?' | '[]' | '[~]' ;
+typeName : IDENTIFIER ('.' IDENTIFIER)* ;
+
+primitiveType
+ : 'int' | 'i8' | 'i16' | 'i32' | 'i64'
+ | 'u1' | 'u8' | 'u16' | 'u32' | 'byte' | 'bool'
+ | 'flt' | 'f32' | 'f64'
+ ;
+
+assignment : expression (assignmentOperator assignment)? ;
+assignmentOperator
+ : '=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^='
+ | '<<=' | '>>=' | '>>>='
+ ;
+
+expression : logicalExpression ('?' assignment (':' assignment)?)? ;
+
+// Both logical operators short-circuit and associate to the right here.
+logicalExpression : bitwiseExpression (('&&' | '||') logicalExpression)? ;
+
+bitwiseExpression
+ : equalityExpression (('&' | '|' | '^') equalityExpression)*
+ ;
+
+equalityExpression : comparisonExpression (('==' | '!=') comparisonExpression)* ;
+
+// Chained comparisons test adjacent operands and short-circuit. A chain must
+// keep its direction; equality has lower precedence and does not join a chain.
+comparisonExpression
+ : shiftExpression
+ ( (('<' | '<=') shiftExpression)+ | (('>' | '>=') shiftExpression)+ )?
+ ;
+
+shiftExpression
+ : additiveExpression (('<<' | '>>' | '>>>') additiveExpression)*
+ ;
+
+additiveExpression
+ : multiplicativeExpression (('+' | '-') multiplicativeExpression)*
+ ;
+
+multiplicativeExpression
+ : unaryExpression (('*' | '/' | '%') unaryExpression)*
+ ;
+
+unaryExpression
+ : ('-' | '!') unaryExpression
+ | updateOperator IDENTIFIER
+ | postfixExpression
+ ;
+
+// Prefix updates require a local name; postfix updates also allow fields
+// and array elements. All updates require an assignable operand.
+updateOperator : '++' | '--' ;
+postfixExpression : primaryExpression postfixSuffix* updateOperator? ;
+postfixSuffix : '.' IDENTIFIER | '[' assignment ']' | '#' | callSuffix | methodCallSuffix ;
+
+// For a fixed function-valued member, object.name(args) passes object as self.
+// This overlaps ordinary field selection followed by a call syntactically;
+// name/type resolution determines which call form applies.
+methodCallSuffix : '.' IDENTIFIER callSuffix ;
+
+primaryExpression
+ : INTEGER_LITERAL
+ | FLOAT_LITERAL
+ | STRING_LITERAL
+ | CHARACTER_LITERAL
+ | 'true'
+ | 'false'
+ | 'null'
+ | IDENTIFIER
+ | '(' assignment ')'
+ | newExpression
+ | functionExpression
+ ;
+
+// A function is an expression bound with an ordinary declaration.
+// Its last statement supplies the implicit result; return can exit earlier.
+functionExpression : '{' parameterList? '->' statement* '}' ;
+parameterList : (parameter ','?)+ ;
+parameter : type bindingModifier? IDENTIFIER ;
+
+// Function types have unnamed, space-separated argument types.
+// {int} is the zero-argument type; its function expression still uses ->.
+functionType
+ : '{' type+ '->' type '}' '?'?
+ | '{' type '}' '?'?
+ ;
+
+callSuffix : '(' argumentList? ')' ;
+argumentList : assignment (',' assignment)* ','? ;
+
+// Allocation invokes the declared constructor; inline initializer blocks from
+// earlier chapters are replaced by constructor arguments.
+newExpression : 'new' type ('[' assignment ']' | callSuffix)? ;
+
+INTEGER_LITERAL : [1-9] DIGIT* | '0' [0-7]* | '0' [xX] HEX_DIGIT+ ;
+FLOAT_LITERAL : DIGIT+ ('.' DIGIT* ('e' DIGIT+)? | 'e' '-'? DIGIT+) ;
+STRING_LITERAL : '"' (ESCAPE | ~["\\])* '"' ;
+CHARACTER_LITERAL : '\'' (ESCAPE | ~['\\]) '\'' ;
+fragment ESCAPE : '\\' [0ntr\\'"] ;
+IDENTIFIER : NON_DIGIT (NON_DIGIT | DIGIT)* ;
+fragment NON_DIGIT : [a-zA-Z_] ;
+fragment DIGIT : [0-9] ;
+fragment HEX_DIGIT : [0-9a-fA-F] ;
+WHITESPACE : [ \t\r\n]+ -> skip ;
+LINE_COMMENT : '//' ~[\r\n]* -> skip ;
+BLOCK_COMMENT : '/*' .*? '*/' -> skip ;
+```
diff --git a/docs/chapter32/32-grammar.md b/docs/chapter32/32-grammar.md
new file mode 100644
index 00000000..6fb23da7
--- /dev/null
+++ b/docs/chapter32/32-grammar.md
@@ -0,0 +1,275 @@
+# Grammar for Chapter 32
+
+English | [日本語](32-grammar.ja.md)
+
+The handwritten recursive-descent implementation lives in
+[`com.seaofnodes.simple.parser`](../../src/main/java/com/seaofnodes/simple/parser/).
+The production-to-code map below the grammar describes where syntax ends and
+name resolution or graph construction begins. This grammar documents the
+language; it is not input to a parser generator.
+
+`int` is an alias for `i32`; `i64` explicitly selects 64-bit integer storage.
+This alias does not change literal inference or intermediate arithmetic.
+
+Integer literals use decimal (`42`), leading-zero octal (`052`), or hexadecimal
+(`0x2a`, `0X2A`). Octal digits are 0–7; `08` and `09` are errors. Hexadecimal
+and octal literals can spell any 64-bit bit pattern: the high bit gives the
+usual signed value, so `0xffffffffffffffff` is -1. Decimal literals retain
+their signed 64-bit limit. Floating literals remain decimal, including forms
+such as `012.5` and `012f`. A radix prefix does not change integer inference
+or storage width.
+
+```antlrv4
+grammar SimpleLanguage;
+
+// Name lookup, assignable operands, type compatibility, and access permissions
+// are checked by the compiler in addition to these syntax rules.
+// A file is a compilation unit; its path supplies its namespace.
+// Qualified names resolve nested types and other units without an import keyword.
+program : statement* EOF ;
+
+block : '{' statement* '}' ;
+
+statement
+ : block
+ | returnStatement
+ | ifStatement
+ | whileStatement
+ | forStatement
+ | breakStatement
+ | continueStatement
+ | structDeclaration
+ | declaration ';'
+ | assignment ';'
+ | ';'
+ ;
+
+returnStatement : 'return' assignment ';' ;
+ifStatement : 'if' '(' assignment ')' statement ('else' statement)? ;
+whileStatement : 'while' '(' assignment ')' statement ;
+breakStatement : 'break' ';' ;
+continueStatement : 'continue' ';' ;
+
+forStatement
+ : 'for' '(' (declaration | assignment)? ';' assignment? ';' assignment? ')' statement
+ ;
+
+structDeclaration : 'struct' IDENTIFIER '{' structMember* '}' ';' ;
+structMember : constructorDeclaration | methodDeclaration | statement ;
+
+// The constructor name must match the enclosing struct's name.
+constructorDeclaration : 'new' IDENTIFIER '=' constructorExpression ';' ;
+constructorExpression : '{' constructorParameterList? '->' statement* '}' ;
+constructorParameterList : (constructorParameter ','?)+ ;
+constructorParameter : type '^'? bindingModifier? IDENTIFIER ;
+// ^ accepts an unfinished struct reference; ? independently permits null.
+// Only self may be read while incomplete; ^ arguments may be stored/forwarded.
+// A new result is incomplete iff an actual argument is. See ../../chapter29/README.md#incomplete-types.
+
+// A method is an ordinary fixed function binding in a struct definition.
+// The compiler supplies self; it is not written in parameterList.
+// Function types and expressions both receive their implicit receiver here.
+// Global functions use their owning class singleton as self.
+methodDeclaration : 'val' bindingModifier? memberName '=' functionExpression ';' ;
+memberName : IDENTIFIER | primitiveType ;
+
+declaration : declarationType binding (',' binding)* ;
+declarationType : type | 'var' | 'val' ;
+binding : bindingModifier? IDENTIFIER ('=' initializer)? ;
+// At class/struct member scope, memberName also permits primitive type names.
+// Ordinary locals and parameters still require a non-keyword IDENTIFIER.
+bindingModifier : '!' | '~' ;
+// A declaration initializer consisting of the string "C" declares an extern
+// symbol: a function, or explicit numeric native storage. Ordinary strings
+// elsewhere are array-valued expressions.
+initializer : assignment ;
+
+// The prefix qualifies the named struct reference, not an enclosing array.
+// Each [] / [~] suffix qualifies its own array layer. ? requires a reference.
+type
+ : functionType
+ | primitiveType typeSuffix*
+ | accessModifier? typeName typeSuffix*
+ ;
+accessModifier : '!' | '~' ;
+typeSuffix : '?' | '[]' | '[~]' ;
+typeName : IDENTIFIER ('.' IDENTIFIER)* ;
+
+primitiveType
+ : 'int' | 'i8' | 'i16' | 'i32' | 'i64'
+ | 'u1' | 'u8' | 'u16' | 'u32' | 'byte' | 'bool'
+ | 'flt' | 'f32' | 'f64'
+ ;
+
+assignment : expression (assignmentOperator assignment)? ;
+assignmentOperator
+ : '=' | '+=' | '-=' | '*=' | '/=' | '%=' | '&=' | '|=' | '^='
+ | '<<=' | '>>=' | '>>>='
+ ;
+
+expression : logicalExpression ('?' assignment (':' assignment)?)? ;
+
+// Both logical operators short-circuit and associate to the right here.
+logicalExpression : bitwiseExpression (('&&' | '||') logicalExpression)? ;
+
+bitwiseExpression
+ : equalityExpression (('&' | '|' | '^') equalityExpression)*
+ ;
+
+equalityExpression : comparisonExpression (('==' | '!=') comparisonExpression)* ;
+
+// Chained comparisons test adjacent operands and short-circuit. A chain must
+// keep its direction; equality has lower precedence and does not join a chain.
+comparisonExpression
+ : shiftExpression
+ ( (('<' | '<=') shiftExpression)+ | (('>' | '>=') shiftExpression)+ )?
+ ;
+
+shiftExpression
+ : additiveExpression (('<<' | '>>' | '>>>') additiveExpression)*
+ ;
+
+additiveExpression
+ : multiplicativeExpression (('+' | '-') multiplicativeExpression)*
+ ;
+
+multiplicativeExpression
+ : unaryExpression (('*' | '/' | '%') unaryExpression)*
+ ;
+
+unaryExpression
+ : ('-' | '!') unaryExpression
+ | updateOperator IDENTIFIER
+ | postfixExpression
+ ;
+
+// Prefix updates require a local name; postfix updates also allow fields
+// and array elements. All updates require an assignable operand.
+updateOperator : '++' | '--' ;
+postfixExpression : primaryExpression postfixSuffix* updateOperator? ;
+postfixSuffix : '.' memberName | '[' assignment ']' | '#' | callSuffix | methodCallSuffix ;
+
+// For a fixed function-valued member, object.name(args) passes object as self.
+// This overlaps ordinary field selection followed by a call syntactically;
+// name/type resolution determines which call form applies.
+methodCallSuffix : '.' memberName callSuffix ;
+
+primaryExpression
+ : INTEGER_LITERAL
+ | FLOAT_LITERAL
+ | stringExpression
+ | CHARACTER_LITERAL
+ | 'true'
+ | 'false'
+ | 'null'
+ | IDENTIFIER
+ | '(' assignment ')'
+ | newExpression
+ | functionExpression
+ ;
+
+// A function is an expression bound with an ordinary declaration.
+// Its last statement supplies the implicit result; return can exit earlier.
+functionExpression : '{' parameterList? '->' statement* '}' ;
+parameterList : (parameter ','?)+ ;
+parameter : type bindingModifier? IDENTIFIER ;
+
+// Function types have unnamed, space-separated argument types.
+// {int} is the zero-argument type; its function expression still uses ->.
+functionType
+ : '{' type+ '->' type '}' '?'?
+ | '{' type '}' '?'?
+ ;
+
+callSuffix : '(' argumentList? ')' ;
+argumentList : assignment (',' assignment)* ','? ;
+
+// Allocation invokes the declared constructor; inline initializer blocks from
+// earlier chapters are replaced by constructor arguments.
+newExpression
+ : 'new' type ('[' '~'? assignment ']' arrayInitializer? | arrayInitializer | callSuffix)?
+ ;
+// With no explicit length, type must end in [] or [~] and the initializer is a list.
+arrayInitializer
+ : '{' (assignment (',' assignment)* ','?)? '}'
+ | '{' ('int' | 'i32' | 'i64' | 'u32') IDENTIFIER '->' statement* '}'
+ ;
+
+INTEGER_LITERAL : [1-9] DIGIT* | '0' [0-7]* | '0' [xX] HEX_DIGIT+ ;
+// The f suffix also accepts an integer-shaped token, e.g. 12f.
+FLOAT_LITERAL : DIGIT+ ('.' DIGIT* ('e' DIGIT+)? | 'e' '-'? DIGIT+) 'f'?
+ | DIGIT+ 'f' ;
+// String text uses a lexical mode: whitespace/comments are literal here.
+// Interpolation re-enters the ordinary expression grammar, recursively.
+stringExpression : '"' (STRING_TEXT | ESCAPE | '%%' | interpolation)* '"' ;
+interpolation : '%' format? '(' assignment ')' ;
+format : FORMAT_FLAG* FORMAT_WIDTH? ('.' FORMAT_WIDTH?)? FORMAT_KIND TIME_STYLE? ;
+// Flags: - + space # 0. Width/precision: decimal digits, no expressions.
+// Kinds: d i u o x X f F e E g G a A c s b t.
+// TIME_STYLE: F r R M D T, allowed only after t; default F (ISO UTC).
+// Time styles: ISO, 12-hour, 24-hour, elapsed MM:SS.mmm, DD/MM/YY, HH:MM:SS.
+// Duplicate/inapplicable flags and precision on c/b/t are rejected.
+// Time accepts width and left alignment only; see time.md.
+// STRING_TEXT excludes double quote, backslash, and percent.
+CHARACTER_LITERAL : '\'' (ESCAPE | ~['\\]) '\'' ;
+fragment ESCAPE : '\\' [0ntr\\'"%] ;
+IDENTIFIER : NON_DIGIT (NON_DIGIT | DIGIT)* ;
+fragment NON_DIGIT : [a-zA-Z_] ;
+fragment DIGIT : [0-9] ;
+fragment HEX_DIGIT : [0-9a-fA-F] ;
+WHITESPACE : [ \t\r\n]+ -> skip ;
+LINE_COMMENT : '//' ~[\r\n]* -> skip ;
+BLOCK_COMMENT : '/*' .*? '*/' -> skip ;
+```
+
+## Reading the parser alongside the grammar
+
+All paths below are within `src/main/java/com/seaofnodes/simple/parser/`.
+The components share one `Parser` instance containing the cursor, active scope,
+compilation unit, and graph utilities. They are package-private collaborators;
+there is no inheritance chain, AST, or additional compiler pass.
+
+| Productions | Implementation |
+| --- | --- |
+| `program` | [`Parser.parse`](../../src/main/java/com/seaofnodes/simple/parser/Parser.java): establish the source-unit scope, parse its initializer, resolve remaining file names, publish its class |
+| `statement`, `block`, loops, jumps, `returnStatement` | [`Statements`](../../src/main/java/com/seaofnodes/simple/parser/Statements.java), starting at `parseStatement` |
+| `declaration`, `binding`, `bindingModifier` | [`Declarations`](../../src/main/java/com/seaofnodes/simple/parser/Declarations.java): declaration/expression lookahead, then each binding and initializer |
+| `structDeclaration`, `constructorDeclaration` | [`Structs`](../../src/main/java/com/seaofnodes/simple/parser/Structs.java), starting at `parseStruct` and `parseConstructorDeclaration`; field discovery and initialization checks follow these entry points |
+| `type`, `typeName`, `functionType` | [`Types`](../../src/main/java/com/seaofnodes/simple/parser/Types.java): `parseType` and `parseFunctionType`; qualified-name lookup lives in `typeName`, `dottedName`, and `rootedName` |
+| `assignment` through `primaryExpression` | [`Expressions`](../../src/main/java/com/seaofnodes/simple/parser/Expressions.java): `parseAssignment`, `parseExpression`, `parseLogical`, `parseBitwise`, `parseEquality`, `parseComparison`, `parseShift`, `parseAddition`, `parseMultiplication`, `parseUnary`, `parsePrimary` |
+| `postfixExpression`, member selection and updates | `Expressions.parsePostfix` / `parsePostfixMethod` dispatch to [`References.parseField`](../../src/main/java/com/seaofnodes/simple/parser/References.java); `References.parseName` handles bare names, implicit receivers, and forward references |
+| `functionExpression`, `parameterList`, calls, `argumentList` | [`Functions`](../../src/main/java/com/seaofnodes/simple/parser/Functions.java): `parseFunction`, `parseConstructor`, shared `parameters` and `arguments`, then `parseBody` |
+| `newExpression`, `arrayInitializer` | [`Allocations.parseNew`](../../src/main/java/com/seaofnodes/simple/parser/Allocations.java), [`ArrayInitializers`](../../src/main/java/com/seaofnodes/simple/parser/ArrayInitializers.java); private initialization, list checks, and generator loops |
+| `stringExpression`, `interpolation` | [`Strings.parse`](../../src/main/java/com/seaofnodes/simple/parser/Strings.java), using `Lexer.stringPart` / `stringFormat`; normal expression parsing resumes inside each interpolation |
+| Literals, identifiers, comments, token matching | [`Lexer`](../../src/main/java/com/seaofnodes/simple/parser/Lexer.java); it also supplies source-location snapshots used by diagnostics and serialized IR |
+
+`ControlFlow` shares guarded scope merging between `if`, `?:`, `&&`, and `||`.
+`Conversions` shares binding, field, and result conversions. These
+operations are compiler semantics rather than additional grammar productions.
+`Parser` retains the type registry and the small control/memory/peephole helpers
+used by several productions and by the rest of the compiler.
+
+There are a few deliberate differences between a syntax-only parser and this
+one-pass IR builder:
+
+- A statement beginning with `{` might be a block or a function-type binding.
+ `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.
+ 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
+ belong. Explicit constructor bodies are scanned first and parsed after field
+ 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.
+
+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
+privacy policy is separate from recognizing a qualified type name. The existing
+same-named function binding inside a struct is also recognized as a constructor;
+`new Name = { ... };` is the explicit constructor spelling above.
diff --git a/docs/chapter32/README.ja.md b/docs/chapter32/README.ja.md
new file mode 100644
index 00000000..f8cb31ac
--- /dev/null
+++ b/docs/chapter32/README.ja.md
@@ -0,0 +1,43 @@
+# 第32章:コンパイラ内部の高速化
+
+[English](README.md) | 日本語
+
+[前の章:第31章 — 描画、時間、グラフィカルゲーム](../chapter31/README.ja.md)
+
+第31章は描画、ゲーム、ライブラリを完成させたスナップショットです。
+この章では言語と実行例を引き継ぎ、コンパイルとテストにかかる時間を調べます。
+
+主な変更は次のとおりです。
+
+- テストを独立した JVM のグループに分割し、各 JVM の JIT・GC スレッド数を調整します。
+ ネイティブテストの出力先を分離し、型の格子テストも4つの JVM に分割します。
+- `isConstant` と `isFinal` はポインタの参照先を再帰的にたどらないため、不要な再帰処理の準備と後始末を取り除きます。
+- 高価な検証の既定値を log 8 から log 10 に変更し、インライン化の各途中段階で繰り返していたスケジュール検証を削減します。
+- 外部状態を読む依存関係を不透明な引数に限定し、定数引数の削除による無関係な利用側への通知を減らします。
+ 呼び出しの切り離しで変更したパラメータは明示的に再処理します。
+- IFG の live-out マップと作業領域を関数ごとに持ち、スピルによる再試行の間だけ再利用します。
+ 過去のコンパイルの基本ブロックを保持し続けることがなくなります。
+ スピル候補の評価に使う関数の大きさも、彩色の試行ごとに一度だけ計算します。
+- ロードを命令に組み込めるか調べる走査では、訪問済みノードを ID の BitSet で管理します。
+ パック値のヒストグラムはコメントアウトし、通常のコンパイルでは収集しません。
+ ELF の `.simple` セクションのサイズと内訳も測定し、今後の形式改善の基準にします。
+
+測定ではワークリストからの peephole 呼び出しが約446万回から370万回へ、17.2%減少しました。
+詳細な測定条件、実装の説明、残る調査対象は[英語版](README.md)を参照してください。
+
+`chapter32` ディレクトリから実行します。
+
+```sh
+make -j 8 release
+make -j 8 tests_nographics
+make test CLASS=EscapeFlowTest "TEST_JAVA_OPTS=-XX:ActiveProcessorCount=2 -Dsimple.assert.expensive=1"
+```
+
+依存関係がない新しい環境では、オンラインで `make libs` を一度実行してください。
+通常のビルドとテストはオフラインで動作し、画面や音声デバイスを必要としません。
+log 1 は進捗のたびに検証し、log 8 は以前の頻度、log 0 は高価な検証だけを無効にします。
+
+[文法](32-grammar.ja.md)、[実行例](examples/README.md)、
+[描画](../../src/main/smp/sys/draw/README.md)、[音声](../../src/main/smp/sys/audio.md)、
+[時間](../../src/main/smp/sys/time/README.md)もこのスナップショットに含まれます。
+言語とライブラリの解説は[第31章](../chapter31/README.md)を参照してください。
diff --git a/docs/chapter32/README.md b/docs/chapter32/README.md
new file mode 100644
index 00000000..b6bc6635
--- /dev/null
+++ b/docs/chapter32/README.md
@@ -0,0 +1,212 @@
+# Chapter 32: Compiler Internal Speedups
+
+English | [日本語](README.ja.md)
+
+[Previous: Chapter 31 — Software Drawing, Time, and Graphical Games](../chapter31/README.md)
+
+The games and libraries from chapter 31 made both compiling and testing slow
+enough to interrupt development. This chapter makes room for future work:
+faster feedback for Simple's developers, and faster compilation for its users.
+
+| What improved | Result |
+| --- | --- |
+| Repeated compilation | 29–79% less compile time for the large workloads below |
+| Development testing | Roughly 30 seconds for a full run → 8.8 seconds for sanity checks; the full suite now takes 22.8 seconds |
+| IR stored in ELF files | 21.9% smaller across 26 objects |
+
+The compiler figures isolate the allocator-scratch fix in repeated compiles.
+The testing gain includes a deliberate coverage tradeoff. The sections below
+explain what changed and what each measurement covers.
+
+## Faster development of Simple
+
+### Measure the work and the wait
+
+A test run starts JVMs, compiles Java methods, runs the compiler, checks
+assertions, links native programs, and executes them. In one serial profiling
+run, compiler phases took 29.7 seconds and 153 GCC calls took another 29.8,
+mostly linking. Compiler optimization could address only part of the cost.
+
+Parallel testing has the "tallest pole" problem: we wait for the last worker.
+The [Makefile](Makefile) now splits the former catch-all JVM into balanced
+groups, with private native outputs. Each JVM sizes its JIT and GC pools for
+two processors. Eight Make jobs beat both four and sixteen on this host.
+
+| Command | Coverage | Warm elapsed time |
+| --- | --- | ---: |
+| `make -j8 sanity` | Full lattice, chapter/backend tests, saved fuzzer regressions, focused compiler tests | 8.8 s |
+| `make -j8 tests` | All of the above, plus remaining library, application, and CLI integration | 22.8 s |
+
+These runs use Windows, Java 21, and a 10-core/20-thread i9-10900K, with builds
+already up to date. They execute 680 and 819 tests respectively, including the
+lattice partitions. Assertions stay enabled. Use the full suite before finishing
+a change, especially when working on libraries or interfaces omitted by `sanity`.
+
+Routine savings came from cheaper fixtures: loop over the division/remainder
+matrix instead of generating 200 conditional checks; share native programs
+between formatting cases; compile two small modules for an assembly-dump test
+instead of all of `sys`. The full suite's GCC calls fell from 153 to 141.
+
+### Keep the full lattice, with fewer repetitions
+
+The [lattice test](../../src/test/java/com/seaofnodes/simple/TypeTest.java) stays in
+the sanity run. Compiler transformations depend on its laws, so we reduced
+repetition rather than sampling fewer types.
+
+First, format assertion messages only on failure. Doing that inside the cubic
+loop reduced the standalone run from 10.6 to 4.5 seconds. Next, cache pairwise
+meets and joins, computing both operand orders before checking commutativity.
+
+Associativity formerly visited all `n^3` ordered triples. Now it visits
+`i <= j <= k`, including repeated operands: `n(n+1)(n+2)/6` iterations. Each
+visit compares all six results:
+
+```
+(a & b) & c c & (a & b)
+(a & c) & b b & (a & c)
+(b & c) & a a & (b & c)
+```
+
+Once the original pairs commute, the six original associativity equalities
+connect these results in a cycle. Comparing them to one common result checks
+the same property. We must retain both operand orders involving intermediate
+types: `a & b` may be outside the gathered set, so its commutativity has not
+yet been established.
+
+All comparable-pair monotonicity checks remain. The complete unpartitioned
+TypeTest now takes about 0.7 seconds. Make still partitions it across four
+JVMs, each with private type-interning state.
+
+## Faster compilation for Simple users
+
+### Wake nodes when something relevant changes
+
+`listener.addDep(source)` asks to wake a node when the source changes.
+Registering extra dependencies is easy; paying for them happens later.
+
+Tracing enqueues exposed two broad notifications. Calls and summaries read
+`Start.outside` even when their arguments did not need it, subscribing them to
+unrelated changes. They now read it only for opaque arguments. Removing a
+constant Phi input also woke every user of that constant throughout the
+program. It now queues the changed Phi.
+
+These filters cut worklist visits from 4.46 million to 3.70 million, or 17.2%.
+Time inside `iterate()` fell from 14.24 to 11.97 seconds. Further MemPhi and
+IfNode filters reduced visits slightly without a measurable timing gain.
+Fewer visits alone are not proof of a faster compiler.
+
+Broad notifications can hide missing dependencies. Stronger verification found
+nodes that had relied on accidental wakeups, including a Phi whose guard-merge
+rewrite became possible after an If predicate changed. Checking every progress
+step isolated the peephole that exposed the missing dependency.
+
+Normal runs sample expensive checks every 1,024 eligible steps, retaining entry
+and completed-phase checks. Use `-Dsimple.assert.expensive=1` to check every
+progress step while diagnosing a failure. Ordinary assertions remain enabled.
+
+### Give scratch data the lifetime of the work
+
+[RegAlloc](../../src/main/java/com/seaofnodes/simple/codegen/RegAlloc.java) already
+allocated one function at a time, but its interference-graph helper retained
+basic-block keys from every previous allocation. Each `sys` compile added
+another 2,558 keys to clear on later runs.
+
+Each function now owns its [IFG](../../src/main/java/com/seaofnodes/simple/codegen/IFG.java)
+scratch maps. They survive spill retries, then become unreachable when allocation
+finishes. Spill scoring also computes the function's area once per coloring
+attempt instead of walking the blocks for each candidate.
+
+| Program | Before | After |
+| --- | ---: | ---: |
+| `sys` library | 1,290 ms | 913 ms |
+| Clock | 537 ms | 279 ms |
+| Breakout | 1,007 ms | 609 ms |
+| Graphical tic-tac-toe | 1,362 ms | 292 ms |
+
+These medians isolate that change: six measured compiles after three warmups,
+alternating baseline and changed compilers, with the same library and assertions
+enabled. They include object export but exclude linking. The old compiler
+accumulated keys during warmup too; this measures repeated compilation, not
+fresh command-line startup. Machine-code bytes matched in all 26 objects checked.
+
+### Remove empty space and unnecessary allocation
+
+[MemMergeNode](../../src/main/java/com/seaofnodes/simple/node/MemMergeNode.java)
+used alias numbers as input indices, leaving mostly null slots supplied by
+the default memory value. A dense list plus an alias-to-input map cut `sys`'s
+live MemMerge input slots from 54,388 to 2,462. That change alone reduced its
+compile time by 5.8%, while preserving folding behavior and generated code.
+
+Other savings were straightforward: remove recursive scratch-state setup from
+the shallow `isConstant` and `isFinal` queries; use node-ID BitSets for load-fold
+visits; stop collecting a packed-value histogram left over from profiling.
+The latter two changes reduced `sys` compiler-thread allocation from 119.6 to
+69.4 MiB and median compile time from 1,017 to 942 ms. These are separate
+comparisons, not cumulative chapter-wide timings.
+
+### Make saved compiler state smaller
+
+ELF's `.simple` section stores reloadable IR, declarations, and import metadata.
+It occupied 79% of the measured `sys` objects. Three encoding changes removed
+avoidable overhead: gradual growth for packed integers, explicit MemMerge
+alias/input pairs instead of default holes, and a wider compact encoding for
+singleton function IDs. Strings retain raw UTF-8 bytes.
+
+| `.simple` payload | Before | After | Reduction |
+| --- | ---: | ---: | ---: |
+| `sys`, all 22 modules | 469,881 bytes | 368,694 bytes | 21.5% |
+| Clock | 43,854 bytes | 31,906 bytes | 27.2% |
+| Breakout | 80,950 bytes | 62,139 bytes | 23.2% |
+| Graphical tic-tac-toe | 44,353 bytes | 35,961 bytes | 18.9% |
+| HelloWorld | 14,635 bytes | 11,523 bytes | 21.3% |
+
+Across these 26 objects, the payload shrank by 143,450 bytes, or 21.9%, with
+identical machine code. Compile timings showed no consistent improvement;
+the demonstrated gain is smaller saved compiler state.
+
+## Keep the generated code good
+
+Changing worklist order can change rewrites and register allocation. Some
+broader notification filters increased register copies, so we did not keep
+them. Judge a compiler speedup by compile time, memory use, and generated code
+together.
+
+Correctness fixes uncovered here belong in their teaching chapters:
+[Phi factoring after strength reduction in chapter 5](../chapter05/README.md#factoring-after-strength-reduction),
+and shared class receivers in [chapter 28a](../chapter28a/README.md#globals-use-the-same-receiver-as-fields)
+and [chapter 28b](../chapter28b/README.md).
+
+## Build and use this chapter
+
+From `chapter32`, populate the dependency cache once with `make libs` if needed.
+Ordinary builds use that cache and do not download dependencies.
+
+```sh
+make -j8 release
+make -j8 sanity
+make -j8 tests
+```
+
+For a fully headless full run, use `make -j8 tests_nographics`. It disables the
+optional MiniFB and miniaudio backends. The packed IR header changes from `C0DE`
+to `C0D2`; the reader rejects the older format. Run `make clean` before
+`make -j8 release` to rebuild old objects, and rebuild any separately maintained
+Simple libraries too.
+
+Run one class, or enable every-step verification for a focused investigation:
+
+```sh
+make test CLASS=TypeTest
+make test CLASS=WorklistTest "TEST_JAVA_OPTS=-XX:ActiveProcessorCount=2 -Dsimple.assert.expensive=1"
+```
+
+The [grammar and parser map](32-grammar.md) describes this snapshot.
+[Chapter 31](../chapter31/README.md) teaches its language and library additions;
+the [examples](examples/README.md) include launch commands for the games.
+Library references live with [drawing](../../src/main/smp/sys/draw/README.md),
+[window/input](../../src/main/smp/sys/gfx.md), [audio](../../src/main/smp/sys/audio.md), and
+[time](../../src/main/smp/sys/time/README.md). Further projects belong in the
+[roadmap](../roadmap.md).
+
+Use the fast checks while editing. Run the full suite before finishing, and
+turn up verification when a failure needs a closer look.
diff --git a/docs/chapter32/examples/A_helloWorld.smp b/docs/chapter32/examples/A_helloWorld.smp
new file mode 100644
index 00000000..4ed6abdf
--- /dev/null
+++ b/docs/chapter32/examples/A_helloWorld.smp
@@ -0,0 +1,2 @@
+sys.io.p("Hello, World!\n");
+return 0;
diff --git a/docs/chapter32/examples/Breakout.smp b/docs/chapter32/examples/Breakout.smp
new file mode 100644
index 00000000..d60894ac
--- /dev/null
+++ b/docs/chapter32/examples/Breakout.smp
@@ -0,0 +1,369 @@
+// Clear 24 x 8 bricks. Arrows or mouse move; Space/click serves; P pauses;
+// R restarts; Q/Escape exits. Any argument runs ten frames as a smoke test.
+u32 WIDTH = 1008, HEIGHT = 760, COLS = 24, ROWS = 8;
+int LEFT = 24, RIGHT = 984, TOP = 84, BOTTOM = 718;
+int BRICK_TOP = 152, BRICK_DX = 40, BRICK_DY = 22, BRICK_W = 36, BRICK_H = 18;
+int RADIUS = 5, PADDLE_HALF = 56, PADDLE_Y = 674;
+int READY = 0, PLAY = 1, WON = 2, LOST = 3;
+int KEY_LEFT = 263, KEY_RIGHT = 262; // MiniFB key codes; gfx.LEFT is a mouse button.
+i64 STEP_ms = 8, FRAME_ms = 16;
+u32 BACKGROUND = 0x0b1220, WHITE = 0xeef7ff, MUTED = 0x8aabc4, CYAN = 0x4ce0ef;
+val COLORS = new u32[~]{0xff5268,0xff8050,0xffb548,0xffdb58,
+ 0x9bdd58,0x45d8b0,0x49b9f5,0x8d94ff};
+val DIGITS = new u8[~][~]{"0","1","2","3","4","5","6","7","8","9"};
+
+struct Game {
+ u8[] bricks = new u8[COLS*ROWS]{int i -> 1;};
+ int score = 0, remaining = COLS*ROWS, lives = 3, depth = 1, phase = READY;
+ bool boosted = false, backWall = false, paused = false;
+ f64 x = 504.0, y = 663.0, dx = 0.4, dy = -0.916515138991168;
+
+ // Fixed 8 ms simulation, split further to travel at most two pixels per step.
+ // Even at maximum boosted speed a ball cannot tunnel through an 18 px brick.
+ val _tick = { int direction ->
+ if( paused || phase == WON || phase == LOST ) return 0;
+ _paddle(paddle+direction*6.4);
+ if( phase == READY ) { x = paddle; y = PADDLE_Y-RADIUS-6; return 0; }
+ f64 seconds = 0.008; // 8ms
+ while( seconds > 0.000000001 && phase == PLAY ) {
+ f64 dt = 2.0/speed;
+ if( dt > seconds ) dt = seconds;
+ seconds -= dt;
+ f64 oldX = x, oldY = y;
+ x += dx*speed*dt;
+ y += dy*speed*dt;
+ if( x < LEFT+RADIUS && dx < 0.0 ) {
+ x = 2.0*(LEFT+RADIUS)-x; dx = -dx; _cue(1);
+ }
+ if( x > RIGHT-RADIUS && dx > 0.0 ) {
+ x = 2.0*(RIGHT-RADIUS)-x; dx = -dx; _cue(1);
+ }
+ if( y < TOP+RADIUS && dy < 0.0 ) {
+ y = 2.0*(TOP+RADIUS)-y; dy = -dy;
+ backWall = true; _cue(1);
+ }
+ if( dy > 0.0 && oldY <= PADDLE_Y-RADIUS && y >= PADDLE_Y-RADIUS &&
+ paddle-PADDLE_HALF-RADIUS <= x <= paddle+PADDLE_HALF+RADIUS ) _rebound();
+ if( y > BOTTOM+RADIUS ) {
+ _lostBall();
+ break;
+ }
+ // Map the center into the grid of radius-expanded brick boxes.
+ // Their overlap is smaller than one cell: at most 2 x 2 candidates.
+ if( x <= LEFT+2 -RADIUS || x >= LEFT+2 +(COLS-1)*BRICK_DX+BRICK_W+RADIUS ||
+ y <= BRICK_TOP-RADIUS || y >= BRICK_TOP+(ROWS-1)*BRICK_DY+BRICK_H+RADIUS )
+ continue;
+ int col = (x-(LEFT+2 -RADIUS))/BRICK_DX;
+ int row = (y-(BRICK_TOP-RADIUS))/BRICK_DY;
+ bool hit = false;
+ for( int r = row > 0 ? row-1 : 0; r <= row && r < ROWS && !hit; r++ )
+ for( int c = col > 0 ? col-1 : 0; c <= col && c < COLS; c++ ) {
+ int i = r*COLS+c;
+ if( bricks[i] == 0 ) continue;
+ f64 left = LEFT+2 +c*BRICK_DX-RADIUS;
+ f64 top = BRICK_TOP+r*BRICK_DY-RADIUS;
+ f64 right = left+BRICK_W+2*RADIUS;
+ f64 bottom= top +BRICK_H+2*RADIUS;
+ if( left < x < right && top < y < bottom ) {
+ bool back = false;
+ // Resolve the face crossed this step, using the previous center.
+ // Vertical faces win a simultaneous corner contact.
+ if( oldY <= top && dy > 0.0 ) {
+ y = top; dy = -dy; back = true;
+ } else if( oldY >= bottom && dy < 0.0 ) {
+ y = bottom; dy = -dy;
+ } else if( oldX <= left && dx > 0.0 ) {
+ x = left; dx = -dx;
+ } else if( oldX >= right && dx < 0.0 ) {
+ x = right; dx = -dx;
+ } else continue; // Missed all bricks
+ _brick(i,back);
+ hit = true;
+ break;
+ }
+ }
+ }
+ return 0;
+ };
+
+
+ // Several sound things might happen in this event, pick one
+ int sound = 0; // Increasing priority: wall, paddle, brick, boost, miss, win.
+ val _cue = { int snd -> if( snd > sound ) sound = snd; };
+
+ // Ball speed is a fraction of deepest brick hit, plus backwall boost
+ f64 speed;
+ val _speed = { -> speed = (320.0+35.0*(depth-1))*(boosted ? 1.65 : 1.0); };
+
+ // Clamp paddle to wall sides
+ f64 paddle;
+ val _paddle = { f64 x ->
+ paddle = x < LEFT +PADDLE_HALF ? LEFT +PADDLE_HALF :
+ x > RIGHT-PADDLE_HALF ? RIGHT-PADDLE_HALF :
+ x;
+ };
+
+ // Hit the paddle
+ val _rebound = { ->
+ // Where along the paddle did you hit?
+ f64 offset = (x-paddle)/PADDLE_HALF;
+ if( offset < -1.0 ) offset = -1.0;
+ if( offset > 1.0 ) offset = 1.0;
+ dx = 0.88*offset;
+ // A near-center hit still drifts sideways instead of repeating forever.
+ if( -0.12 < dx < 0.12 ) dx = dx < 0.0 ? -0.12 : 0.12;
+ dy = -_sqrt(1.0-dx*dx); // Bounce upwards speed
+ y = PADDLE_Y-RADIUS; // Reset ball hit to top of paddle
+ backWall = false; // Did not hit back wall
+ _cue(2); // Paddle bounce sound
+ };
+
+ // Hit a brick?
+ int soundDepth; // Which brick depth for the boop
+ val _brick = { int index, bool back ->
+ if( bricks[index] == 0 ) return 0; // No brick to hit!
+ bricks[index] = 0; // Clear brick
+ int row = ROWS-index/COLS; // Get brick row
+ score += row; // Score by row
+ remaining--; // Fewer bricks to iwn
+ if( row > depth ) depth = row; // Max depth seen
+ // Brick-hit sound
+ if( sound <= 3 ) { _cue(3); soundDepth = row; }
+ if( back && backWall && !boosted ) { _cue(3); boosted = true; }
+ if( remaining == 0 ) { _cue(6); phase = WON; }
+ _speed();
+ return 0;
+ };
+
+ // Missed ball with paddle
+ val _lostBall = { ->
+ lives--;
+ phase = lives == 0 ? LOST : READY;
+ backWall = false;
+ depth = 1;
+ boosted = false;
+ _speed();
+ x = paddle; y = PADDLE_Y-RADIUS-6;
+ _cue(5);
+ };
+
+ // Reset for another round
+ val _reset = { ->
+ for( int i = 0; i < bricks#; i++ ) bricks[i] = 1;
+ score = 0;
+ remaining = COLS*ROWS;
+ lives = 3;
+ depth = 1;
+ phase = READY;
+ boosted = false;
+ backWall = false;
+ paused = false;
+ sound = 0;
+ soundDepth = 1;
+ paddle = 504.0;
+ x = paddle;
+ y = PADDLE_Y-RADIUS-6;
+ _speed();
+ };
+
+ // --------------------------------
+ // Drawing code
+ val _hud = { !sys.draw.Canvas c ->
+ c.text(24,22,"BREAKOUT",5,WHITE);
+ c.text(264,20,"SCORE",2,MUTED);
+ _number(c,264,40,score,3,4,WHITE);
+ c.text(424,20,"BRICKS",2,MUTED);
+ _number(c,424,40,remaining,3,4,WHITE);
+ c.text(584,20,"BALLS",2,MUTED);
+ for( int i = 0; i < lives; i++ ) c.fillCircle(590+23*i,50,5,CYAN);
+ c.text(714,20,"SPEED",2,MUTED);
+ int ispeed = speed;
+ _number(c,714,40,ispeed,3,4,boosted ? COLORS[0] : WHITE);
+ c.text(838,40,boosted ? "BOOST!" : "NORMAL",3,boosted ? COLORS[0] : MUTED);
+ };
+
+
+ val _bricks = { !sys.draw.Canvas c ->
+ c.fillRect(LEFT-4,TOP-4,RIGHT-LEFT+8,4,MUTED);
+ c.fillRect(LEFT-4,TOP,4,BOTTOM-TOP,0x29435a);
+ c.fillRect(RIGHT,TOP,4,BOTTOM-TOP,0x29435a);
+ c.text(376,108,boosted ? "BACK WALL BOOST ACTIVE" : "BREAK THROUGH FOR A BOOST",2,boosted ? COLORS[0] : MUTED);
+ for( int i = 0; i < bricks#; i++ ) {
+ if( bricks[i] == 0 ) continue;
+ int row = i/COLS;
+ i64 x = LEFT+2+(i%COLS)*BRICK_DX, y = BRICK_TOP+row*BRICK_DY;
+ c.fillRect(x,y,BRICK_W,BRICK_H,COLORS[row]);
+ c.fillRect(x,y,BRICK_W,2,WHITE);
+ }
+ };
+
+ val _overlay = { !sys.draw.Canvas c ->
+ if( phase != PLAY || paused ) {
+ c.fillRect(246,422,516,108,0x17263a).rect(246,422,516,108,2,0x29435a);
+ u8[~] title = paused ? "PAUSED" : phase == WON ? "WALL CLEARED!" : phase == LOST ? "GAME OVER" : "READY?";
+ c.text(504-(title#*4-1)*4/2,442,title,4,WHITE);
+ u8[~] help = paused ? "P TO CONTINUE" : phase == WON || phase == LOST ? "R TO PLAY AGAIN" : "SPACE OR CLICK TO SERVE";
+ c.text(504-(help#*4-1)*2/2,490,help,2,CYAN);
+ }
+ return 0;
+ };
+
+ // With this Canvas, we draw into the blank canvas, then "present". The
+ // underlying graphics lib copies the bits, and we are then free to clear
+ // and draw again while the old bits continue to be presented.
+ val _draw = { !sys.draw.Canvas c ->
+ c.clear(BACKGROUND);
+ _hud(c);
+ _bricks(c);
+ i64 paddle = paddle, ballX = x, ballY = y;
+ int glowRadius = RADIUS+3;
+ c.fillRect(paddle-PADDLE_HALF,PADDLE_Y,2*PADDLE_HALF,12,CYAN);
+ c.fillRect(paddle-PADDLE_HALF+4,PADDLE_Y+2,2*PADDLE_HALF-8,2,WHITE);
+ c.fillCircle(ballX,ballY,glowRadius,boosted ? 0x672a42 : 0x224b61);
+ c.fillCircle(ballX,ballY,RADIUS,boosted ? COLORS[0] : WHITE);
+ _overlay(c);
+ c.text(24,738,"ARROWS / MOUSE: MOVE SPACE / CLICK: SERVE P: PAUSE R: RESTART Q / ESC: QUIT",2,MUTED);
+ };
+
+ // Served and still holding serve key
+ bool serveHeld;
+ // Paused and still holding pause key
+ bool pauseHeld;
+ // Restart and still holding restart key
+ bool restartHeld;
+ // Last mouse position; track moving mouse
+ int lastMouse;
+
+ // Read and act on the controls
+ val _input = { sys.draw.Canvas c ->
+ val gfx = sys.gfx;
+ bool serve = gfx.key(' ') || gfx.button(gfx.LEFT);
+ bool pause = gfx.key('P');
+ bool restart= gfx.key('R');
+
+ // Keyboard direction and mouse position
+ int direction = (gfx.key(KEY_RIGHT) ? 1 : 0)-(gfx.key(KEY_LEFT) ? 1 : 0);
+ int mouse = c.localX(gfx.mouseX());
+
+ // Restart requested
+ restartHeld = debounce( restart, restartHeld, { -> _reset(); sys.audio.stop(); } );
+
+ // Playing or ready to play game?
+ if( phase == READY || phase == PLAY ) {
+ // Flip pause state
+ pauseHeld = debounce( pause, pauseHeld, { -> paused = !paused; } );
+
+ // If no key and mouse moved, set paddle to mouse
+ if( mouse >= 0 && mouse != lastMouse && direction == 0 && !paused ) {
+ _paddle(mouse*1.0); // Set paddle to mouse
+ // If READY and not PLAY, ball tracks paddle directly
+ if( phase == READY ) x = paddle;
+ }
+ lastMouse = mouse;
+
+ }
+
+ // Serve requested
+ serveHeld = debounce( serve, serveHeld, _serve );
+
+ // Return key direction, so the tick tracking can slide paddle smoothly
+ return direction;
+ };
+
+ val debounce = { bool b, bool bHeld, { int } action ->
+ if( b && !bHeld ) // Action requested and repeating
+ action(); // Do action
+ b; // Dont action again, until 'b' is released
+ };
+
+
+ // Serve the ball; give it a nominal direction and speed
+ val _serve = { ->
+ if( phase == READY && !paused ) {
+ phase = PLAY;
+ dx = 0.4;
+ dy = -_sqrt(1.0-dx*dx);
+ }
+ return 0;
+ };
+};
+
+// Fixed-width decimal labels avoid allocating new strings on every frame.
+val _number = { !sys.draw.Canvas c, i64 x, i64 y, int value, int digits, int scale, u32 color ->
+ for( int i = 0; i < digits; i++ ) {
+ c.text(x+(digits-1-i)*4*scale,y,DIGITS[value%10],scale,color);
+ value /= 10;
+ }
+};
+
+// Short, fading triangle waves; the array initializer builds PCM once at startup.
+val _tone = { int period ->
+ val samples = new i16[~2400]{int i ->
+ int phase = i%period;
+ int triangle = phase < period/2 ? phase : period-phase;
+ return (triangle*4-period)*6000/period*(2400-i)/2400;
+ };
+ int handle = sys.audio.load(samples);
+ return handle < 0 ? sys.audio.BOOP : handle;
+};
+
+
+// Fast low accuracy sqrt
+val _sqrt = { f64 n ->
+ f64 r = 1.0;
+ for( int i = 0; i < 8; i++ ) r = (r+n/r)*0.5;
+ return r;
+};
+
+val main = { u8[~][] args ->
+ // Shortcuts
+ val gfx = sys.gfx, audio = sys.audio;
+
+ // Open a window
+ if( gfx.open("Simple Breakout",WIDTH,HEIGHT) != gfx.OK ) return 1;
+
+ // Audio setup; pre-specify a series of sounds
+ audio.open(); // Optional: a missing audio backend leaves play silent.
+ val sounds = new int[~]{0,_tone(120),_tone(80),audio.BOOP,audio.WIN,audio.LOSE,audio.WIN};
+ // Bottom to top: roughly 333..800 Hz, below the old 1000 Hz brick tone.
+ val brickSounds = new int[~ROWS]{int i -> int period = 144-i*12; _tone(period);};
+
+ // Setup drawing board
+ val c = new sys.draw.Canvas(WIDTH,HEIGHT);
+
+ // Setup game contents
+ val g = new Game;
+ g._reset();
+
+ //
+ int frames = 0, status = gfx.OK;
+ i64 last_ms = sys.time.monotonic(), pending_ms = 0, frame_ms = last_ms;
+
+ while( status == gfx.OK ) {
+ if( gfx.key('Q') || gfx.key(gfx.ESCAPE) ) break;
+ // Physics stays in base coordinates; only drawing and input scale.
+ if( c.resize(gfx.width(),gfx.height()) ) {
+ g.lastMouse = c.localX(gfx.mouseX());
+ frame_ms = 0;
+ }
+ int direction = g._input(c);
+ i64 now_ms = sys.time.monotonic(), elapsed_ms = now_ms-last_ms;
+ last_ms = now_ms;
+ // Drop long stalls instead of teleporting the ball after a window drag.
+ pending_ms += elapsed_ms < 0 ? 0 : elapsed_ms > 64 ? 64 : elapsed_ms;
+ while( pending_ms >= STEP_ms ) { g._tick(direction); pending_ms -= STEP_ms; }
+ if( g.sound != 0 ) {
+ audio.play(g.sound == 3 ? brickSounds[g.soundDepth-1] : sounds[g.sound]);
+ g.sound = 0;
+ }
+ if( now_ms >= frame_ms ) {
+ g._draw(c);
+ status = gfx.presentSize(c.pixels,c.width,c.height);
+ frame_ms = now_ms+FRAME_ms;
+ if( args# > 1 && ++frames == 10 ) break;
+ }
+ if( status == gfx.OK ) status = gfx.wait(STEP_ms-pending_ms);
+ }
+ audio.close(); gfx.close();
+ return status == gfx.ERROR ? 1 : 0;
+};
diff --git a/docs/chapter32/examples/BubbleSort.smp b/docs/chapter32/examples/BubbleSort.smp
new file mode 100644
index 00000000..6bdb13a9
--- /dev/null
+++ b/docs/chapter32/examples/BubbleSort.smp
@@ -0,0 +1,38 @@
+
+// An implementation of
+// https://sampleprograms.io/projects/bubble-sort/
+//
+// Bubble sort, with reading (parsing) and writing (formatting) the data.
+
+val sort = { !sys.aryi64 nums ->
+ sys.aryi64?! more = nums;
+ while( more ) {
+ more = null;
+ for( u32 i = 0; i < nums.len-1; i++ )
+ if( nums.buf[i] > nums.buf[i+1] ) {
+ u32 next = i+1;
+ more = nums.swap(i,next);
+ }
+ }
+};
+
+// Read one process argument of the form "[ 4, 3, 2, 1]" and print it sorted.
+// args[0] is the executable name, as with native C argc/argv.
+val main = { u8[~][] args ->
+ val usage = { ->
+ sys.io.p("Usage: please provide a list of at least two integers to sort in the format \"[1, 2, 3, 4, 5]\"\n");
+ return 0;
+ };
+ if( args# != 2 ) return usage();
+
+ var nums = sys.aryi64.parseAryI64(args[1]);
+ if( !nums ) return usage();
+ if( nums.len < 2 ) return usage();
+
+ // Bubble sort array of integers
+ sort(nums);
+
+ // Print the same bracketed array-list format accepted as input.
+ nums.str().add('\n').write(1);
+ return 0;
+};
diff --git a/docs/chapter32/examples/Capitalize.smp b/docs/chapter32/examples/Capitalize.smp
new file mode 100644
index 00000000..00fdd481
--- /dev/null
+++ b/docs/chapter32/examples/Capitalize.smp
@@ -0,0 +1,23 @@
+
+// An implementation of
+// https://sampleprograms.io/projects/capitalize/
+
+val main = { u8[~][] args ->
+ if( args# > 2 ) {
+ sys.io.p("Use quotes around multiple strings.\n");
+ return 0;
+ }
+ if( args# != 2 || args[1]# == 0 ) {
+ sys.io.p("Usage: please provide a string\n");
+ return 0;
+ }
+
+ u8[~] input = args[1];
+ var output = new u8[input# + 1];
+ u32 len = input#;
+ sys.ary.copy(output,0,input,0,len);
+ output[0] = sys.char.toupper(input[0]);
+ output[input#] = '\n';
+ sys.io.p(output);
+ return 0;
+};
diff --git a/docs/chapter32/examples/Clock.smp b/docs/chapter32/examples/Clock.smp
new file mode 100644
index 00000000..fb50f84e
--- /dev/null
+++ b/docs/chapter32/examples/Clock.smp
@@ -0,0 +1,128 @@
+// Local clocks; click the button or press Space to switch. Q/Escape exits.
+// Any argument runs ten frames, exercising both faces for smoke tests.
+u32 GREEN = 0x62ff70, DIM = 0x123d20, BACKGROUND = 0x020b05;
+
+val main = { u8[~][] args ->
+ val gfx = sys.gfx;
+ val time = sys.time;
+ // The main Canvas
+ val screen = new sys.draw.Canvas(720,540);
+ if( gfx.open("Simple digital and analog clocks",screen.width,screen.height) != gfx.OK ) return 1;
+
+ // Button to flip clock style
+ val button = new sys.draw.Button(220,454,280,52,"ANALOG CLOCK");
+ val timers = new sys.time.Timers();
+ u32 frame_id = timers.every(33);
+ if( frame_id == 0 ) { gfx.close(); return 1; }
+
+ bool analog = false, held = false;
+ int frames = 0, status = gfx.OK;
+
+ // Main event loop
+ while( status == gfx.OK ) {
+ bool resized = screen.resize(gfx.width(),gfx.height());
+ // Did the user press space bar?
+ bool space = gfx.key(' ');
+ // Did the left mouse button go down?
+ bool down = gfx.button(gfx.LEFT);
+ // ANd did it go down over this button?
+ bool click = button.update(screen.localX(gfx.mouseX()),screen.localY(gfx.mouseY()),down);
+ // If clicked, flip the clock mode
+ if( click || (space && !held) ) analog = !analog;
+ held = space;
+ if( gfx.key('Q') ) break;
+ // Change button label
+ button.label = analog ? "DIGITAL CLOCK" : "ANALOG CLOCK";
+ // If the next timer event is the every-33-msec event
+ if( timers.poll(time.monotonic()) == frame_id || resized ) {
+ // Draw the clock screen and button
+ _draw(screen,time.now(),analog);
+ button.draw(screen,3,GREEN,BACKGROUND,DIM);
+ // Presne the canvas on screen
+ status = gfx.presentSize(screen.pixels,screen.width,screen.height);
+ // Testing only: show 5 frames, flip to analog, show 5 more and exit
+ if( args# > 1 ) {
+ frames++;
+ if( frames == 5 ) analog = true;
+ if( frames == 10 ) break;
+ }
+ }
+ if( status != gfx.OK ) break;
+ // Stall until next timer event
+ status = gfx.wait(time.remaining(timers.nextDeadline(),time.monotonic()));
+ }
+ gfx.close();
+ return status == gfx.ERROR ? 1 : 0;
+};
+
+val _draw = { !sys.draw.Canvas screen, i64 wall_ms, i64 analog ->
+ val d = sys.time.local(wall_ms);
+ screen.clear(BACKGROUND);
+ screen.text(266,24,"SIMPLE CLOCK",4,GREEN);
+ if( analog ) _analog(screen,d.hour,d.minute,d.second,d.millisecond);
+ else _digital(screen,d.hour,d.minute,d.second);
+ screen.text(298,412,"%(sys.time.formatLocal(wall_ms,sys.time.DATE))",4,GREEN);
+ screen.text(249,520,"SPACE SWITCH Q OR ESC QUIT",2,GREEN);
+};
+
+// a..g bits: top, upper-right, lower-right, bottom, lower-left, upper-left,
+// middle. Faint unlit bars retain the old LED figure-eight silhouette.
+val _digitFont = new u8[~]{
+ // 0 1 2 3 4 5 6 7 8 9
+ 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f
+};
+val _digitBars = new u8[~]{
+ // x0 y0 x1 y1
+ 14, 0, 58, 0, // a: top
+ 68, 12, 68, 60, // b: upper-right
+ 68, 84, 68, 132, // c: lower-right
+ 14, 144, 58, 144, // d: bottom
+ 4, 84, 4, 132, // e: lower-left
+ 4, 12, 4, 60, // f: upper-left
+ 14, 72, 58, 72 // g: middle
+};
+val _digit = { !sys.draw.Canvas c, int x, int y, i64 digit ->
+ int bits = 0 <= digit < _digitFont# ? _digitFont[digit] : 0;
+ for( int i = 0; i < 7; i++ ) {
+ u32 color = (bits&(1<<i)) != 0 ? GREEN : DIM;
+ int bar = i*4;
+ c.line(x+_digitBars[bar ],y+_digitBars[bar+1],
+ x+_digitBars[bar+2],y+_digitBars[bar+3],10,color);
+ }
+};
+
+val _digital = { !sys.draw.Canvas c, int hour, int minute, int second ->
+ _digit(c, 68,166, hour/10); _digit(c,154,166, hour%10);
+ _digit(c,284,166,minute/10); _digit(c,370,166,minute%10);
+ _digit(c,500,166,second/10); _digit(c,586,166,second%10);
+ for( int i = 0; i < 2; i++ ) {
+ c.fillCircle(254+i*216,214,6,GREEN);
+ c.fillCircle(254+i*216,262,6,GREEN);
+ }
+ c.text(272,352,"LOCAL TIME 24H",3,GREEN);
+};
+val _hand = { !sys.draw.Canvas c, f64 turn, int length, int thickness, u32 color ->
+ f64 angle = turn*2*sys.math.PI;
+ int x = 360+sys.math.sin(angle)*length, y = 232-sys.math.cos(angle)*length;
+ c.line(360,232,x,y,thickness,color);
+};
+val _analog = { !sys.draw.Canvas c, int hour, int minute, int second, int millisecond ->
+ c.circle(360,232,154,3,GREEN);
+ for( int i = 0; i < 60; i++ ) {
+ f64 angle = i/60.0*2*sys.math.PI;
+ bool major = i%5 == 0;
+ int inner = major ? 133 : 143;
+ f64 sine = sys.math.sin(angle), cosine = sys.math.cos(angle);
+ int x0 = 360+sine*inner, y0 = 232-cosine*inner;
+ int x1 = 360+sine* 149 , y1 = 232-cosine* 149 ;
+ c.line(x0,y0,x1,y1,major ? 3 : 1,GREEN);
+ }
+ c.text(349,100,"12",2,GREEN); c.text(484,227,"3",2,GREEN);
+ c.text(357,354, "6",2,GREEN); c.text(230,227,"9",2,GREEN);
+ f64 seconds = second+millisecond/1000.0;
+ f64 minutes = minute+seconds/60.0;
+ _hand(c,(hour%12+minutes/60.0)/12.0,78,8,GREEN);
+ _hand(c,minutes/60.0,112,5,GREEN);
+ _hand(c,seconds/60.0,128,2,0xc3ffcb);
+ c.fillCircle(360,232,6,GREEN);
+};
diff --git a/docs/chapter32/examples/Dijkstra.smp b/docs/chapter32/examples/Dijkstra.smp
new file mode 100644
index 00000000..6591b310
--- /dev/null
+++ b/docs/chapter32/examples/Dijkstra.smp
@@ -0,0 +1,71 @@
+
+// An implementation of
+// https://sampleprograms.io/projects/dijkstra/
+
+val shortestPath = { !sys.aryi64 matrix, int nodes, int src, int dst ->
+ i64 infinity = sys.integer.MAX_I64;
+ var visited = new sys.adt.bitset();
+ // All nodes are infinitely far from each other, except the starting point
+ var dist = new i64[nodes]{ int i -> i == src ? 0 : infinity; };
+
+ i64 result = -1;
+ int count = 0;
+ while( count < nodes && result < 0 ) {
+ int nearest = -1;
+ i64 best = infinity;
+ for( int node = 0; node < nodes; node++ )
+ if( !visited.get(node) && dist[node] < best ) {
+ nearest = node;
+ best = dist[node];
+ }
+ if( nearest < 0 ) count = nodes;
+ else {
+ if( nearest == dst ) return best;
+ visited.set(nearest);
+ for( int node = 0; node < nodes; node++ ) {
+ u32 index = nearest*nodes + node;
+ i64 weight = matrix.get(index);
+ if( weight > 0 && !visited.get(node) && best+weight < dist[node] )
+ dist[node] = best+weight;
+ }
+ }
+ count++;
+ }
+ return result;
+};
+
+val usage = { ->
+ sys.io.p("Usage: please provide three inputs: a serialized matrix, a source node and a destination node\n");
+ return 0;
+};
+
+val main = { u8[~][] args ->
+ // Exactly 3 args
+ if( args# != 4 ) return usage();
+ // First is a serialized square matrix of positive numbers
+ var matrix = sys.aryi64.parseAryI64(args[1]);
+ if( !matrix ) return usage();
+ if( !matrix.len ) return usage();
+ // All numbers are positive
+ for( u32 i = 0; i < matrix.len; i++ )
+ if( matrix.get(i) < 0 ) return usage();
+ // Matrix is square
+ int nodes = 0;
+ while( nodes*nodes < matrix.len ) nodes++;
+ if( nodes*nodes != matrix.len )
+ return usage(); // Not a square matrix
+
+ // src,dst are values within the matrix
+ i64 src = sys.aryu8.atoi(args[2]);
+ i64 dst = sys.aryu8.atoi(args[3]);
+ if( src < 0 || src >= nodes || dst < 0 || dst >= nodes )
+ return usage(); // Source and destination land within the graph
+
+ int source = src, destination = dst;
+ i64 cost = shortestPath(matrix,nodes,source,destination);
+ if( cost >= 0 ) {
+ new sys.aryu8().num(cost).add('\n').write(1);
+ return 0;
+ }
+ return usage();
+};
diff --git a/docs/chapter32/examples/FileIO.smp b/docs/chapter32/examples/FileIO.smp
new file mode 100644
index 00000000..59b3159e
--- /dev/null
+++ b/docs/chapter32/examples/FileIO.smp
@@ -0,0 +1,52 @@
+
+// An implementation of
+// https://sampleprograms.io/projects/file-input-output/
+
+val FILE = "output.txt";
+
+val main = { u8[~][] args ->
+ var str = new sys.aryu8();
+ str.addAry("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\n");
+ str.addAry("Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n");
+ str.addAry("Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.\n");
+ str.addAry("Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n");
+
+ // Create
+ i32 fd = sys.io.create(FILE);
+ if( fd == -1 ) return _error();
+ // Write
+ u32 len = str.len;
+ int wrote = sys.io.writeOff(fd,str.buf,0,len);
+ if( wrote == -1 ) return _error();
+ if( wrote != str.len ) return _error2(-2);
+ // Close
+ if( sys.io.close(fd) != 0 ) return _error();
+
+ // Open
+ i32 fd2 = sys.io.open(FILE);
+ if( fd2 == -1 ) return _error();
+ // Read
+ var got = sys.io.read(fd2);
+ if( !got ) return _error();
+ if( got# != str.len ) return _error2(-3);
+ // Close
+ if( sys.io.close(fd2) != 0 ) return _error();
+
+ // Check contents are equal
+ if( sys.ary.cmp(got,0,str.buf,0,len) )
+ return _error2(-4);
+
+ // Remove
+ if( sys.io.remove(FILE) != 0 ) return _error();
+
+ sys.io.p("File I/O succeeded\n");
+ return 0;
+};
+
+val _error2 = { i32 errno ->
+ sys.io.remove(FILE);
+ new sys.aryu8().addAry("Failed with error code ").num(errno).add('\n').write(sys.libc.STDERR);
+ sys.libc._exit(errno);
+};
+
+val _error = { -> _error2(sys.libc.errno()); };
diff --git a/docs/chapter32/examples/Graphics.smp b/docs/chapter32/examples/Graphics.smp
new file mode 100644
index 00000000..1878e97d
--- /dev/null
+++ b/docs/chapter32/examples/Graphics.smp
@@ -0,0 +1,26 @@
+// Optional graphics smoke test: pixels are drawn entirely in Simple.
+// Pass any argument for a short, self-closing test; otherwise close or press Esc.
+val main = { u8[~][] args ->
+ if( sys.gfx.open("Simple pixels",320,240) != sys.gfx.OK ) return 1;
+ val c = new sys.draw.Canvas(320,240);
+ int result = sys.gfx.OK;
+ bool dirty = true;
+ int frames = 0;
+ while( result == sys.gfx.OK ) {
+ if( c.resize(sys.gfx.width(),sys.gfx.height()) ) dirty = true;
+ if( dirty ) {
+ // The gradient fills the window, including non-4:3 shapes.
+ int dx = c.width > 1 ? c.width-1 : 1, dy = c.height > 1 ? c.height-1 : 1;
+ for( int y = 0; y < c.height; y++ )
+ for( int x = 0; x < c.width; x++ )
+ c.pixels[y*c.width+x] = (x*255/dx << 16) | (y*255/dy << 8) | 64;
+ result = sys.gfx.presentSize(c.pixels,c.width,c.height);
+ if( result != sys.gfx.OK ) break;
+ dirty = false;
+ }
+ result = sys.gfx.poll(true);
+ if( args# > 1 && ++frames == 5 ) break;
+ }
+ sys.gfx.close();
+ return result == sys.gfx.ERROR ? 1 : 0;
+};
diff --git a/docs/chapter32/examples/README.md b/docs/chapter32/examples/README.md
new file mode 100644
index 00000000..df092e88
--- /dev/null
+++ b/docs/chapter32/examples/README.md
@@ -0,0 +1,119 @@
+# Runnable examples
+
+These programs live beside the documentation so readers can find and run them.
+Their non-graphical native regression tests run as part of `make tests`.
+All four graphical demos support window resizing. Clock, Tic-tac-toe, and
+Breakout scale their base layouts uniformly and center them in the window;
+mouse input follows the same transform. Breakout keeps its physics in base
+coordinates, so resizing preserves the current game and ball speed. The pixel
+gradient fills the entire window at its new resolution.
+The optional [pixel-window example](Graphics.smp) uses MiniFB; see
+[graphics setup](../../src/main/smp/sys/gfx.md). `make run-graphics` opens it explicitly.
+The [graphical tic-tac-toe](TicTacToeGraphical.smp) uses the Simple
+[drawing library](../../src/main/smp/sys/draw/README.md). Run it with
+`make run-graphical-tictactoe`; click a cell or press 1–9, R/Space to
+replay, and Q/Escape to quit. The terminal game below remains available.
+Optional [background audio](../../src/main/smp/sys/audio.md) supplies soft move and win/loss cues.
+
+The [digital and analog clock](Clock.smp) demonstrates the [time library](../../src/main/smp/sys/time/README.md),
+green seven-segment digits, smooth clock hands, and a reusable software button.
+Run `make run-clock`; click the button or press Space to switch faces,
+and Q/Escape to exit. Both faces show system-local time.
+`make clock-example` builds it without starting a window.
+
+The [Breakout game](Breakout.smp) has 24 columns and 8 rows, with colors and
+point values by depth: 1 at the bottom through 8 at the top, 864 points total.
+Clear the wall before losing all three balls. Mouse movement or the arrow keys
+move the paddle; Space/left click serves, P pauses, R restarts, Q/Escape exits.
+Run `make run-breakout` or build only with `make breakout`.
+The familiar paddle, serve, and limited-ball rules follow
+[Atari's Breakout instructions](https://atari.com/pages/breakout).
+
+The deepest row reached with the current ball sets the base speed: 320 pixels/second plus 35 for
+each additional depth. After touching the back wall, hitting the top of a brick
+activates a **one-time 1.65x speed boost**; side/front hits do not. Returning to
+the paddle disarms that trip's back-wall opportunity. Losing a ball resets depth
+and boost, so each new ball starts at 320 pixels/second and can earn its own
+back-wall boost. Edge hits on the paddle give a wider
+rebound than center hits. Clear all bricks to win; no new wall replaces them.
+
+Physics uses fixed 8 ms ticks with movement split into steps of at most two
+pixels, including at boosted speed. Rendering runs roughly every 16 ms. The
+brick and sound tables demonstrate array initializers; the short bounce tones
+use read-only PCM arrays made by index functions. Brick boops rise in pitch with
+row depth, from about 333 Hz at the bottom to 800 Hz at the top. Audio is optional. Native
+tests in `BreakoutTest` exercise collisions, scoring, lives, pause, paddle angles,
+the boost, and clearing the whole wall without a display or audio device.
+
+From `chapter32`, build the tic-tac-toe executable (without starting it):
+
+```sh
+make lib tictactoe
+```
+
+Run the Windows build from PowerShell:
+
+```powershell
+.\build\examples\x86_64_v2_win64\TicTacToe.exe
+```
+
+Or from Command Prompt (`cmd.exe`):
+
+```bat
+.\build\examples\x86_64_v2_win64\TicTacToe.exe
+```
+
+Or from Bash (Cygwin, using the Windows build):
+
+```bash
+./build/examples/x86_64_v2_win64/TicTacToe.exe
+```
+
+The Windows executable uses Cygwin's runtime; its `bin` directory must be on
+`PATH` (as it is when building with Cygwin GCC).
+
+For a native Linux build, run these commands from this same `chapter32`
+directory in WSL. Separate Java and native output directories let the Windows
+and Linux builds coexist:
+
+```sh
+make lib tictactoe CLZDIR=build/classes-linux
+./build/examples/x86_64_v2_SystemV/TicTacToe
+```
+
+From PowerShell, prefix either command with `wsl -d Ubuntu-24.04 --`.
+On a standalone Linux checkout, `CLZDIR` can be omitted.
+The compiler's `--link` option produces an executable without running it;
+`--norun` continues to produce object files only.
+
+`TicTacToe.smp` currently prints the welcome, square numbering, and empty board,
+then waits for a move. Press **1–9** without Enter to place X, or
+**q**, Escape, Ctrl-C, or Ctrl-D to quit. Enter is silently ignored; other
+invalid keys and occupied squares prompt again without taking a turn. The board
+is printed after each player and CPU move; only accepted move digits are echoed.
+Play continues until someone wins or the board is
+full. The CPU takes an immediate win, blocks an immediate loss, then prefers
+the center, corners, and edges.
+
+Other examples are Hello World (`A_helloWorld.smp`), `BubbleSort.smp`,
+`Capitalize.smp`, `Dijkstra.smp`, and `FileIO.smp`. The latter creates, checks,
+and removes `output.txt` in the working directory.
+
+## Single-keystroke input
+
+`sys.io.getch()` blocks for one byte without terminal editing or echo. It returns
+0–255 for a byte, or -1 for EOF or an error. On -1, `sys.libc.errno()` is
+`sys.libc.EOF` (-1) for end-of-input, otherwise the OS error code.
+Terminal Ctrl-C and Ctrl-D are bytes 3
+and 4, so the application decides how to handle them. Unicode and function keys
+may produce multiple bytes; this is an ASCII-oriented byte API, not a key-event
+decoder.
+
+The small C runtime adapter uses [POSIX terminal modes](https://man7.org/linux/man-pages/man3/termios.3.html),
+including Cygwin on Windows. It restores the saved mode before returning,
+including after an interrupted read. Files and pipes use an ordinary one-byte
+read. `make test CLASS=TerminalInputTest` runs the Java regression tests for
+redirected input, errors, prompt output, Enter, and Escape. Check terminal
+editing, echo, and mode restoration by running the executable in a terminal.
+`make test CLASS=TicTacToeTest` checks complete games, all eight winning lines,
+draws, occupied squares, and CPU blocking.
diff --git a/docs/chapter32/examples/TicTacToe.smp b/docs/chapter32/examples/TicTacToe.smp
new file mode 100644
index 00000000..ee4e3182
--- /dev/null
+++ b/docs/chapter32/examples/TicTacToe.smp
@@ -0,0 +1,132 @@
+// Player is X, CPU is O. Squares are numbered left-to-right, top-to-bottom.
+val main = { u8[~][] args ->
+ sys.io.p("Tic-tac-toe!\nYou are X; the CPU is O. You go first.\n");
+ sys.io.p("Press a square's number (no Enter needed), or q/Esc to quit.\n");
+ sys.io.p("Squares:\n 1 | 2 | 3 \n---+---+---\n 4 | 5 | 6 \n---+---+---\n 7 | 8 | 9 \n\n");
+ val board = new u8[9]{ int i -> ' '; }; // Initialize the board
+ // Draw empty board
+ _draw(board);
+
+ while( true ) {
+ sys.io.p("Your move (1-9): ");
+ // Valid user move 1-9, or 0 for quitting
+ int square = _validMove(board) - 1;
+ if( square < 0 ) return 0;
+ // Set user choice; print board
+ board[square] = 'X';
+ sys.io.p("\n");
+ _draw(board);
+ // A winner?
+ if( _finished(board) ) return 0;
+ // Compute CPU move
+ int reply = _cpu(board);
+ // Set CPU choice; print board
+ board[reply] = 'O';
+ sys.io.p("CPU plays %(reply+1).\n");
+ _draw(board);
+ // A winner?
+ if( _finished(board) ) return 0;
+ }
+};
+
+// Return with a valid user move 1-9, or 0 to exit
+val _validMove = { u8[~] board ->
+ while( true ) {
+ int key = sys.io.getch();
+ if( key == -1 && sys.libc.errno() != sys.libc.EOF ) {
+ sys.io.err("\nUnable to read the keyboard.\n");
+ return 0;
+ }
+ // Various quitting conditions
+ if( key == -1 || key == 'q' || key == 'Q' || key == 27 || key == 3 || key == 4 ) {
+ sys.io.p("\nGoodbye!\n");
+ return 0;
+ }
+ // Ignore CR/LF
+ if( key == '\r' || key == '\n' ) continue;
+
+ // Valid choice
+ if( key < '1' || key > '9' ) {
+ sys.io.p("\nChoose a square from 1 to 9: ");
+ continue;
+ }
+ if( board[key-'1'] != ' ' ) {
+ sys.io.p("\nThat square is occupied. Your move (1-9): ");
+ continue;
+ }
+ sys.io.p("%c(key)");
+ return key-'0';
+ }
+};
+
+// Return the winning mark, or zero.
+val _winner = { u8[~] board ->
+ for( int i = 0; i < 3; i++ ) {
+ int row = i*3;
+ if( board[row] != ' ' && board[row] == board[row+1] && board[row] == board[row+2] )
+ return board[row];
+ if( board[i] != ' ' && board[i] == board[i+3] && board[i] == board[i+6] )
+ return board[i];
+ }
+ if( board[4] != ' ' ) {
+ if( board[0] == board[4] && board[4] == board[8] ) return board[4];
+ if( board[2] == board[4] && board[4] == board[6] ) return board[4];
+ }
+ return 0;
+};
+
+val _finished = { u8[~] board ->
+ int winner = _winner(board);
+ if( winner == 'X' ) { sys.io.p("You win!\n"); return true; }
+ if( winner == 'O' ) { sys.io.p("CPU wins!\n"); return true; }
+ for( int i = 0; i < board#; i++ )
+ if( board[i] == ' ' ) return false;
+ sys.io.p("It's a draw!\n");
+ return true;
+};
+
+// Try each empty square, restoring it before returning.
+val _threat = { u8[] board, u8 mark ->
+ for( int i = 0; i < board#; i++ ) {
+ if( board[i] == ' ' ) {
+ board[i] = mark;
+ bool wins = _winner(board) == mark;
+ board[i] = ' '; // Restore board
+ if( wins ) return i;
+ }
+ }
+ return -1;
+};
+
+// Win if possible, otherwise block, then prefer center, corners, and edges.
+// Called only after _finished has ruled out a full board.
+val _cpu = { u8[] board ->
+ // If O can win, do so
+ int win = _threat(board,'O');
+ if( win >= 0 ) return win;
+ // If X will win next move, block
+ int block = _threat(board,'X');
+ if( block >= 0 ) return block;
+ // If center is open, take it
+ if( board[4] == ' ' ) return 4;
+ // If a corner is open, take it
+ for( int i = 0; i < board#; i += 2 )
+ if( board[i] == ' ' ) return i;
+ // Take whatever is available
+ for( int i = 0; i < board#; i++ )
+ if( board[i] == ' ' ) return i;
+ return -1;
+};
+
+val _draw = { u8[~] board ->
+ val out = new sys.aryu8();
+ for( int row = 0; row < 3; row++ ) {
+ for( int col = 0; col < 3; col++ ) {
+ out.add(' ').add(board[row*3+col]).add(' ');
+ if( col < 2 ) out.add('|');
+ }
+ out.add('\n');
+ if( row < 2 ) out.addAry("---+---+---\n");
+ }
+ out.write(sys.libc.STDOUT);
+};
diff --git a/docs/chapter32/examples/TicTacToeGraphical.smp b/docs/chapter32/examples/TicTacToeGraphical.smp
new file mode 100644
index 00000000..72ee6522
--- /dev/null
+++ b/docs/chapter32/examples/TicTacToeGraphical.smp
@@ -0,0 +1,169 @@
+// Player is X, CPU is O. Squares are numbered left-to-right, top-to-bottom.
+// Graphical tic-tac-toe; the same strategy as TicTacToe.smp.
+// Click an empty square or press 1-9. R/Space replays; Q/Escape quits.
+// Pass any argument for a five-poll window smoke test.
+val main = { u8[~][] args ->
+ val screen = new sys.draw.Canvas(600,780);
+ val board = new u8[9];
+ _reset(board);
+ if( sys.gfx.open("Simple tic-tac-toe",screen.width,screen.height) != sys.gfx.OK ) return 1;
+ sys.audio.open(); // Audio is optional; failure leaves the game silent.
+ _draw(screen,board,-1);
+ int result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height);
+ bool mouseHeld = false, keyHeld = false, replayHeld = false;
+ int hover = -1, frames = 0;
+
+ while( result == sys.gfx.OK ) {
+ result = sys.gfx.wait(17);
+ if( result != sys.gfx.OK ) break;
+ if( sys.gfx.key('Q') ) break;
+ bool down = sys.gfx.button(sys.gfx.LEFT);
+ bool replay = sys.gfx.key('R') || sys.gfx.key(' ');
+ bool resized = screen.resize(sys.gfx.width(),sys.gfx.height());
+ int square = _square(screen.localX(sys.gfx.mouseX()),screen.localY(sys.gfx.mouseY()));
+ bool dirty = resized || square != hover;
+ hover = square;
+ if( replay && !replayHeld ) { sys.audio.stop(); _reset(board); dirty = true; }
+ bool digit = false;
+ int choice = down && !mouseHeld ? square : -1;
+ for( int i = 0; i < 9; i++ ) {
+ int key = '1'+i;
+ if( sys.gfx.key(key) ) {
+ digit = true;
+ if( !keyHeld ) choice = i;
+ }
+ }
+ if( !(replay && !replayHeld) && _move(board,choice) ) {
+ sys.audio.play(_sound(board));
+ dirty = true;
+ }
+ mouseHeld = down;
+ keyHeld = digit;
+ replayHeld = replay;
+ if( dirty ) {
+ _draw(screen,board,hover);
+ result = sys.gfx.presentSize(screen.pixels,screen.width,screen.height);
+ }
+ if( args# > 1 && ++frames == 5 ) break;
+ }
+ sys.audio.close();
+ sys.gfx.close();
+ return result == sys.gfx.ERROR ? 1 : 0;
+};
+
+// Called only for an accepted move; invalid input never requests a sound.
+val _sound = { u8[~] board ->
+ int winner = _winner(board);
+ return winner == 'X' ? sys.audio.WIN : winner == 'O' ? sys.audio.LOSE : sys.audio.BOOP;
+};
+
+val _reset = { u8[] board ->
+ for( int i = 0; i < 9; i++ ) board[i] = ' ';
+};
+val _square = { int x, int y ->
+ if( x < 48 || x >= 552 || y < 168 || y >= 672 ) return -1;
+ return (y-168)/168*3+(x-48)/168;
+};
+
+// One player turn followed by one CPU turn. Invalid/finished moves do nothing.
+val _move = { u8[] board, int square ->
+ if( square < 0 || square >= 9 || board[square] != ' ' || _finished(board) ) return false;
+ board[square] = 'X';
+ if( !_finished(board) ) {
+ int reply = _cpu(board);
+ if( reply >= 0 ) board[reply] = 'O';
+ }
+ return true;
+};
+
+val _finished = { u8[~] board ->
+ if( _winner(board) ) return true;
+ for( int i = 0; i < 9; i++ ) if( board[i] == ' ' ) return false;
+ return true;
+};
+
+val _winningLine = { u8[~] board ->
+ for( int i = 0; i < 3; i++ ) {
+ int row = i*3;
+ if( board[row] != ' ' && board[row] == board[row+1] && board[row] == board[row+2] ) return i;
+ if( board[i] != ' ' && board[i] == board[i+3] && board[i] == board[i+6] ) return 3+i;
+ }
+ if( board[4] != ' ' ) {
+ if( board[0] == board[4] && board[4] == board[8] ) return 6;
+ if( board[2] == board[4] && board[4] == board[6] ) return 7;
+ }
+ return -1;
+};
+// Return the winning mark, or zero.
+val _winner = { u8[~] board ->
+ int line = _winningLine(board);
+ return line < 0 ? 0 : line < 3 ? board[line*3] : line < 6 ? board[line-3] : board[4];
+};
+
+// Try each empty square, restoring it before returning.
+val _threat = { u8[] board, u8 mark ->
+ for( int i = 0; i < 9; i++ )
+ if( board[i] == ' ' ) {
+ board[i] = mark;
+ bool wins = _winner(board) == mark;
+ board[i] = ' '; // Restore board
+ if( wins ) return i;
+ }
+ return -1;
+};
+// Win if possible, otherwise block, then prefer center, corners, and edges.
+// Called only after _finished has ruled out a full board.
+val _cpu = { u8[] board ->
+ // If O can win, do so
+ int win = _threat(board,'O');
+ if( win >= 0 ) return win;
+ // If X will win next move, block
+ int block = _threat(board,'X');
+ if( block >= 0 ) return block;
+ // If center is open, take it
+ if( board[4] == ' ' ) return 4;
+ // If a corner is open, take it
+ for( int i = 0; i < 9; i += 2 ) if( board[i] == ' ' ) return i;
+ // Take whatever is available
+ for( int i = 0; i < 9; i++ ) if( board[i] == ' ' ) return i;
+ return -1;
+};
+
+val _draw = { !sys.draw.Canvas screen, u8[~] board, int hover ->
+ u32 background = 0x142e36, paper = 0xf2eddf, ink = 0x35535a;
+ u32 cross = 0xe47b57, ring = 0x248b89, accent = 0xf0c778;
+ int winner = _winner(board);
+ bool finished = _finished(board);
+ screen.clear(background);
+ screen.text(48,34,"TIC TAC TOE",6,paper);
+ screen.fillRect(48,90,504,3,ink);
+ screen.text(48,116,finished ? (winner == 'X' ? "YOU WIN!" : winner == 'O' ? "CPU WINS" : "DRAW") : "YOUR TURN",4,accent);
+ screen.line(428,112,450,134,5,cross).line(450,112,428,134,5,cross);
+ screen.circle(496,123,13,5,0x70c9bf);
+ screen.text(428,145,"YOU",2,0xa2b9b7);
+ screen.text(484,145,"CPU",2,0xa2b9b7);
+ screen.fillRect(48,168,504,504,paper);
+ if( !finished && hover >= 0 && hover < 9 && board[hover] == ' ' )
+ screen.fillRect(48+(hover%3)*168,168+hover/3*168,168,168,0xd9e8de);
+ for( int i = 1; i < 3; i++ ) {
+ screen.fillRect(48+i*168-3,168,6,504,ink);
+ screen.fillRect(48,168+i*168-3,504,6,ink);
+ }
+ for( int i = 0; i < 9; i++ ) {
+ int cx = 132+(i%3)*168, cy = 252+i/3*168;
+ if( board[i] == 'X' )
+ screen.line(cx-38,cy-38,cx+38,cy+38,12,cross).line(cx+38,cy-38,cx-38,cy+38,12,cross);
+ else if( board[i] == 'O' ) screen.circle(cx,cy,48,11,ring);
+ else screen.text(cx-6,cy-10,i == 0 ? "1" : i == 1 ? "2" : i == 2 ? "3" :
+ i == 3 ? "4" : i == 4 ? "5" : i == 5 ? "6" : i == 6 ? "7" : i == 7 ? "8" : "9",4,0x95a59e);
+ }
+ int line = _winningLine(board);
+ if( line >= 0 ) {
+ int first = line < 3 ? line*3 : line < 6 ? line-3 : line == 6 ? 0 : 2;
+ int last = line < 3 ? first+2 : line < 6 ? first+6 : line == 6 ? 8 : 6;
+ screen.line(132+(first%3)*168,252+first/3*168,132+(last%3)*168,252+last/3*168,5,0xeab64e);
+ }
+ screen.text(48,704,"CLICK A SQUARE OR PRESS 1-9",3,paper);
+ screen.text(48,738,"R OR SPACE REPLAY Q OR ESC QUIT",3,0xa2b9b7);
+ screen.rect(48,168,504,504,3,ink);
+};
diff --git a/src/main/c/simple_graphics.c b/src/main/c/simple_graphics.c
index a35c28a6..a1c0e952 100644
--- a/src/main/c/simple_graphics.c
+++ b/src/main/c/simple_graphics.c
@@ -36,7 +36,7 @@ static void *find_backend(void) {
}
const char *relative[]={"./" BACKEND_NAME,
"./build/release/" BACKEND_ABI "/" BACKEND_NAME,
- "./chapter31/build/release/" BACKEND_ABI "/" BACKEND_NAME};
+ "./chapter32/build/release/" BACKEND_ABI "/" BACKEND_NAME};
for (unsigned i=0;i<sizeof(relative)/sizeof(*relative);++i) {
void *handle=dlopen(relative[i],RTLD_NOW | RTLD_LOCAL);
if (handle) return handle;
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;
}
diff --git a/src/main/smp/sys/audio.md b/src/main/smp/sys/audio.md
index bb2ad77c..ba02e4d9 100644
--- a/src/main/smp/sys/audio.md
+++ b/src/main/smp/sys/audio.md
@@ -1,6 +1,6 @@
# Optional background audio
-[Chapter 31](../../../../README.md#graphics-and-sound) introduces the library.
+[Chapter 31](../../../../../chapter31/README.md#graphics-and-sound) introduces the library.
The Simple API is implemented in [audio.smp](audio.smp), with the native adapter
in [simple_miniaudio.c](../../c/simple_miniaudio.c).
@@ -9,7 +9,7 @@ optional native C backend. Playback runs on its own thread; the game keeps
processing input and drawing. No Python, CMake, codec packages, or sound files
are needed. Default builds/tests never download miniaudio or open a device.
-From `chapter31`:
+From `chapter32`:
```sh
make libs # Once while online
@@ -21,7 +21,7 @@ The last command builds both optional backends and runs a tictactoe game with
sounds. Accepted moves get a quiet 70ms sine boop. A player win gets a 480ms
rising C-E-G celebration; a CPU win reverses the notes
-For direct execution from `chapter31`, configure both backends and launch the
+For direct execution from `chapter32`, configure both backends and launch the
game using your shell.
PowerShell:
diff --git a/src/main/smp/sys/draw/README.md b/src/main/smp/sys/draw/README.md
index 7d3bf6c8..c1b91ac1 100644
--- a/src/main/smp/sys/draw/README.md
+++ b/src/main/smp/sys/draw/README.md
@@ -1,6 +1,6 @@
# Drawing in Simple
-[Chapter 31](../../../../../README.md#graphics-and-sound) introduces the library.
+[Chapter 31](../../../../../../chapter31/README.md#graphics-and-sound) introduces the library.
The implementation is in [Canvas.smp](Canvas.smp), [Button.smp](Button.smp),
and the [draw module](../draw.smp).
@@ -93,7 +93,7 @@ and a Space shortcut in the same single-threaded loop.
## Graphical tic-tac-toe
-From `chapter31`:
+From `chapter32`:
```sh
make run-graphical-tictactoe
diff --git a/src/main/smp/sys/gfx.md b/src/main/smp/sys/gfx.md
index 931d985f..61a2aba5 100644
--- a/src/main/smp/sys/gfx.md
+++ b/src/main/smp/sys/gfx.md
@@ -1,6 +1,6 @@
# Optional graphics
-[Chapter 31](../../../../README.md#graphics-and-sound) introduces the library.
+[Chapter 31](../../../../../chapter31/README.md#graphics-and-sound) introduces the library.
The Simple API is implemented in [gfx.smp](gfx.smp), with the window adapter in
[simple_minifb.c](../../c/simple_minifb.c).
@@ -15,7 +15,7 @@ The game run target also builds optional [background audio](audio.md).
## Default: no graphics dependency
-From `chapter31`, the usual `make release`, `make tests`, and `make tictactoe`
+From `chapter32`, the usual `make release`, `make tests`, and `make tictactoe`
need no MiniFB, graphics headers, OpenGL, CMake, or running display. Nothing
downloads dependencies unless you explicitly request `make libs` or `make init`
(`make lib` remains a setup alias). Build and run targets never use the network.
@@ -32,7 +32,7 @@ the process. Non-graphics programs ignore even a broken graphics configuration.
## Build the optional backend
-From `chapter31`:
+From `chapter32`:
```sh
make libs # Once while online; fills the persistent lib/ cache.
@@ -68,7 +68,7 @@ also demonstrates the diagnostic and exit status 1 when graphics is absent.
or release Escape to exit. Passing any argument to the executable makes it
close after five polling iterations, for a quick smoke test.
-To run directly from `chapter31` in PowerShell:
+To run directly from `chapter32` in PowerShell:
```powershell
$env:SIMPLE_MINIFB = (Resolve-Path build/release/x86_64_v2_win64/simple_minifb.dll).Path
@@ -92,7 +92,7 @@ export SIMPLE_MINIFB="$PWD/build/release/x86_64_v2_win64/simple_minifb.dll"
For WSL, from the repository root:
```sh
-wsl -d Ubuntu-24.04 -- bash -lc 'cd chapter31 && make graphics graphics-example CLZDIR=build/classes-linux'
+wsl -d Ubuntu-24.04 -- bash -lc 'cd chapter32 && make graphics graphics-example CLZDIR=build/classes-linux'
```
Inside WSL, set `SIMPLE_MINIFB` to the full path of the Linux `.so`, then run
@@ -107,7 +107,7 @@ With no `SIMPLE_MINIFB` setting, the runtime searches beside the executable,
then its `../../release/<ABI>` and `../release/<ABI>` directories. These cover
the examples and test build layouts regardless of the current directory.
It also checks the current directory, `build/release/<ABI>`, and
-`chapter31/build/release/<ABI>` relative to the current directory. Thus built
+`chapter32/build/release/<ABI>` relative to the current directory. Thus built
examples such as `Clock.exe` can be launched directly without configuration.
`SIMPLE_MINIFB` overrides discovery; an invalid explicit path reports an error
diff --git a/src/main/smp/sys/time/README.md b/src/main/smp/sys/time/README.md
index baa920cb..602015e9 100644
--- a/src/main/smp/sys/time/README.md
+++ b/src/main/smp/sys/time/README.md
@@ -1,6 +1,6 @@
# Time and single-threaded animation
-[Chapter 31](../../../../../README.md#time-library) introduces the library.
+[Chapter 31](../../../../../../chapter31/README.md#time-library) introduces the library.
The implementation is in [time.smp](../time.smp), [DateTime.smp](DateTime.smp),
and [Timers.smp](Timers.smp).
@@ -122,8 +122,8 @@ The [digital and analog clock example](../../../../../docs/examples/Clock.smp) c
the repository root, with graphics dependencies already cached:
```sh
-make -C chapter31 clock-example # Build without opening a window.
-make -C chapter31 run-clock # Build the backend and run.
+make -C chapter32 clock-example # Build without opening a window.
+make -C chapter32 run-clock # Build the backend and run.
```
Click the button or press Space to switch between green seven-segment digits
diff --git a/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java b/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java
index 0e4c230a..5399aecf 100644
--- a/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java
+++ b/src/test/java/com/seaofnodes/simple/AssemblyDumpTest.java
@@ -13,25 +13,39 @@ public class AssemblyDumpTest {
@Test public void libraryUnitsAndGlyphs() throws Exception {
Path root=Path.of("build/objs/assembly-dump");
Files.createDirectories(root);
- Path build=Files.createTempDirectory(root,"sys-");
- CodeGen code=new CodeGen("src/main/smp",build.toString(),null,"sys",null,123,true,TypeInteger.BOT)
+ Path fixture=Files.createTempDirectory(root,"font-");
+ Path source=Files.createDirectories(fixture.resolve("src"));
+ Path build=Files.createDirectories(fixture.resolve("obj"));
+ Files.createDirectories(source.resolve("Atlas"));
+ // Use the real font, but only two tiny modules: drawing integration is
+ // covered by DrawTest. This test needs multiple units and constant data.
+ String canvasSource=Files.readString(Path.of("src/main/smp/sys/draw/Canvas.smp"));
+ int fontStart=canvasSource.indexOf("val _glyphs =");
+ assertTrue("Font declaration",fontStart>=0);
+ int fontEnd=canvasSource.indexOf("};",fontStart);
+ assertTrue("Font initializer",fontEnd>=0);
+ Files.writeString(source.resolve("Atlas/Font.smp"),canvasSource.substring(fontStart,fontEnd+2)+
+ "\nval glyph={int i -> _glyphs[i];};\n");
+ Files.writeString(source.resolve("Atlas.smp"),"val glyph={int i -> Font.glyph(i);};\n");
+ CodeGen code=new CodeGen(source.toString(),build.toString(),null,"Atlas",null,123,true,TypeInteger.BOT)
.driver(CodeGen.Phase.Serialize,TestC.CPU_PORT,TestC.CALL_CONVENTION)
.driver(CodeGen.Phase.Encoding,TestC.CPU_PORT,TestC.CALL_CONVENTION);
var entry=code._encoding;
String before=code.asm();
assertSame("Dumping another unit must not change the active encoding",entry,code._encoding);
+ assertEquals(2,code._compunits.size());
for( var unit : code._compunits.values() )
if( unit._src!=null ) {
String heading="=== Compilation unit: "+unit._cname+" ===";
assertEquals("Exactly one heading for "+unit._cname,2,before.split(heading,-1).length);
}
- int start=before.indexOf("=== Compilation unit: sys.draw.Canvas ===");
+ int start=before.indexOf("=== Compilation unit: Atlas.Font ===");
assertTrue(start>=0);
int end=before.indexOf("=== Compilation unit:",start+1);
String canvas=before.substring(start,end<0 ? before.length() : end);
assertTrue(canvas.contains("Constant Pool"));
- assertTrue(canvas.contains("sys.draw.Canvas._glyphs: []u16"));
- TypeMemPtr ptr=(TypeMemPtr)code._compunits.get("sys/draw/Canvas")._clz.field("_glyphs")._t;
+ assertTrue(canvas.contains("Atlas.Font._glyphs: []u16"));
+ TypeMemPtr ptr=(TypeMemPtr)code._compunits.get("Atlas/Font")._clz.field("_glyphs")._t;
TypeConAry glyphs=(TypeConAry)ptr._obj.field("[]")._t;
assertEquals(96,glyphs.len());
BAOS bytes=new BAOS();
@@ -40,10 +54,10 @@ public class AssemblyDumpTest {
canvas.contains("60000000"+HexFormat.of().formatHex(bytes.toByteArray())));
code.exportELF(false,false);
com.seaofnodes.simple.codegen.PrintRegTestSupport.checkDataAliases(
- build.resolve("sys/draw/Canvas.o"),196,"sys.draw.Canvas._glyphs");
+ build.resolve("Atlas/Font.o"),196,"Atlas.Font._glyphs");
assertSame(entry,code._encoding);
assertEquals("Export must not truncate the dump to its entry unit",before,code.asm());
- Files.writeString(build.resolve("sys.asm"),before);
+ Files.writeString(build.resolve("Atlas.asm"),before);
}
@Test public void combinedEncodingAndEarlierPhase() {
diff --git a/src/test/java/com/seaofnodes/simple/BAOSTest.java b/src/test/java/com/seaofnodes/simple/BAOSTest.java
new file mode 100644
index 00000000..03e53b6d
--- /dev/null
+++ b/src/test/java/com/seaofnodes/simple/BAOSTest.java
@@ -0,0 +1,58 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.type.PackedTypeTestSupport;
+import com.seaofnodes.simple.util.BAOS;
+import java.util.Random;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class BAOSTest {
+ @Test public void packedIntBoundaries() {
+ int[] values={Integer.MIN_VALUE,-134217729,-134217728,-1048577,-1048576,
+ -8193,-8192,-65,-64,-1,0,1,63,64,8191,8192,1048575,1048576,
+ 134217727,134217728,Integer.MAX_VALUE};
+ int[] widths={5,5,4,4,3,3,2,2,1,1,1,1,1,2,2,3,3,4,4,5,5};
+ BAOS out=new BAOS();
+ for( int i=0; i<values.length; i++ ) {
+ int before=out.size();
+ out.packed4(values[i]);
+ assertEquals("width of "+values[i],widths[i],out.size()-before);
+ }
+ BAOS in=new BAOS(out.toByteArray());
+ for( int value : values ) assertEquals(value,in.packed4());
+ assertEquals(out.size(),in.size());
+ out.clear();
+ out.packed4(-65); out.packed4(64);
+ assertArrayEquals(new byte[]{(byte)0x81,1,(byte)0x80,1},out.toByteArray());
+ }
+
+ @Test public void packedIntsAndStrings() {
+ Random random=new Random(123);
+ int[] values=new int[10000];
+ BAOS out=new BAOS();
+ for( int i=0; i<values.length; i++ ) out.packed4(values[i]=random.nextInt());
+ String[] strings={"","ASCII stays compact", "\u0000", "caf\u00e9 \u65e5\u672c\u8a9e \uD83D\uDE00", "x".repeat(8192)};
+ for( String s : strings ) out.packedS(s);
+ out.packed8(Long.MIN_VALUE);
+ BAOS in=new BAOS(out.toByteArray());
+ for( int value : values ) assertEquals(value,in.packed4());
+ for( String s : strings ) assertEquals(s,in.packedS());
+ assertEquals(Long.MIN_VALUE,in.packed8());
+ assertEquals(out.size(),in.size());
+ }
+
+ @Test public void rejectPackedIntOverflow() {
+ for( byte last : new byte[]{0x10,(byte)0x80} ) {
+ BAOS in=new BAOS(new byte[]{(byte)0x80,(byte)0x80,(byte)0x80,(byte)0x80,last});
+ try { in.packed4(); fail("overflow accepted"); }
+ catch( IllegalArgumentException expected ) { assertTrue(expected.getMessage().contains("overflow")); }
+ }
+ }
+
+ @Test public void wideSingletonFunctionIds() {
+ new CodeGen("");
+ for( int id : new int[]{2,63,64,254,255,256,1024,65535} )
+ PackedTypeTestSupport.singleton(id);
+ }
+}
diff --git a/src/test/java/com/seaofnodes/simple/CallEndTest.java b/src/test/java/com/seaofnodes/simple/CallEndTest.java
index f57fd96a..bba3a2c8 100644
--- a/src/test/java/com/seaofnodes/simple/CallEndTest.java
+++ b/src/test/java/com/seaofnodes/simple/CallEndTest.java
@@ -7,6 +7,30 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class CallEndTest {
+ // Inlining unlinks the original call before cloning. Each edited Parm
+ // needs a visit even when removing the argument leaves its type unchanged.
+ @Test public void testUnlinkSchedulesParameters() {
+ CodeGen code = new CodeGen("val f = { int x -> x+1; }; return f(arg);").parse();
+ FunNode fun = null;
+ for( FunNode f : code._linker )
+ if( f!=null && "f".equals(f._name) ) fun=f;
+ assertNotNull(fun);
+ CallNode call = null;
+ for( Node in : fun._inputs )
+ if( in instanceof CallNode c ) call=c;
+ assertNotNull(call);
+ Node[] uses = fun._outputs.asAry();
+ code._iter._work.clear();
+ call.unlink(fun,fun._inputs.find(call));
+ int parms = 0;
+ for( Node use : uses )
+ if( use instanceof ParmNode && !use.isDead() ) {
+ assertTrue(code._iter._work.on(use));
+ parms++;
+ }
+ assertTrue(parms>0);
+ }
+
// An unknown value can become a private object or callback. Both escape
// sinks must reserve those possibilities before the value is known.
@Test public void testUnknownEscapesRefineToPrivateValues() {
diff --git a/src/test/java/com/seaofnodes/simple/Chapter05Test.java b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
index ed4a54bd..9f733da5 100644
--- a/src/test/java/com/seaofnodes/simple/Chapter05Test.java
+++ b/src/test/java/com/seaofnodes/simple/Chapter05Test.java
@@ -202,19 +202,17 @@ return a;
catch( RuntimeException e ) { assertEquals("Undefined name 'ififif'",e.getMessage()); }
}
- private static <N extends Node> N init(N n) { n._type=n.compute(); return n; }
-
@Test public void testDoublingBeforeAndAfterStrengthReduction() {
- for( boolean reduced : new boolean[]{false,true} )
+ for( boolean shift : new boolean[]{false,true} )
for( boolean reverse : new boolean[]{false,true} ) {
CodeGen code = new CodeGen("");
- Node ctrl = init(new CProjNode(code._start,0,"Ctrl"));
- RegionNode region = init(new RegionNode(null,null,ctrl,ctrl));
- Node p = code.con(TypeInteger.BOT);
- Node i = init(new MinusNode(p));
- Node twice = reduced ? init(new ShlNode(null,p,code.con(1))) : init(new AddNode(p,p,(byte)1));
- Node sum = init(new AddNode(i,p,(byte)1));
- PhiNode phi = init(new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum));
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ RegionNode region = new RegionNode(null,null,ctrl,ctrl).init();
+ Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32);
+ Node twice = shift ? new ShlNode(null,p,code.con(1)).init()
+ : new AddNode(p,p,(byte)1).init();
+ Node sum = new AddNode(i,p,(byte)1).init();
+ PhiNode phi = new PhiNode("sum",region,reverse ? sum : twice,reverse ? twice : sum).init();
phi.keep();
Node factored = phi.idealize();
assertTrue(factored instanceof AddNode);
@@ -225,4 +223,17 @@ return a;
phi.unkeep();
}
}
+
+ @Test public void testOtherShiftIsNotDoubling() {
+ CodeGen code = new CodeGen("");
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ RegionNode region = new RegionNode(null,null,ctrl,ctrl).init();
+ Node p = code.con(TypeInteger.BOT), i = code.con(TypeInteger.I32);
+ Node shift = new ShlNode(null,p,code.con(2)).init();
+ Node sum = new AddNode(i,p,(byte)1).init();
+ PhiNode phi = new PhiNode("sum",region,shift,sum).init();
+ phi.keep();
+ assertNull(phi.idealize());
+ phi.unkeep();
+ }
}
diff --git a/src/test/java/com/seaofnodes/simple/Chapter10Test.java b/src/test/java/com/seaofnodes/simple/Chapter10Test.java
index 559def2f..13950789 100644
--- a/src/test/java/com/seaofnodes/simple/Chapter10Test.java
+++ b/src/test/java/com/seaofnodes/simple/Chapter10Test.java
@@ -197,7 +197,9 @@ while (arg) {
return bar.a;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("Stop[ return ((Phi(Loop,0,(Sar+2))<<32)>>32); return Test.Bar; ]", code.print());
+ assertEquals("Stop[ return Phi(Loop,0,(((Phi_a+2)<<32)>>32)); return Test.Bar; ]", code.print());
+ assertEquals("0",Eval2.eval(code,0));
+ assertEquals("6",Eval2.eval(code,-3));
}
@Test
@@ -319,7 +321,9 @@ while( i.x < i.len ) {
return sum;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("Stop[ return Phi(Loop,0,(((Phi_sum+((Phi(Loop,0,(((Sar+1)<<32)>>32))<<32)>>32))<<32)>>32)); return Test.Iter; ]", code.print());
+ assertEquals("Stop[ return Phi(Loop,0,(((Phi_sum+((Phi(Loop,0,(Sar+1))<<32)>>32))<<32)>>32)); return Test.Iter; ]", code.print());
+ assertEquals("0",Eval2.eval(code,0));
+ assertEquals("45",Eval2.eval(code,10));
}
diff --git a/src/test/java/com/seaofnodes/simple/Chapter13Test.java b/src/test/java/com/seaofnodes/simple/Chapter13Test.java
index 70cfe25e..738a4d15 100644
--- a/src/test/java/com/seaofnodes/simple/Chapter13Test.java
+++ b/src/test/java/com/seaofnodes/simple/Chapter13Test.java
@@ -116,7 +116,9 @@ if (v1) {
return v0.f;
""");
code.driver(CodeGen.Phase.FinalizeIR);
- assertEquals("return ((Phi(Region,((.f<<32)>>32),2)<<32)>>32);", code.print());
+ assertEquals("return Phi(Region,((.f<<32)>>32),2);", code.print());
+ assertEquals("2",Eval2.eval(code,0));
+ assertEquals("0",Eval2.eval(code,1));
}
diff --git a/src/test/java/com/seaofnodes/simple/Chapter21Test.java b/src/test/java/com/seaofnodes/simple/Chapter21Test.java
index bd2a453a..7a59adb0 100644
--- a/src/test/java/com/seaofnodes/simple/Chapter21Test.java
+++ b/src/test/java/com/seaofnodes/simple/Chapter21Test.java
@@ -533,8 +533,8 @@ val sieve = { int N ->
String sprimes = sb.p("]").toString();
// Compile, link against native C; expect the above string of primes to be printed out by C
- // Load/Phi hoisting now requires the pointer before the loop entry.
- TestC.runC(src, "sieve", sprimes,216);
+ // Phi factoring also recognizes p<<1 after p+p strength reduction.
+ TestC.runC(src, "sieve", sprimes,215);
// Evaluate on RISC5 emulator; expect return of an array of primes in
// the simulated heap.
diff --git a/src/test/java/com/seaofnodes/simple/Chapter23Test.java b/src/test/java/com/seaofnodes/simple/Chapter23Test.java
index f1ad4898..8667c0bd 100644
--- a/src/test/java/com/seaofnodes/simple/Chapter23Test.java
+++ b/src/test/java/com/seaofnodes/simple/Chapter23Test.java
@@ -279,7 +279,7 @@ return _s.peek('q');
CodeGen code = new CodeGen(src).driver(CodeGen.Phase.TypeCheck);
assertEquals("return Phi(Region,0,1);", code.print());
assertEquals("1", Eval2.eval(code, 0));
- testCPU(src,"x86_64_v2", "win64",31,null);
+ testCPU(src,"x86_64_v2", "win64",23,null);
};
@Test
diff --git a/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java b/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java
index 12634f24..ee7406c6 100644
--- a/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java
+++ b/src/test/java/com/seaofnodes/simple/EscapeFlowTest.java
@@ -113,6 +113,37 @@ public class EscapeFlowTest {
assertTrue(XInt.bit(((TypeFunPtr)after.ret()).fidxs(),7));
}
+ // Ordinary arguments do not read Start, but a later opaque argument must
+ // subscribe both the summary and consumers of its exposed escapes.
+ @Test public void testSummaryOutsideDependency() {
+ CodeGen code = new CodeGen("return 0;").parse();
+ code._phase = CodeGen.Phase.Opto;
+ TypeTuple state = TypeTuple.make(Type.CONTROL,TypeMem.START,TypeInteger.BOT);
+ code._start._type = TypeTuple.make(Type.CONTROL,TypeMem.BOT,TypeInteger.BOT);
+ Node ctrl = ConstantNode.raw(Type.CONTROL), mem = ConstantNode.raw(TypeMem.START);
+ Node arg = ConstantNode.raw(Type.BOTTOM);
+ SummaryNode summary = new SummaryNode(state,new int[0],ctrl,mem,arg).init();
+ SummaryNode observer = new SummaryNode(state,new int[0],ctrl,mem).init();
+ summary.exposed(observer);
+ code._iter._work.clear();
+ code._start.setType(TypeTuple.make(Type.CONTROL,TypeMem.START.makeFrom(XInt.make(XInt.make(7),8),XInt.EMPTY),TypeInteger.BOT));
+ assertFalse(code._iter._work.on(summary));
+ assertFalse(code._iter._work.on(observer));
+
+ arg.setType(TypeMemPtr.makeNullable(TypeStruct.forward("OpaqueSummary")));
+ assertTrue(code._iter._work.on(summary));
+ assertTrue(code._iter._work.on(observer));
+ assertTrue(XInt.bit(((TypeTuple)summary.compute()).mem()._escFs,7));
+ assertTrue(XInt.bit(summary.exposed(observer)._escFs,7));
+ code._iter._work.clear();
+ code._start.setType(TypeTuple.make(Type.CONTROL,TypeMem.START.makeFrom(XInt.make(8),XInt.EMPTY),TypeInteger.BOT));
+ assertTrue(code._iter._work.on(summary));
+ assertTrue(code._iter._work.on(observer));
+ assertTrue(XInt.bit(((TypeTuple)summary.compute()).mem()._escFs,8));
+ assertTrue(XInt.bit(summary.exposed(observer)._escFs,8));
+ assertFalse(XInt.bit(summary.exposed(observer)._escFs,7));
+ }
+
// Public construction exposes the allocator; private-memory helpers
// remain internal and can inline into it.
@Test public void testPublicAllocator() {
diff --git a/src/test/java/com/seaofnodes/simple/MemMergeTest.java b/src/test/java/com/seaofnodes/simple/MemMergeTest.java
new file mode 100644
index 00000000..253bce0b
--- /dev/null
+++ b/src/test/java/com/seaofnodes/simple/MemMergeTest.java
@@ -0,0 +1,83 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.TypeMem;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class MemMergeTest {
+ @Test public void testDenseAliasesAndDefaults() {
+ CodeGen code = new CodeGen("");
+ Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT).keep();
+ MemMergeNode mem = new MemMergeNode(null,defaults);
+ mem.alias(10000,value);
+ mem.alias(2,value);
+ mem.alias(513,value);
+ assertEquals(5,mem.nIns());
+ assertEquals(2,mem.aliasAt(2));
+ assertEquals(513,mem.aliasAt(3));
+ assertEquals(10000,mem.aliasAt(4));
+ assertSame(value,mem.alias(10000));
+ assertSame(defaults,mem.alias(512));
+ assertNull(mem.explicitAlias(9999));
+ assertSame(value,mem.explicitAlias(10000));
+ mem.alias(513,null);
+ assertEquals(4,mem.nIns());
+ assertEquals(10000,mem.aliasAt(3));
+ assertSame(value,mem.alias(10000));
+ mem.alias(2,defaults);
+ assertSame(mem,mem.idealize());
+ assertEquals(3,mem.nIns());
+ assertSame(defaults,mem.alias(2));
+ // Removing/reinserting colliding keys must not leave tombstones or stale slots.
+ for( int i=0; i<100; i++ ) {
+ mem.alias(100+i*8,value);
+ mem.alias(100+i*8,null);
+ }
+ assertEquals(3,mem.nIns());
+ mem.alias(10000,defaults);
+ assertSame(mem,mem.idealize());
+ assertEquals(2,mem.nIns());
+ // Retain the sparse implementation's fold eligibility for this experiment.
+ assertNull(mem.idealize());
+ assertSame(defaults,new MemMergeNode(null,defaults).idealize());
+ value.unkeep();
+ }
+
+ @Test public void testIndependentCopyMaps() {
+ CodeGen code = new CodeGen("");
+ Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT);
+ MemMergeNode mem = new MemMergeNode(null,defaults);
+ mem.alias(200,value);
+ MemMergeNode copy = (MemMergeNode)mem.copyEmpty();
+ for( Node in : mem._inputs ) copy.addDef(in);
+ copy.alias(7,value);
+ assertEquals(3,mem.nIns());
+ assertEquals(4,copy.nIns());
+ assertSame(defaults,mem.alias(7));
+ assertSame(value,mem.alias(200));
+ copy.alias(200,null);
+ assertSame(value,mem.alias(200));
+ assertSame(defaults,copy.alias(200));
+ code._phase = CodeGen.Phase.Select;
+ MemMergeNode selected = new MemMergeNode(mem);
+ assertEquals(200,selected.aliasAt(2));
+ assertSame(value,selected.alias(200));
+ }
+
+ @Test public void testStackedMergesKeepOverrides() {
+ CodeGen code = new CodeGen("");
+ Node defaults = code.con(TypeMem.START), value = code.con(TypeMem.BOT), override = code.con(TypeMem.TOP);
+ MemMergeNode inner = new MemMergeNode(null,defaults);
+ inner.alias(8,value);
+ inner.alias(10000,value);
+ MemMergeNode outer = new MemMergeNode(null,inner);
+ outer.alias(10000,override);
+ assertSame(outer,outer.idealize());
+ assertEquals(4,outer.nIns());
+ assertSame(defaults,outer.in(1));
+ assertSame(value,outer.alias(8));
+ assertSame(override,outer.alias(10000));
+ }
+}
diff --git a/src/test/java/com/seaofnodes/simple/ModTest.java b/src/test/java/com/seaofnodes/simple/ModTest.java
index 7f79599d..c06e99f1 100644
--- a/src/test/java/com/seaofnodes/simple/ModTest.java
+++ b/src/test/java/com/seaofnodes/simple/ModTest.java
@@ -166,20 +166,31 @@ public class ModTest {
return integerEdges(new long[]{Long.MIN_VALUE,Long.MIN_VALUE+1,-17,-5,-1,0,1,5,17,Long.MAX_VALUE});
}
private static String integerEdges(long[] values) {
+ // Keep the full value matrix in data, rather than compiling a long
+ // chain of constant calls and conditional returns for every pair.
StringBuilder source=new StringBuilder("""
val rem_noInline={ i64 x,i64 y -> x%y; };
val div_noInline={ i64 x,i64 y -> x/y; };
val main={ ->
+ val values=new i64[~]{
""");
- int failure=1;
- for( long x : values )
- for( long y : values ) {
- source.append("if(rem_noInline(").append(literal(x)).append(',').append(literal(y))
- .append(")!=").append(literal(y==0 ? 0 : x%y)).append(") return ").append(failure++).append(';');
- source.append("if(div_noInline(").append(literal(x)).append(',').append(literal(y))
- .append(")!=").append(literal(y==0 ? 0 : x/y)).append(") return ").append(failure++).append(';');
+ for(int i=0;i<values.length;i++) source.append(i==0 ? "" : ",").append(literal(values[i]));
+ source.append("}; val expectedRem=new i64[~]{");
+ int n=0;
+ for(long x:values) for(long y:values) source.append(n++==0 ? "" : ",").append(literal(y==0 ? 0 : x%y));
+ source.append("}; val expectedDiv=new i64[~]{");
+ n=0;
+ for(long x:values) for(long y:values) source.append(n++==0 ? "" : ",").append(literal(y==0 ? 0 : x/y));
+ return source.append("""
+ };
+ int index=0;
+ for(int i=0;i<values#;i++) for(int j=0;j<values#;j++) {
+ if(rem_noInline(values[i],values[j])!=expectedRem[index]) return index*2+1;
+ if(div_noInline(values[i],values[j])!=expectedDiv[index]) return index*2+2;
+ index++;
}
- return source.append("return 0; };").toString();
+ return 0; };
+ """).toString();
}
@Test public void nativeFloatingEdges() throws Exception {
double[][] cases={{Double.MAX_VALUE,0.1},{-Double.MAX_VALUE,0.1},
diff --git a/src/test/java/com/seaofnodes/simple/SchedulingTest.java b/src/test/java/com/seaofnodes/simple/SchedulingTest.java
index 16e12b0f..28b84ee1 100644
--- a/src/test/java/com/seaofnodes/simple/SchedulingTest.java
+++ b/src/test/java/com/seaofnodes/simple/SchedulingTest.java
@@ -1,8 +1,47 @@
package com.seaofnodes.simple;
import org.junit.Test;
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.codegen.IterPeeps;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import static org.junit.Assert.*;
public class SchedulingTest {
+ @Test public void verifierAllowsLoadAfterMemoryMerge() {
+ CodeGen code = loadAfterMemoryMerge();
+ assertTrue(IterPeeps.schedulableUses(code));
+ }
+
+ @Test public void verifierRejectsLoadUsedBeforeMemoryMerge() {
+ CodeGen code = loadAfterMemoryMerge();
+ ReturnNode ret = (ReturnNode)code._stop.walk(n -> n instanceof ReturnNode ? n : null);
+ LoadNode load = (LoadNode)ret.expr();
+ // The load may move below its check, but cannot serve a use above its memory.
+ ret.setDef(0,load.in(0));
+ try {
+ IterPeeps.schedulableUses(code);
+ fail("A load cannot execute before its memory is available");
+ } catch( AssertionError error ) {
+ assertTrue(error.getMessage(),error.getMessage().contains("Unschedulable data node LoadNode"));
+ }
+ }
+
+ private static CodeGen loadAfterMemoryMerge() {
+ CodeGen code = new CodeGen("return arg;").parse();
+ ReturnNode ret = (ReturnNode)code._stop.walk(n -> n instanceof ReturnNode ? n : null);
+ Node ctrl = ret.ctrl();
+ IfNode iff = new IfNode(ctrl,ret.expr()).init();
+ Node yes = new CProjNode(iff,0,"True").init();
+ Node no = new CProjNode(iff,1,"False").init();
+ RegionNode region = new RegionNode(null,null,yes,no).init();
+ Node phi = new BulkMemPhiNode("mem",region,ret.mem(),ret.mem()).init();
+ Node mem = new MemMergeNode(null,phi).init();
+ Node load = new LoadNode(null,"[]",2,ctrl,mem,code.con(TypeMemPtr.BOT),code.con(TypeInteger.ZERO)).init();
+ ret.setDef(0,region);
+ ret.setDef(2,load);
+ return code;
+ }
@Test public void nativeFoldedLoadsWithLaterOperands() throws Exception {
TestC.runSYS("""
val compare_noInline={ i64[] a, int flag ->
diff --git a/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java b/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
index 1c278791..cc4e552f 100644
--- a/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
+++ b/src/test/java/com/seaofnodes/simple/SeparateCompilationTest.java
@@ -10,6 +10,42 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class SeparateCompilationTest {
+ @Test public void testSparseWideMemoryImport() throws Exception {
+ Path build=Path.of("build/objs/separate");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"wide-memory-");
+ StringBuilder source=new StringBuilder("int f0=7;\n");
+ for( int i=1; i<300; i++ ) source.append("int f").append(i).append("=0;\n");
+ source.append("val touch={int n -> f299=n; return f0+f299;};");
+ new CodeGen(null,lib.toString(),null,"Wide",source.toString(),123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ var paths=new Ary<>(new String[]{lib.toString()});
+ CodeGen code=new CodeGen(null,null,paths,"WideEval","return Wide.touch((arg<<32)>>32);",123,true,TypeInteger.BOT)
+ .driver(CodeGen.Phase.TypeCheck);
+ assertEquals("12",Eval2.eval(code,5));
+ TestC.run("return Wide.touch(5)==12 ? 0 : 1;","wide_memory_client",paths,
+ TestC.CALL_CONVENTION,null,null,"",-1);
+ }
+
+ @Test public void testOldObjectFormatRequestsRebuild() throws Exception {
+ Path build=Path.of("build/objs/separate");
+ Files.createDirectories(build);
+ Path lib=Files.createTempDirectory(build,"old-format-");
+ new CodeGen(null,lib.toString(),null,"Old","val value=7;",123,true,TypeInteger.BOT)
+ .driver(TestC.CPU_PORT,TestC.CALL_CONVENTION,false,false);
+ Path file=lib.resolve("Old.o");
+ ElfReader elf=ElfReader.load(file.toFile(),null);
+ byte[] bytes=Files.readAllBytes(file);
+ bytes[elf._bais.size()+3]='E'; // Previous C0DE header, before format 2.
+ Files.write(file,bytes);
+ try {
+ ElfReader.load(file.toFile(),null).loadPublicTypes(new CodeGen(""));
+ fail("old format accepted");
+ } catch( IllegalArgumentException expected ) {
+ assertTrue(expected.getMessage().contains("rebuild the object file"));
+ }
+ }
+
@Test public void testImportedReadOnlyPrimitiveArray() throws Exception {
Path build=Path.of("build/objs/separate");
Files.createDirectories(build);
diff --git a/src/test/java/com/seaofnodes/simple/StringFormatTest.java b/src/test/java/com/seaofnodes/simple/StringFormatTest.java
index 59b62709..d6783380 100644
--- a/src/test/java/com/seaofnodes/simple/StringFormatTest.java
+++ b/src/test/java/com/seaofnodes/simple/StringFormatTest.java
@@ -11,28 +11,88 @@ import org.junit.Test;
import static org.junit.Assert.*;
public class StringFormatTest extends TestC {
- private static void prints(String body, String expected) throws Exception {
- runSYS("val main={ -> "+body+" return 0; };", "stringFormat",expected,-1);
+ // Share a few native programs, retaining a separately reported assertion
+ // for each case. Blocks isolate locals; the delimiter preserves embedded
+ // NULs and newlines in the expected output.
+ private enum Format {
+ DefaultsAndNestedStrings("sys.io.p(\"CPU plays %(2+3). %(\"nested %(7)\") %(true) %(1.5)\\n\");",
+ "CPU plays 5. nested 7 1 1.5\n"),
+ Formats("sys.io.p(\"%+06d(17)|%#08x(42)|%-5.3s(\"abcdef\")|%.2f(1.25)|%c(65)|%b(false)\\n\");",
+ "+00017|0x00002a|abc |1.25|A|false\n"),
+ RemainderInInterpolation("int mod=17; sys.io.p(\"%(mod%5)|%02d(mod%5)|%%|\\%|%(mod %= 5)|%(mod)\");",
+ "2|02|%|%|2|2"),
+ IntegerLimits("i64 lo=-9223372036854775807-1; sys.io.p(\"%(lo)|%(9223372036854775807)|%u(-1)|%X(-1)\");",
+ "-9223372036854775808|9223372036854775807|18446744073709551615|FFFFFFFFFFFFFFFF"),
+ IntegerPaddingRules("sys.io.p(\"%#.0o(0)|%#.3o(1)|%#x(0)|%-08d(17)|%08.4d(-17)|%+d(0)|% d(0)\");",
+ "0|001|0|17 | -0017|+0| 0"),
+ BuilderNumberUsesFormatter("val b=new sys.aryu8(); b.num(-9223372036854775807-1).add('|').num(9223372036854775807); sys.io.p(sys.text.end(b));",
+ "-9223372036854775808|9223372036854775807"),
+ EvaluationOrder("int x=0; val s=\"%(x++)%(x++)%(x++)\"; sys.io.p(\"%(s):%(s#):%(x)|%%|\\%\");",
+ "012:3:3|%|%"),
+ EvaluationMutatesBytes("val a=new u8[1]; a[0]='A'; sys.io.p(\"%(a)%(a[0]='B')%(a)\");", "A66B"),
+ Converters("sys.io.p(sys.text.int(17)); sys.io.p(sys.text.char(65)); sys.io.p(sys.text.bool(true)); sys.io.p(sys.text.flt(1.5));",
+ "17Atrue1.5"),
+ FieldNamedInt("struct S { int int=7; }; sys.io.p(\"%((new S).int)\");", "7"),
+ FloatAndAlternateFormats("f32 x=1.25f; sys.io.p(\"%(x)|%f(x)|%.2e(x)|%.2G(x)|%#o(9)|% d(7)|%.0d(0)|%a(1.5)\");",
+ "1.25|1.250000|1.25e+00|1.2|011| 7||0x1.8p+0"),
+ BufferGrowth("sys.io.p(\"%0100d(17)|%.100f(1.0)\");", "0".repeat(98)+"17|1."+"0".repeat(100)),
+ BytesAndEmptyStrings("val empty=\"%(\"\")\"; val bytes=\"a\\0b\"; sys.io.p(\"%(empty#):%s(bytes):%.2s(bytes):%c(0)\");",
+ "0:a\0b:a\0:\0"),
+ Utf8String("val s=\"π\"; sys.io.p(\"%(s):%(s#):%(s[0]):π\");", "π:2:207:π"),
+ DeferredParsing("""
+ struct S { u8[~] s; new S={ -> s="%("}) %(3)")"; }; };
+ val s=new S;
+ sys.io.p(s.s);
+ for(int i=0; i<2; sys.io.p("%(i++) %("(")")) { }
+ """, "}) 30 (1 (");
+
+ final String body, expected;
+ Format(String body, String expected) { this.body=body; this.expected=expected; }
+ }
+ private static final String END="\n--end-format-case--\n";
+ private static final int BATCH_SIZE=5;
+ private static final String[] OUTPUTS=new String[Format.values().length];
+
+ @org.junit.BeforeClass public static void resetNativeBatches() {
+ java.util.Arrays.fill(OUTPUTS,null);
+ }
+
+ private static void prints(Format test) throws Exception {
+ int index=test.ordinal();
+ if( OUTPUTS[index]==null ) {
+ Format[] cases=Format.values();
+ int first=index/BATCH_SIZE*BATCH_SIZE, limit=Math.min(first+BATCH_SIZE,cases.length);
+ StringBuilder source=new StringBuilder("val main={ -> ");
+ for( int i=first; i<limit; i++ ) {
+ assertFalse("Reserved batch delimiter",cases[i].expected.contains(END));
+ source.append('{').append(cases[i].body).append('}');
+ source.append("sys.io.p(\"\\n--end-format-case--\\n\");");
+ }
+ source.append("return 0; };");
+ String exe=compile(source.toString(),"stringFormat"+first,
+ new Ary<>(new String[]{RELEASE_SYS_DIR}),CALL_CONVENTION,null,null,-1);
+ String[] outputs=exec(TEST_TIMEOUT_SECONDS,exe).split(java.util.regex.Pattern.quote(END),-1);
+ assertEquals("Each format case must complete",limit-first+1,outputs.length);
+ assertEquals("No output after final case", "",outputs[outputs.length-1]);
+ for( int i=first; i<limit; i++ ) OUTPUTS[i]=outputs[i-first];
+ }
+ assertEquals(test.name(),test.expected,OUTPUTS[index]);
}
@Test public void testDefaultsAndNestedStrings() throws Exception {
- prints("sys.io.p(\"CPU plays %(2+3). %(\"nested %(7)\") %(true) %(1.5)\\n\");",
- "CPU plays 5. nested 7 1 1.5\n");
+ prints(Format.DefaultsAndNestedStrings);
}
@Test public void testFormats() throws Exception {
- prints("sys.io.p(\"%+06d(17)|%#08x(42)|%-5.3s(\"abcdef\")|%.2f(1.25)|%c(65)|%b(false)\\n\");",
- "+00017|0x00002a|abc |1.25|A|false\n");
+ prints(Format.Formats);
}
@Test public void testRemainderInInterpolation() throws Exception {
- prints("int mod=17; sys.io.p(\"%(mod%5)|%02d(mod%5)|%%|\\%|%(mod %= 5)|%(mod)\");",
- "2|02|%|%|2|2");
+ prints(Format.RemainderInInterpolation);
}
@Test public void testIntegerLimits() throws Exception {
- prints("i64 lo=-9223372036854775807-1; sys.io.p(\"%(lo)|%(9223372036854775807)|%u(-1)|%X(-1)\");",
- "-9223372036854775808|9223372036854775807|18446744073709551615|FFFFFFFFFFFFFFFF");
+ prints(Format.IntegerLimits);
}
@Test public void testSignedAndUnsignedRadices() throws Exception {
@@ -49,13 +109,11 @@ public class StringFormatTest extends TestC {
}
@Test public void testIntegerPaddingRules() throws Exception {
- prints("sys.io.p(\"%#.0o(0)|%#.3o(1)|%#x(0)|%-08d(17)|%08.4d(-17)|%+d(0)|% d(0)\");",
- "0|001|0|17 | -0017|+0| 0");
+ prints(Format.IntegerPaddingRules);
}
@Test public void testBuilderNumberUsesFormatter() throws Exception {
- prints("val b=new sys.aryu8(); b.num(-9223372036854775807-1).add('|').num(9223372036854775807); sys.io.p(sys.text.end(b));",
- "-9223372036854775808|9223372036854775807");
+ prints(Format.BuilderNumberUsesFormatter);
}
@Test public void testFormattingInEvaluatorFromSource() {
@@ -74,15 +132,13 @@ public class StringFormatTest extends TestC {
}
@Test public void testEvaluationOrderAndLength() throws Exception {
- prints("int x=0; val s=\"%(x++)%(x++)%(x++)\"; sys.io.p(\"%(s):%(s#):%(x)|%%|\\%\");",
- "012:3:3|%|%");
- prints("val a=new u8[1]; a[0]='A'; sys.io.p(\"%(a)%(a[0]='B')%(a)\");", "A66B");
+ prints(Format.EvaluationOrder);
+ prints(Format.EvaluationMutatesBytes);
}
@Test public void testConverters() throws Exception {
- prints("sys.io.p(sys.text.int(17)); sys.io.p(sys.text.char(65)); sys.io.p(sys.text.bool(true)); sys.io.p(sys.text.flt(1.5));",
- "17Atrue1.5");
- prints("struct S { int int=7; }; sys.io.p(\"%((new S).int)\");", "7");
+ prints(Format.Converters);
+ prints(Format.FieldNamedInt);
}
@Test public void testForwardReturnTypes() throws Exception {
@@ -91,14 +147,13 @@ public class StringFormatTest extends TestC {
}
@Test public void testFloatAndAlternateFormats() throws Exception {
- prints("f32 x=1.25f; sys.io.p(\"%(x)|%f(x)|%.2e(x)|%.2G(x)|%#o(9)|% d(7)|%.0d(0)|%a(1.5)\");",
- "1.25|1.250000|1.25e+00|1.2|011| 7||0x1.8p+0");
+ prints(Format.FloatAndAlternateFormats);
runSYS("val format_noInline={ f32 x -> \"%(x)|%f(x)\"; }; val main={ -> sys.io.p(format_noInline(1.25f)); return 0; };",
"stringFormatFloat","1.25|1.250000",-1);
}
@Test public void testBufferGrowth() throws Exception {
- prints("sys.io.p(\"%0100d(17)|%.100f(1.0)\");", "0".repeat(98)+"17|1."+"0".repeat(100));
+ prints(Format.BufferGrowth);
}
@Test public void testLiteralRemainsConstant() {
@@ -107,18 +162,12 @@ public class StringFormatTest extends TestC {
}
@Test public void testBytesAndEmptyStrings() throws Exception {
- prints("val empty=\"%(\"\")\"; val bytes=\"a\\0b\"; sys.io.p(\"%(empty#):%s(bytes):%.2s(bytes):%c(0)\");",
- "0:a\0b:a\0:\0");
- prints("val s=\"π\"; sys.io.p(\"%(s):%(s#):%(s[0]):π\");", "π:2:207:π");
+ prints(Format.BytesAndEmptyStrings);
+ prints(Format.Utf8String);
}
@Test public void testDeferredParsing() throws Exception {
- prints("""
- struct S { u8[~] s; new S={ -> s="%("}) %(3)")"; }; };
- val s=new S;
- sys.io.p(s.s);
- for(int i=0; i<2; sys.io.p("%(i++) %("(")")) { }
- """, "}) 30 (1 (");
+ prints(Format.DeferredParsing);
}
@Test public void testImportedFormatter() throws Exception {
diff --git a/src/test/java/com/seaofnodes/simple/TestWorkspace.java b/src/test/java/com/seaofnodes/simple/TestWorkspace.java
new file mode 100644
index 00000000..d875c47a
--- /dev/null
+++ b/src/test/java/com/seaofnodes/simple/TestWorkspace.java
@@ -0,0 +1,54 @@
+package com.seaofnodes.simple;
+
+import java.io.IOException;
+import java.nio.file.*;
+import java.nio.file.attribute.BasicFileAttributes;
+
+/** Prepare a Make test group's working directory without sharing native outputs. */
+public class TestWorkspace {
+ public static void main(String[] args) throws IOException {
+ if( args.length!=2 || !args[0].matches("tests_group[0-7]|sanity_group[0-2]") || !args[1].matches("[A-Za-z0-9_]+") )
+ throw new IllegalArgumentException("Expected test group and CPU_ABI");
+ Path root = Path.of("").toAbsolutePath().normalize();
+ Path work = root.resolve("build/tests").resolve(args[0]).normalize();
+ if( !work.startsWith(root.resolve("build/tests")) )
+ throw new IllegalArgumentException("Test workspace outside build/tests");
+ // Classes and JARs use the parent's absolute classpath. Copy source
+ // fixtures and native libraries; tests may write their own build tree.
+ for( String tree : new String[]{"src","docs","build/release/"+args[1],"build/objs/lib_"+args[1]} )
+ sync(root.resolve(tree),work.resolve(tree));
+ Files.createDirectories(work.resolve("build/objs"));
+ }
+
+ private static void sync(Path source, Path target) throws IOException {
+ if( !Files.isDirectory(source) ) throw new IOException("Missing test input: "+source);
+ // Remove deleted/renamed inputs as well as refreshing changed files;
+ // stale modules could otherwise make a test pass incorrectly. Only
+ // copied input trees are cleaned, preserving generated test artifacts.
+ if( Files.exists(target) ) Files.walkFileTree(target,new SimpleFileVisitor<>() {
+ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ Path original = source.resolve(target.relativize(file));
+ if( attrs.isSymbolicLink() || !Files.isRegularFile(original) ) Files.delete(file);
+ return FileVisitResult.CONTINUE;
+ }
+ @Override public FileVisitResult postVisitDirectory(Path dir, IOException error) throws IOException {
+ if( error!=null ) throw error;
+ if( !Files.isDirectory(source.resolve(target.relativize(dir))) ) Files.delete(dir);
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ Files.walkFileTree(source,new SimpleFileVisitor<>() {
+ @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
+ Files.createDirectories(target.resolve(source.relativize(dir)));
+ return FileVisitResult.CONTINUE;
+ }
+ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ Path copy = target.resolve(source.relativize(file));
+ if( !Files.exists(copy) || Files.size(copy)!=attrs.size() ||
+ !Files.getLastModifiedTime(copy).equals(attrs.lastModifiedTime()) )
+ Files.copy(file,copy,StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.COPY_ATTRIBUTES);
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ }
+}
diff --git a/src/test/java/com/seaofnodes/simple/TypeTest.java b/src/test/java/com/seaofnodes/simple/TypeTest.java
index 52e857e9..adcc1b3a 100644
--- a/src/test/java/com/seaofnodes/simple/TypeTest.java
+++ b/src/test/java/com/seaofnodes/simple/TypeTest.java
@@ -7,6 +7,58 @@ import static org.junit.Assert.assertSame;
public class TypeTest {
+ @Test public void testFinalPointerCycles() {
+ TypeStruct cycle = TypeStruct.open("FinalPointerCycle");
+ Assert.assertFalse(cycle.isFinal());
+ TypeMemPtr self = TypeMemPtr.make(cycle).withAccess(true);
+ cycle = cycle.add(Field.make("self",self,2,true))
+ .add(Field.make("value",TypeInteger.BOT,3,true)).close();
+ self = (TypeMemPtr)cycle.field("self")._t;
+ assertSame(cycle,self._obj);
+ Assert.assertTrue(self.isFinal());
+ Assert.assertTrue(cycle.isFinal());
+ assertSame(cycle,cycle.makeRO());
+
+ // Slot finality and pointer access are independent: a final slot can
+ // still hold a writable pointer, and a readonly pointer can refer to
+ // an object whose declared fields are mutable.
+ Assert.assertFalse(TypeMemPtr.make(cycle).isFinal());
+ Assert.assertFalse(Field.make("slot",self,4,false).isFinal());
+ TypeStruct mutable = cycle.addOrUpdate(Field.make("value",TypeInteger.BOT,3,false));
+ Assert.assertFalse(mutable.isFinal());
+ Assert.assertTrue(TypeMemPtr.make(mutable).withAccess(true).isFinal());
+ Assert.assertTrue(cycle.isFinal());
+ }
+
+ @Test public void testConstantPointerCycles() {
+ TypeStruct cycle = TypeStruct.open("ConstantPointerCycle");
+ TypeMemPtr self = TypeMemPtr.make((byte)2,cycle,true);
+ cycle = cycle.add(Field.make("self",self,2,true))
+ .add(Field.make("value",TypeInteger.constant(7),3,true)).close();
+ self = (TypeMemPtr)cycle.field("self")._t;
+ assertSame(cycle,self._obj);
+ Assert.assertTrue(self.isConstant());
+ Assert.assertTrue(cycle.isConstant());
+ // A constant shape does not make an arbitrary pointer a singleton.
+ Assert.assertFalse(TypeMemPtr.make(cycle).isConstant());
+
+ TypeStruct varying = TypeStruct.make("VaryingConstantReferent",false,
+ Field.make("value",TypeInteger.BOT,4,false));
+ Assert.assertFalse(varying.isConstant());
+ // Conversely, a singleton pointer can refer to mutable contents.
+ Assert.assertTrue(TypeMemPtr.make((byte)2,varying,true).isConstant());
+
+ TypeMem memory = TypeMem.make(2,cycle,true,true,true,XInt.EMPTY,XInt.EMPTY);
+ Assert.assertTrue(memory.isConstant());
+ Assert.assertFalse(TypeMem.make(2,cycle,true,false,true,XInt.EMPTY,XInt.EMPTY).isConstant());
+ // Repeated aggregate types are sharing, not recursion. Neither query
+ // should require or leave behind a cyclic-traversal visit marker.
+ TypeTuple tuple = TypeTuple.make(cycle,memory,cycle);
+ Assert.assertTrue(tuple.isConstant());
+ Assert.assertTrue(tuple.isConstant());
+ Assert.assertFalse(TypeTuple.make(cycle,TypeInteger.BOT).isConstant());
+ }
+
@Test public void testConstantArrayElements() {
TypeConAry range=TypeConAry.make(TypeInteger.U16,new long[]{5,6,7});
Assert.assertEquals("[5-7]",range.toString());
@@ -223,64 +275,78 @@ public class TypeTest {
@Test
public void testLatticeTheory() {
Type[] ts = Type.gather();
+ // Make partitions the outer loop between independent JVMs. A direct
+ // JUnit/IDE invocation retains the full coverage.
+ int parts = Integer.parseInt(System.getProperty("simple.lattice.parts","1"));
+ int part = Integer.parseInt(System.getProperty("simple.lattice.part" ,"0"));
+ Assert.assertTrue("Invalid lattice partition",parts > 0 && parts <= ts.length && part >= 0 && part < parts);
+
+ // Every triple reuses these pairs. Compute both operand orders rather
+ // than assuming commutativity in the table we are about to check.
+ Type[][] meets = new Type[ts.length][ts.length];
+ Type[][] joins = new Type[ts.length][ts.length];
+ for( int i=0; i<ts.length; i++ )
+ for( int j=0; j<ts.length; j++ ) {
+ meets[i][j] = ts[i].meet(ts[j]);
+ joins[i][j] = ts[i].join(ts[j]);
+ }
- // Confirm commutative & complete
- for( Type t0 : ts )
- for( Type t1 : ts ) {
- check_commute (t0,t1);
- check_symmetric(t0,t1);
+ // Confirm commutative & complete, once per unordered pair.
+ for( int i=part; i<ts.length; i+=parts ) {
+ assertSame(ts[i],meets[i][i]);
+ for( int j=i; j<ts.length; j++ ) {
+ assertSame(meets[i][j],meets[j][i]);
+ check_symmetric(ts[i],ts[j],meets[i][j]);
}
+ }
- // Confirm associative
- for( Type t0 : ts )
- for( Type t1 : ts )
- for( Type t2 : ts )
- assoc(t0,t1,t2);
+ // Each unordered triple represents all six permutations. Check every
+ // intermediate result in both operand orders; a pair's meet need not
+ // itself be in ts, so its commutativity must not be assumed.
+ for( int i=part; i<ts.length; i+=parts )
+ for( int j=i; j<ts.length; j++ )
+ for( int k=j; k<ts.length; k++ )
+ assoc(ts[i],ts[j],ts[k],meets[i][j],meets[i][k],meets[j][k]);
// Confirm symmetry. If A isa B, then A.join(C) isa B.join(C)
- for( Type t0 : ts )
- for( Type t1 : ts )
- if( t0.isa(t1) )
- for( Type t2 : ts ) {
- Type t02 = t0.join(t2);
- Type t12 = t1.join(t2);
+ for( int i=part; i<ts.length; i+=parts ) {
+ Type t0 = ts[i];
+ for( int j=0; j<ts.length; j++ )
+ if( meets[i][j]==ts[j] )
+ for( int k=0; k<ts.length; k++ ) {
+ Type t02 = joins[i][k];
+ Type t12 = joins[j][k];
Type mt = t02.meet(t12);
- assertSame(t0+" isa "+t1+" joined "+t2, mt,t12);
+ if( mt!=t12 ) assertSame(t0+" isa "+ts[j]+" joined "+ts[k], mt,t12);
}
- }
-
- // By design in meet, args are already flipped to order _type, which forces
- // symmetry for things with badly ordered _type fields. The question is
- // still interesting for other orders.
- private static void check_commute( Type t0, Type t1 ) {
- if( t0==t1 ) return;
- if( t0.is_simple() && !t1.is_simple() ) return; // By design, flipped the only allowed order
- Type mta = t0.meet(t1);
- Type mtb = t1.meet(t0); // Reverse args and try again
- assertSame(mta,mtb);
+ }
}
// A & B = MT
// Expect: ~A & ~MT == ~A
// Expect: ~B & ~MT == ~B
private static void check_symmetric( Type t0, Type t1 ) {
+ check_symmetric(t0,t1,t0.meet(t1));
+ }
+
+ private static void check_symmetric( Type t0, Type t1, Type mt ) {
if( t1==t0 ) return;
- Type mt = t0.meet(t1);
Type dm = mt.dual();
Type d0 = t0.dual();
Type d1 = t1.dual();
Type ta = dm.meet(d1);
Type tb = dm.meet(d0);
- assertSame(t0+" & "+t1+" mt="+mt, ta,d1);
- assertSame(t0+" & "+t1+" mt="+mt, tb,d0);
+ if( ta!=d1 ) assertSame(t0+" & "+t1+" mt="+mt, ta,d1);
+ if( tb!=d0 ) assertSame(t0+" & "+t1+" mt="+mt, tb,d0);
}
- private static void assoc( Type t0, Type t1, Type t2 ) {
- Type t01 = t0 .meet(t1 );
- Type t12 = t1 .meet(t2 );
- Type t01_2 = t01.meet(t2 );
- Type t0_12 = t0 .meet(t12);
- assertSame(t0+" & "+t1+" & "+t2, t01_2,t0_12);
+ private static void assoc( Type a, Type b, Type c, Type ab, Type ac, Type bc ) {
+ // The six original associativity equalities connect these six values
+ // in a cycle. Equality to one common result checks the same property.
+ Type result = ab.meet(c);
+ if( result!=c.meet(ab) || result!=ac.meet(b) || result!=b.meet(ac) ||
+ result!=bc.meet(a) || result!=a.meet(bc) )
+ Assert.fail("Associativity: "+a+" & "+b+" & "+c);
}
// Test cyclic types and meets
diff --git a/src/test/java/com/seaofnodes/simple/WorklistTest.java b/src/test/java/com/seaofnodes/simple/WorklistTest.java
new file mode 100644
index 00000000..fce15418
--- /dev/null
+++ b/src/test/java/com/seaofnodes/simple/WorklistTest.java
@@ -0,0 +1,49 @@
+package com.seaofnodes.simple;
+
+import com.seaofnodes.simple.codegen.CodeGen;
+import com.seaofnodes.simple.node.*;
+import com.seaofnodes.simple.type.*;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class WorklistTest {
+ @Test public void testGuardMergeAfterPredicateRewrite() { guardMergeAfterPredicateRewrite(false); }
+ @Test public void testGuardMergeAfterPredicateSubsume() { guardMergeAfterPredicateRewrite(true); }
+
+ private static void guardMergeAfterPredicateRewrite(boolean subsume) {
+ CodeGen code = new CodeGen("");
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ Node old = code.con(TypeInteger.BOOL), value = code.con(TypeInteger.BOT);
+ IfNode iff = new IfNode(ctrl,old).init();
+ Node yes = new CProjNode(iff,0,"True").init();
+ Node no = new CProjNode(iff,1,"False").init();
+ RegionNode region = new RegionNode(null,null,yes,no).init();
+ Node guard = new GuardNode(true,yes,value).init();
+ PhiNode phi = new PhiNode("guard",region,guard,code.con(TypeInteger.ZERO)).init();
+ phi.keep();
+ code._iter._work.clear();
+ assertNull(phi.idealize());
+ assertFalse(code._iter._work.on(phi));
+ // Neither edit changes a Phi input; its predicate dependency must wake it.
+ if( subsume ) old.subsume(value);
+ else iff.setDef(1,value);
+ assertTrue("Predicate rewrite must requeue the guard merge",code._iter._work.on(phi));
+ assertSame(value,phi.idealize());
+ phi.unkeep();
+ }
+ @Test public void testKnownIfDoesNotSearchDominators() {
+ CodeGen code = new CodeGen("");
+ Node ctrl = new CProjNode(code._start,0,"Ctrl").init();
+ IfNode outer = new IfNode(ctrl,code.con(TypeInteger.BOOL)).init();
+ Node yes = new CProjNode(outer,0,"True").init();
+ // Nonconstant, but already known to be nonzero.
+ IfNode inner = new IfNode(yes,code.con(TypeInteger.make(1,2))).init();
+ assertSame(TypeTuple.IF_TRUE,inner._type);
+ assertNull(inner.idealize());
+ for( int i=0; i<outer.nDeps(); i++ ) assertNotSame(inner,outer.dep(i));
+ CProjNode live = new CProjNode(inner,0,"Live").init();
+ CProjNode dead = new CProjNode(inner,1,"Dead").init();
+ assertSame(yes,live.idealize());
+ assertSame(code.XCTRL,dead.idealize());
+ }
+}
diff --git a/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java b/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java
index edb2519c..ae935da0 100644
--- a/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java
+++ b/src/test/java/com/seaofnodes/simple/codegen/RegAllocTestSupport.java
@@ -85,7 +85,7 @@ public class RegAllocTestSupport {
new Op(null,A,null,false,code._start,def);
RegAlloc alloc = new RegAlloc(code);
assertTrue(BuildLRG.run(0,alloc));
- assertFalse("A live value cannot survive a register kill",IFG.build(0,alloc));
+ assertFalse("A live value cannot survive a register kill",new IFG().build(0,alloc));
}
public static void nullUseMask() {
@@ -95,7 +95,7 @@ public class RegAllocTestSupport {
new Op(null,null,null,false,code._start,def); // Scheduling dependency only.
RegAlloc alloc = new RegAlloc(code);
assertTrue(BuildLRG.run(0,alloc));
- assertTrue(IFG.build(0,alloc));
+ assertTrue(new IFG().build(0,alloc));
}
public static void independentFunctions() {
@@ -262,7 +262,7 @@ public class RegAllocTestSupport {
assertTrue(BuildLRG.run(0,alloc));
assertNull(alloc.lrg(top));
assertSame(alloc.lrg(def),alloc.lrg(phi));
- assertTrue(IFG.build(0,alloc));
+ assertTrue(new IFG().build(0,alloc));
alloc.insertBefore(phi,slot,"test",(byte)0,alloc.lrg(phi));
assertSame(top,phi.in(slot));
}
diff --git a/src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java b/src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java
new file mode 100644
index 00000000..c218e98b
--- /dev/null
+++ b/src/test/java/com/seaofnodes/simple/type/PackedTypeTestSupport.java
@@ -0,0 +1,20 @@
+package com.seaofnodes.simple.type;
+
+import com.seaofnodes.simple.util.BAOS;
+import java.util.HashMap;
+import static org.junit.Assert.*;
+
+public class PackedTypeTestSupport {
+ public static void singleton(int id) {
+ Type.TAGOFFS();
+ TypeFunPtr fun=TypeFunPtr.make((byte)2,true,new Type[0],TypeInteger.BOT,XInt.make(id));
+ BAOS out=new BAOS();
+ fun.packed(out,new HashMap<>());
+ assertEquals(id<=254 ? 2 : 4,out.size());
+ BAOS in=new BAOS(out.toByteArray());
+ TypeFunPtr copy=(TypeFunPtr)Type.packed(in,new String[]{""});
+ assertEquals(id,copy.fidx());
+ assertEquals(0,copy.nargs());
+ assertEquals(out.size(),in.size());
+ }
+}