From 89dd0a79da85b2c7102b7c8918a1466e6238fe94 Mon Sep 17 00:00:00 2001 From: Cliff Click Date: Fri, 13 Jun 2025 15:42:08 -0700 Subject: Chapter 24a: SCCP Within a Function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Tamás Hadházy <85063808+Hels15@users.noreply.github.com> 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 Co-authored-by: Hadházy Tamás Co-authored-by: Claude Opus 5 --- Makefile | 12 +- README.ja.md | 2 +- README.md | 2 +- docs/chapter24a/24-grammar.ja.md | 168 + docs/chapter24a/24-grammar.md | 168 + docs/chapter24a/Makefile | 12 + docs/chapter24a/README.ja.md | 116 + docs/chapter24a/README.md | 181 + docs/chapter24a/examples/A_helloWorld.smp | 3 + docs/chapter24a/examples/BubbleSort.smp | 37 + docs/chapter24a/font-awesome-4.7.0.zip | Bin 0 -> 669808 bytes docs/chapter24a/ifg_trim.pdf | Bin 0 -> 155190 bytes docs/chapter24a/lattice.gv | 203 + docs/chapter24a/lattice.svg | 691 +++ docs/chapter24a/lattice2.gv | 85 + docs/chapter24a/lattice2.svg | 260 + docs/chapter24a/pardoe.docx | Bin 0 -> 22583 bytes docs/chapter24a/webtcp.min.js | 65 + src/main/java/com/seaofnodes/simple/IterPeeps.java | 36 +- src/main/java/com/seaofnodes/simple/Parser.java | 38 +- .../com/seaofnodes/simple/codegen/CodeGen.java | 41 +- .../com/seaofnodes/simple/codegen/Encoding.java | 6 +- .../com/seaofnodes/simple/codegen/FinalizeIR.java | 74 +- .../java/com/seaofnodes/simple/codegen/Opto.java | 53 + .../com/seaofnodes/simple/codegen/RegAlloc.java | 37 +- .../java/com/seaofnodes/simple/node/AddFNode.java | 28 +- .../java/com/seaofnodes/simple/node/AddNode.java | 2 +- .../com/seaofnodes/simple/node/ArithFNode.java | 30 + .../java/com/seaofnodes/simple/node/ArithNode.java | 8 +- .../java/com/seaofnodes/simple/node/CProjNode.java | 2 +- .../com/seaofnodes/simple/node/CallEndNode.java | 50 +- .../java/com/seaofnodes/simple/node/CallNode.java | 7 +- .../com/seaofnodes/simple/node/ConFldOffNode.java | 6 +- .../com/seaofnodes/simple/node/ConstantNode.java | 2 +- .../java/com/seaofnodes/simple/node/DivFNode.java | 18 +- .../java/com/seaofnodes/simple/node/FunNode.java | 35 +- .../java/com/seaofnodes/simple/node/IfNode.java | 7 +- .../java/com/seaofnodes/simple/node/LoadNode.java | 29 +- .../com/seaofnodes/simple/node/MemMergeNode.java | 10 +- .../com/seaofnodes/simple/node/MemPhiNode.java | 6 +- .../com/seaofnodes/simple/node/MinusFNode.java | 3 +- .../java/com/seaofnodes/simple/node/MinusNode.java | 2 +- .../java/com/seaofnodes/simple/node/MulFNode.java | 18 +- .../java/com/seaofnodes/simple/node/NewNode.java | 5 +- src/main/java/com/seaofnodes/simple/node/Node.java | 27 +- .../java/com/seaofnodes/simple/node/ParmNode.java | 21 + .../java/com/seaofnodes/simple/node/PhiNode.java | 44 +- .../java/com/seaofnodes/simple/node/ProjNode.java | 2 +- .../com/seaofnodes/simple/node/RegionNode.java | 27 +- .../com/seaofnodes/simple/node/ReturnNode.java | 7 +- .../java/com/seaofnodes/simple/node/StoreNode.java | 2 +- .../java/com/seaofnodes/simple/node/SubFNode.java | 24 +- .../com/seaofnodes/simple/node/ToFloatNode.java | 8 +- .../seaofnodes/simple/node/cpus/arm/SetARM.java | 1 + .../com/seaofnodes/simple/node/cpus/arm/arm.java | 4 +- .../simple/node/cpus/riscv/MemOpRISC.java | 3 + .../simple/node/cpus/x86_64_v2/SetX86.java | 1 + .../simple/print/SimpleGraphAdapter.java | 2 +- .../simple/print/SimpleGraphObserver.java | 2 +- src/main/java/com/seaofnodes/simple/type/Type.java | 10 +- .../com/seaofnodes/simple/type/TypeConAry.java | 77 +- .../com/seaofnodes/simple/type/TypeConAryB.java | 9 +- .../com/seaofnodes/simple/type/TypeConAryI.java | 9 +- .../com/seaofnodes/simple/type/TypeFunPtr.java | 7 +- .../com/seaofnodes/simple/type/TypeInteger.java | 80 +- .../com/seaofnodes/simple/type/TypeMemPtr.java | 1 + .../java/com/seaofnodes/simple/type/TypeRPC.java | 30 +- .../com/seaofnodes/simple/type/TypeStruct.java | 6 + .../java/com/seaofnodes/simple/BrainFuckTest.java | 61 +- .../java/com/seaofnodes/simple/Chapter05Test.java | 16 +- .../java/com/seaofnodes/simple/Chapter06Test.java | 32 +- .../java/com/seaofnodes/simple/Chapter07Test.java | 14 +- .../java/com/seaofnodes/simple/Chapter08Test.java | 22 +- .../java/com/seaofnodes/simple/Chapter09Test.java | 40 +- .../java/com/seaofnodes/simple/Chapter10Test.java | 44 +- .../java/com/seaofnodes/simple/Chapter11Test.java | 6 +- .../java/com/seaofnodes/simple/Chapter12Test.java | 14 +- .../java/com/seaofnodes/simple/Chapter13Test.java | 318 +- .../com/seaofnodes/simple/Chapter14FloatTest.java | 8 +- .../java/com/seaofnodes/simple/Chapter14Test.java | 28 +- .../java/com/seaofnodes/simple/Chapter15Test.java | 38 +- .../java/com/seaofnodes/simple/Chapter16Test.java | 18 +- .../java/com/seaofnodes/simple/Chapter17aTest.java | 10 +- .../java/com/seaofnodes/simple/Chapter17bTest.java | 70 +- .../java/com/seaofnodes/simple/Chapter18Test.java | 43 +- .../java/com/seaofnodes/simple/Chapter19Test.java | 85 +- .../java/com/seaofnodes/simple/Chapter20Test.java | 4 +- .../java/com/seaofnodes/simple/Chapter21Test.java | 187 +- .../java/com/seaofnodes/simple/Chapter22Test.java | 54 +- .../java/com/seaofnodes/simple/Chapter23Test.java | 157 +- .../com/seaofnodes/simple/Chapter24AllocTest.java | 170 + .../java/com/seaofnodes/simple/Chapter24Test.java | 721 +++ src/test/java/com/seaofnodes/simple/Eval2.java | 21 +- .../com/seaofnodes/simple/MemoryEncodingTest.java | 5 +- .../java/com/seaofnodes/simple/MergeSortTest.java | 46 +- src/test/java/com/seaofnodes/simple/PhaseTest.java | 16 +- src/test/java/com/seaofnodes/simple/SccpTest.java | 35 + .../java/com/seaofnodes/simple/SchedulerTest.java | 6 +- src/test/java/com/seaofnodes/simple/Simple.java | 8 +- .../java/com/seaofnodes/simple/SpillStats.java | 5 +- src/test/java/com/seaofnodes/simple/TestArm64.java | 12 +- src/test/java/com/seaofnodes/simple/TestC.java | 17 + src/test/java/com/seaofnodes/simple/TestRisc5.java | 12 +- src/test/java/com/seaofnodes/simple/TypeTest.java | 16 + .../simple/codegen/RegAllocTestSupport.java | 27 + .../com/seaofnodes/simple/evaluator/Scheduler.java | 2 +- .../java/com/seaofnodes/simple/fuzzer/Fuzzer.java | 2 +- .../java/com/seaofnodes/simple/fuzzer/Reducer.java | 2 +- .../seaofnodes/simple/fuzzer/ScriptGenerator.java | 4 +- src/test/java/com/seaofnodes/simple/progs/and1.smp | 10 - src/test/java/com/seaofnodes/simple/progs/and2.smp | 16 - src/test/java/com/seaofnodes/simple/progs/and3.smp | 14 - .../java/com/seaofnodes/simple/progs/antiDep1.smp | 11 - .../com/seaofnodes/simple/progs/brain_fuck.smp | 46 - src/test/java/com/seaofnodes/simple/progs/echo.smp | 3 - src/test/java/com/seaofnodes/simple/progs/fib.smp | 11 - .../com/seaofnodes/simple/progs/helloWorld.smp | 3 - .../java/com/seaofnodes/simple/progs/large.smp | 5344 -------------------- .../java/com/seaofnodes/simple/progs/loop2.smp | 10 - src/test/java/com/seaofnodes/simple/progs/or1.smp | 12 - src/test/java/com/seaofnodes/simple/progs/or2.smp | 23 - .../java/com/seaofnodes/simple/progs/person.smp | 9 - .../java/com/seaofnodes/simple/progs/print.smp | 8 - .../java/com/seaofnodes/simple/progs/ptrand.smp | 10 - .../com/seaofnodes/simple/progs/riscv_load.smp | 4 - .../com/seaofnodes/simple/progs/sext_str_1.smp | 4 - .../seaofnodes/simple/progs/sext_str_fold_away.smp | 5 - .../simple/progs/sext_str_not_fold_away.smp | 4 - .../simple/progs/sext_str_not_fold_away_2.smp | 4 - .../java/com/seaofnodes/simple/progs/sieve.smp | 31 - src/test/java/com/seaofnodes/simple/progs/sort.smp | 38 - .../com/seaofnodes/simple/progs/stacked_r_10x.c | 13 + .../com/seaofnodes/simple/progs/stacked_r_11x.c | 13 + .../com/seaofnodes/simple/progs/stacked_r_12x.c | 13 + .../com/seaofnodes/simple/progs/stacked_r_13x.c | 13 + .../com/seaofnodes/simple/progs/stacked_r_9x.c | 13 + .../com/seaofnodes/simple/progs/store_peep.smp | 3 - 137 files changed, 4511 insertions(+), 6535 deletions(-) create mode 100644 docs/chapter24a/24-grammar.ja.md create mode 100644 docs/chapter24a/24-grammar.md create mode 100644 docs/chapter24a/Makefile create mode 100644 docs/chapter24a/README.ja.md create mode 100644 docs/chapter24a/README.md create mode 100644 docs/chapter24a/examples/A_helloWorld.smp create mode 100644 docs/chapter24a/examples/BubbleSort.smp create mode 100644 docs/chapter24a/font-awesome-4.7.0.zip create mode 100644 docs/chapter24a/ifg_trim.pdf create mode 100644 docs/chapter24a/lattice.gv create mode 100644 docs/chapter24a/lattice.svg create mode 100644 docs/chapter24a/lattice2.gv create mode 100644 docs/chapter24a/lattice2.svg create mode 100644 docs/chapter24a/pardoe.docx create mode 100644 docs/chapter24a/webtcp.min.js create mode 100644 src/main/java/com/seaofnodes/simple/codegen/Opto.java create mode 100644 src/main/java/com/seaofnodes/simple/node/ArithFNode.java create mode 100644 src/test/java/com/seaofnodes/simple/Chapter24AllocTest.java create mode 100644 src/test/java/com/seaofnodes/simple/Chapter24Test.java create mode 100644 src/test/java/com/seaofnodes/simple/SccpTest.java delete mode 100644 src/test/java/com/seaofnodes/simple/progs/and1.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/and2.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/and3.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/antiDep1.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/brain_fuck.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/echo.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/fib.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/helloWorld.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/large.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/loop2.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/or1.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/or2.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/person.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/print.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/ptrand.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/riscv_load.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/sext_str_1.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/sext_str_fold_away.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/sext_str_not_fold_away.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/sext_str_not_fold_away_2.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/sieve.smp delete mode 100644 src/test/java/com/seaofnodes/simple/progs/sort.smp create mode 100644 src/test/java/com/seaofnodes/simple/progs/stacked_r_10x.c create mode 100644 src/test/java/com/seaofnodes/simple/progs/stacked_r_11x.c create mode 100644 src/test/java/com/seaofnodes/simple/progs/stacked_r_12x.c create mode 100644 src/test/java/com/seaofnodes/simple/progs/stacked_r_13x.c create mode 100644 src/test/java/com/seaofnodes/simple/progs/stacked_r_9x.c delete mode 100644 src/test/java/com/seaofnodes/simple/progs/store_peep.smp diff --git a/Makefile b/Makefile index 8fa5a13a..e02c8096 100644 --- a/Makefile +++ b/Makefile @@ -139,12 +139,6 @@ tests: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag @$(JVM) org.junit.runner.JUnitCore $(test_cp) @$(JVM) org.junit.runner.JUnitCore com.seaofnodes.simple.FuzzerWrap -spill-stats: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag - @[ -d build/objs ] || mkdir -p build/objs - @$(JVM) com.seaofnodes.simple.SpillStats - -.PHONY: spill-stats - fuzzer: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag @echo "fuzzing " $(test_cp) @$(JVM) org.junit.runner.JUnitCore com.seaofnodes.simple.FuzzerWrap @@ -182,5 +176,11 @@ tags: $(main_javas) $(test_javas) @rm -f TAGS @$(CTAGS) -e --recurse=yes --extra=+q --fields=+fksaiS $(SRC) $(TST) +spill-stats: $(CLZDIR)/main/.mtag $(CLZDIR)/test/.ttag + @[ -d build/objs ] || mkdir -p build/objs + @$(JVM) com.seaofnodes.simple.SpillStats + +.PHONY: spill-stats + .PHONY: build build: $(CLZDIR)/main/.mtag diff --git a/README.ja.md b/README.ja.md index 165d8eef..67c4285a 100644 --- a/README.ja.md +++ b/README.ja.md @@ -61,7 +61,7 @@ Simple 言語のスタイルは、C または Java のサブセットに倣っ * [第21章](docs/chapter21/README.ja.md):命令エンコーディングと ELF。 * [第22章](docs/chapter22/README.ja.md):Simple の Hello, World! * [第23章](docs/chapter23/README.ja.md):メソッドと型の再検討。 -* 第24a章:関数内の SCCP +* [第24a章](docs/chapter24a/README.ja.md):関数内の SCCP * 第24b章:関数間の SCCP * 第25章:型が決まる前の SSA * 第26章:構築とプライベートメモリ diff --git a/README.md b/README.md index 8162271d..c71501d2 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ The Simple language is styled after a subset of C or Java. * [Chapter 21](docs/chapter21/README.md): Instruction Encodings & ELF * [Chapter 22](docs/chapter22/README.md): A Simple Hello, World! * [Chapter 23](docs/chapter23/README.md): Methods and Types Revisited -* Chapter 24a: SCCP Within a Function +* [Chapter 24a](docs/chapter24a/README.md): SCCP Within a Function * Chapter 24b: SCCP Across Functions * Chapter 25: SSA Before Types Are Known * Chapter 26: Construction and Private Memory diff --git a/docs/chapter24a/24-grammar.ja.md b/docs/chapter24a/24-grammar.ja.md new file mode 100644 index 00000000..5b715ef8 --- /dev/null +++ b/docs/chapter24a/24-grammar.ja.md @@ -0,0 +1,168 @@ +# 第24a章の文法 + +[English](24-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. +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 : methodDeclaration | statement ; + +// A method is an ordinary fixed function binding in a struct definition. +// The compiler supplies self; it is not written in parameterList. +// The general declaration rule also admits explicitly typed function fields. +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. 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)* ','? ; + +// Struct initialization uses a block; array allocation supplies a length. +newExpression : 'new' type ('[' assignment ']' | block)? ; + +INTEGER_LITERAL : '0' | [1-9] 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] ; +WHITESPACE : [ \t\r\n]+ -> skip ; +LINE_COMMENT : '//' ~[\r\n]* -> skip ; +BLOCK_COMMENT : '/*' .*? '*/' -> skip ; +``` diff --git a/docs/chapter24a/24-grammar.md b/docs/chapter24a/24-grammar.md new file mode 100644 index 00000000..4c95692e --- /dev/null +++ b/docs/chapter24a/24-grammar.md @@ -0,0 +1,168 @@ +# Grammar for Chapter 24a + +English | [日本語](24-grammar.ja.md) + +```antlrv4 +grammar SimpleLanguage; + +// Name lookup, assignable operands, type compatibility, and access permissions +// are checked by the compiler in addition to these syntax rules. +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 : methodDeclaration | statement ; + +// A method is an ordinary fixed function binding in a struct definition. +// The compiler supplies self; it is not written in parameterList. +// The general declaration rule also admits explicitly typed function fields. +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. 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)* ','? ; + +// Struct initialization uses a block; array allocation supplies a length. +newExpression : 'new' type ('[' assignment ']' | block)? ; + +INTEGER_LITERAL : '0' | [1-9] 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] ; +WHITESPACE : [ \t\r\n]+ -> skip ; +LINE_COMMENT : '//' ~[\r\n]* -> skip ; +BLOCK_COMMENT : '/*' .*? '*/' -> skip ; +``` diff --git a/docs/chapter24a/Makefile b/docs/chapter24a/Makefile new file mode 100644 index 00000000..12659b8f --- /dev/null +++ b/docs/chapter24a/Makefile @@ -0,0 +1,12 @@ +GV := $(wildcard *.gv) +SVG := $(patsubst %.gv,%.svg,$(GV)) + +.PHONY: all +all: $(SVG) + +%.svg: %.gv + dot -Tsvg $< > $@ + +.PHONY: clean +clean: + @rm -f $(SVG) diff --git a/docs/chapter24a/README.ja.md b/docs/chapter24a/README.ja.md new file mode 100644 index 00000000..fd868f39 --- /dev/null +++ b/docs/chapter24a/README.ja.md @@ -0,0 +1,116 @@ +# 第24a章: 関数内の SCCP + +[English](README.md) | 日本語 + +[Previous: Chapter 23](../chapter23/README.ja.md) | +[Next: Chapter 24b](../chapter24b/README.ja.md) + +この章は旧第24章から分けた、単独で実行できるコンパイラです。 +関数内の SCCP を第24a章で、関数間への拡張を第24b章で説明します。 +最新の説明と検証方法は [英語版](README.md) を参照してください。 + +## 疎な条件付き定数伝播 + +[SCCP](https://en.wikipedia.org/wiki/Sparse_conditional_constant_propagation) は、これまで行ってきたピープホール最適化/定数畳み込みの、上から下へ進む版です。アルゴリズムの規則は文献でよく知られ、大学で一般に教えられています。[スライドの例](https://www.cse.psu.edu/~gxt29/teaching/cse522s23/slides/08monotoneFramework.pdf) があります。 + +- すでに束を持っています。 +- すでに SSA 形式を持っています。したがってアルゴリズムは *疎* です。 +- ノードから型への対応(`Node._type`)を持っています。 +- すでに伝達関数(`Node.compute`)を持っています。 + +すべての `_type` を、⊥ ではなく ⊤ に初期化し、すべてのノードをワークリストに置きます。そこからノードを取り、伝達関数 `node.compute()` を実行します。結果が `node._type` と変われば更新し、その出力側の隣接ノードをワークリストへ入れます。依存関係の追跡とデバッグ用の検査の大部分を省いた簡略版は次のとおりです。 + +```java +while( (n = code._iter._work.pop()) != null ) { + Type nval = n.compute(); + if( n._type != nval ) { + assert n._type.isa(nval); // Types start high and always fall + n._type = nval; // Update type in Node + code._iter.addAll(n._outputs);// Neighbors might change, need to inspect + } +} +``` + +単調な伝達関数と、範囲の拡大回数を制限する widening により、アルゴリズムは *不動点* で停止します。widening は範囲の精度を落とすことがあるため、束で表せる最も精密な答えとは限りません。得られる型は悲観的解析と同等以上の精度です。その後、型が改善されたノードでピープホール規則を実行できます。たとえば新しく発見した定数が、計算を ConstantNode に置き換えます。 + +以下は SSA の擬似コードです。`phi` はマージを意味し、Simple の構文ではありません。 + +```text +int x0 = 1; // x0 = 1 +while( rand ) { + x1 = phi(x0,x2); // x1 = BOT = phi(1,BOT) + x2 = 2 - x1; // x2 = BOT = 2 - BOT +} +return x1 +``` + +SCCP がなければ、この小さなプログラムは `x` の計算を畳み込めません。見れば `x` は常に `1` とわかりますが、下から上へ進む悲観的手法は、x1 が BOT なので x2 が BOT、したがって x1 が BOT と判断します。行き詰まりを解くには楽観的手法が必要です。x1 が `1` と *仮定* すれば、x2 も `1` と発見できます。値の畳み込みは、ループ停止を証明したり、その条件と副作用を除去可能にしたりするものではありません。 + +表はワークリストの処理順の一例を左から右に示します。変化がなくなったら停止します。 + +| 変数 | 初期 | x0=1 | x1=phi(1,T) | x2=2-x1 | x1=phi(1,1) | +|---|----|----|-----------|-------|-----------| +| x0 | T | 1 | 1 | 1 | 1 | +| x1 | T | T | 1 | 1 | 1 | +| x2 | T | T | T | 1 | 1 | + +### 条件付き + +制御フローがデータフローと同じグラフ内にあるため(これが Sea-of-Nodes の大きな要点です)、特別なことをする必要はなく、アルゴリズムはすでに *条件付き* です。ここでも例が役に立ちます。 + +再び SSA の擬似コードを使います。 + +```text +int x0 = 1; // x0 = 1 +while( rand ) { + x1 = phi(x0,x4); // x1 = BOT = phi(1,BOT) + if( x1 == 1 ) // Since x1 is BOT, both true and false arms are taken + x2 = 2 - x1; // x2 = BOT = 2 - BOT + else x3 = 99; // x3 = 99 + x4 = phi(x2,x3); // x4 = BOT = phi(BOT,99) +} +return x1 +``` + +次の表も処理順の一例ですが、今度はすべての経路が到達可能とは限りません。`if` の結果は Control 値の対で、経路が生きていれば `C`、そうでなければ `X` で示します。これは `x4 = phi(x2,x3)` の計算で使います。`PhiNode` は `if` の対応する制御入力 *も* 確認し、生きた経路だけをマージします。 + +| 変数 | 初期 | x0=1 | x1=phi(1,T) | 1 == 1? | x2=2-x1 | x3=99 | x4=phi(C/1,X/99) | x1=phi(1,1) | +|---|-----|----|-----------|---------|---------|---------|----------------|-----------| +| x0 | T | 1 | 1 | 1 | 1 | 1 | 1 | 1 | +| x1 | T | T | 1 | 1 | 1 | 1 | 1 | 1 | +| if | T | T | T | [C,X] | [C,X] | [C,X] | [C,X] | [C,X] | +| x2 | T | T | T | T | 1 | 1 | 1 | 1 | +| x3 | T | T | T | T | T | 99 | 99 | 99 | +| x4 | T | T | T | T | T | T | 1 | 1 | + +この種の条件付き定数伝播は、条件が真か偽と証明できると、最適化後のプログラムから検査と分岐を除去するので、非常に役立ちます。よくあるのが null 検査です。同じプログラムで、整数の代わりに null ポインタを使います。 + +```text +List head = notNullList(); +while( rand ) { + if( head ) head = new List(head,payload); + else { head = null; default_action(); } +} +``` + +`head` は非 null で始まるため、決して null にならず、`default_action` も起きません。ループは簡略化できます。 + +```text +List head = notNullList(); +while( rand ) { + head = new List(head,payload); +} +``` + +## 呼び出しとの境界 + +この章の SCCP は各関数を独立に解析します。未知の呼び出し元を表す Start +入力を残し、呼び出し辺を外します。呼び出しの戻り値には、悲観的解析で得た +型を保持します。これは宣言された戻り値型より精密な場合があります。 +呼び出しによるメモリへの影響は保守的に扱います。 + +ループの整数範囲は Phi で拡大し、解析を収束させます。再帰呼び出しを通る +引数と戻り値の推論・拡大は次の章で導入します。 + +このディレクトリで最初に `make lib`、続いて `make tests` を実行してください。 +リポジトリのルートでは `make tests CHAPTERS=chapter24a` を使えます。 diff --git a/docs/chapter24a/README.md b/docs/chapter24a/README.md new file mode 100644 index 00000000..a1be6e6d --- /dev/null +++ b/docs/chapter24a/README.md @@ -0,0 +1,181 @@ +# Chapter 24a: SCCP Within a Function + +English | [日本語](README.ja.md) + +[Previous: Chapter 23](../chapter23/README.md) | +[Next: Chapter 24b](../chapter24b/README.md) + +This chapter introduces [SCCP](https://en.wikipedia.org/wiki/Sparse_conditional_constant_propagation) +within each function. Next chapter, we'll go interprocedural with SCCP. + +Calls retain conservative interfaces here. In particular, mutually recursive +functions whose return types need inference across calls can still fail with +`No defined return type`; Chapter 24b solves those recursive return cycles. + + +This is an independent compiler snapshot. The [split record](../chapter-split.md) +explains how the former combined SCCP chapter became Chapters 24a and 24b. + +## Sparse Conditional Constant Propagation + +[SCCP](https://en.wikipedia.org/wiki/Sparse_conditional_constant_propagation) +is the optimistic version of the same peephole/constant-folding work we have +been doing all along. Types start at the top of the lattice and fall as we +discover reachable values. The rules for the algorithm are well known from the +literature and commonly taught at the college level; +[example slides](https://www.cse.psu.edu/~gxt29/teaching/cse522s23/slides/08monotoneFramework.pdf). + +- We have a lattice already +- We have SSA form already (hence the algorithm is *sparse*) +- We have a mapping from Nodes to Types (`Node._type`) +- We have transfer functions (`Node.compute`) already. + +We initialize all `_type` fields to ⊤ (as opposed to ⊥), and place all Nodes on +a worklist. We pull a Node from the worklist, run the transfer function +`node.compute()`, and if the result changes from `node._type` we update +`node._type` and put its output neighbors on the worklist. A simplified +version, omitting dependency tracking and most debug checks: + +```java +while( (n = code._iter._work.pop()) != null ) { + Type nval = n.compute(); + if( n._type != nval ) { + assert n._type.isa(nval); // Types start high and always fall + n._type = nval; // Update type in Node + code._iter.addAll(n._outputs);// Neighbors might change, need to inspect + } +} +``` + +With monotone transfer functions and bounded range widening, this algorithm +terminates at a *fixed point*. Widening can lose range precision, so this need +not be the sharpest answer the lattice can express. The resulting types are +at least as precise as those found by pessimistic analysis. We can then run +the peephole rules on nodes +with improved types, to see if unrelated peepholes can fire - such as newly +discovered constants replacing computations with ConstantNodes. + +The following is SSA pseudocode: + +```text +int x0 = 1; // x0 = 1 +while( rand ) { + x1 = phi(x0,x2); // x1 = BOT = phi(1,BOT) + x2 = 2 - x1; // x2 = BOT = 2 - BOT +} +return x1 +``` + +Without SCCP, this small program cannot fold the computation of `x`. +A glance at the program tells us `x` must always be a `1` but +the bottom-up (pessimistic) approach decides that since x1 is BOT, x2 must be +BOT so x1 must be BOT. We need the optimistic approach to break the +stalemate, and just *assume* x1 is `1`, and then we can discover that x2 is +also a `1`. Folding the value does not prove the loop terminates or make +its condition and side effects removable. + + +The table shows one possible worklist order, from left to right. The solve +stops when no more changes happen: + +|Var|init|x0=1|x1=phi(1,T)|x2=2-x1|x1=phi(1,1)| +|---|----|----|-----------|-------|-----------| +|x0 | T | 1 | 1 | 1 | 1 | +|x1 | T | T | 1 | 1 | 1 | +|x2 | T | T | T | 1 | 1 | + + + +### Conditional + +Since our control flow is in the same graph as our data flow (that's the major +point of Sea-of-Nodes!), we need not do anything special and our algorithm is +*conditional* already. Again an example is interesting: + +Again using SSA pseudocode: + +```text +int x0 = 1; // x0 = 1 +while( rand ) { + x1 = phi(x0,x4); // x1 = BOT = phi(1,BOT) + if( x1 == 1 ) // Since x1 is BOT, both true and false arms are taken + x2 = 2 - x1; // x2 = BOT = 2 - BOT + else x3 = 99; // x3 = 99 + x4 = phi(x2,x3); // x4 = BOT = phi(BOT,99) +} +return x1 +``` + +Again the table shows one possible order, although this time not all +paths are reachable. The `if` result is a pair of Control values, shown as +either `C` if the path is alive or `X` if not. This is used when we compute +`x4 = phi(x2,x3)`; the `PhiNode` ALSO checks the corresponding control input +from the `if` and only merges alive paths. + + +|Var|init |x0=1|x1=phi(1,T)| 1 == 1? | x2=2-x1 | x3=99 |x4=phi(C/1,X/99)|x1=phi(1,1)| +|---|-----|----|-----------|---------|---------|---------|----------------|-----------| +|x0 | T | 1 | 1 | 1 | 1 | 1 | 1 | 1 | +|x1 | T | T | 1 | 1 | 1 | 1 | 1 | 1 | +|if | T | T | T | [C,X] | [C,X] | [C,X] | [C,X] | [C,X] | +|x2 | T | T | T | T | 1 | 1 | 1 | 1 | +|x3 | T | T | T | T | T | 99 | 99 | 99 | +|x4 | T | T | T | T | T | T | 1 | 1 | + +This kind of conditional constant propagation really helps if a condition can +be proven true or false, as this removes a test and branch from the optimized +program. A common way this happens is with null tests; here is the same +idea as above, but using null pointers instead of integers (in pseudocode): + +```text +List head = notNullList(); +while( rand ) { + if( head ) head = new List(head,payload); + else { head = null; default_action(); } +} +``` + +Here since `head` starts not-null, it can never be null and the +`default_action` can never happen, and the loop can +simplify: + +```text +List head = notNullList(); +while( rand ) { + head = new List(head,payload); +} +``` + +## Convergence and calls + +Integer ranges can grow one value per loop trip. A loop Phi widens its range +after a bounded number of such steps. Constants stay precise; above-center +ranges must remain narrow so they can fall to constants monotonically. + +During SCCP, each function retains its unknown-caller Start input. Call edges +are disconnected, and call results keep the summaries already established by +pessimistic analysis. Those summaries can be sharper than the written +signature, so discarding them would lose valid facts. Calls still carry +whole-memory effects. The solve discovers no new call edges. + +After the solve, ordinary peepholes relink calls and apply inlining as before. +FinalizeIR removes uncalled bodies and detaches calls for scheduling. This +separates local optimistic analysis from the existing pessimistic call machinery. + +`SccpTest` checks a loop fixed point and a function called with 1 and 2: its +parameter remains general here, while the following chapter infers [1,2]. + +A recursive function whose return type needs optimistic propagation through +calls can still report "No defined return type" here. The next chapter adds +that inference and the widening needed to make it converge; its +`Chapter24Test.testRecursiveWidening` exercises both recursive data cycles. + +## Building and checking + +Run `make lib` once for Java test dependencies, then `make tests` in this +directory. From the repository root, use `make tests CHAPTERS=chapter24a`. +The inherited tests retain their historical class names. + +The [grammar](24-grammar.md) includes chained comparisons introduced in +Chapter 23 beside short-circuit expressions. Allocator tuning is covered in +the [appendix](../appendices/optimizer-tuning.md). diff --git a/docs/chapter24a/examples/A_helloWorld.smp b/docs/chapter24a/examples/A_helloWorld.smp new file mode 100644 index 00000000..07ff935f --- /dev/null +++ b/docs/chapter24a/examples/A_helloWorld.smp @@ -0,0 +1,3 @@ +// -*- mode: java; -*- +sys.io.p("Hello, World!"); +return 0; diff --git a/docs/chapter24a/examples/BubbleSort.smp b/docs/chapter24a/examples/BubbleSort.smp new file mode 100644 index 00000000..938e3181 --- /dev/null +++ b/docs/chapter24a/examples/BubbleSort.smp @@ -0,0 +1,37 @@ +// -*- mode: java; -*- + +// An implementation of +// https://sampleprograms.io/projects/bubble-sort/ +// +// Bubble sort, with reading (parsing) and writing (formatting) the data. + +val sort = { !sys.aryi64 nums -> + var done = false; + while( !done ) { + done = true; + for( var i = 0; i < nums.len-1; i++ ) + if( nums.buf[i] > nums.buf[i+1] ) { + int tmp = nums.buf[i]; + nums.buf[i] = nums.buf[i+1]; + nums.buf[i+1] = tmp; // Swap + done = false; + } + } +}; + +// Read from stdin a line of the form "[ 4, 3, 2, 1]" and print it sorted. +val main = { -> + // Parse array of numbers from stdin + var nums = sys.parseAryI64( sys.io.stdin() ); + if( !nums ) { + sys.io.p("stdin must look like [4, 3, 2, 1]"); + return 1; + } + + // Bubble sort array of integers + sort(nums); + + // Print a list of numbers to stdout + nums.str().write(1); + return 0; +}; diff --git a/docs/chapter24a/font-awesome-4.7.0.zip b/docs/chapter24a/font-awesome-4.7.0.zip new file mode 100644 index 00000000..b6bdb4bd Binary files /dev/null and b/docs/chapter24a/font-awesome-4.7.0.zip differ diff --git a/docs/chapter24a/ifg_trim.pdf b/docs/chapter24a/ifg_trim.pdf new file mode 100644 index 00000000..d952fd4f Binary files /dev/null and b/docs/chapter24a/ifg_trim.pdf differ diff --git a/docs/chapter24a/lattice.gv b/docs/chapter24a/lattice.gv new file mode 100644 index 00000000..8661082d --- /dev/null +++ b/docs/chapter24a/lattice.gv @@ -0,0 +1,203 @@ +digraph Lattice { + compound = true; + // Define nodes + splines=false; + node [shape=circle, style=filled]; + nodesep=0.2; + ranksep=0.2; + + TOP [label=<⊤>, fillcolor=black, fontcolor=white]; + BOT [label=<⊥>, fillcolor=black, fontcolor=white]; + + // ---------------------- + // Control + XCTRL [label=<⊤:ctrl>, fillcolor=yellow, shape=oval]; + CTRL [label=<⊥:ctrl>, fillcolor=yellow, shape=oval]; + + TOP -> XCTRL; + XCTRL -> CTRL; + CTRL -> BOT; + + // ---------------------- + // Integers + INT_TOP [label=<⊤:int>, fillcolor=lightblue, shape=oval]; + INT_BOT [label=<⊥:int>, fillcolor=lightblue, shape=oval]; + + INT_HI [label="[min>max]" , fillcolor=lightblue, shape=oval]; + INT_XBOOL [label="[1...0]", fillcolor=lightblue, shape=oval]; + INT_CON [label="constants", fillcolor=lightblue, shape=oval]; + INT_CON0 [label="0", fillcolor=lightblue]; + INT_CON1 [label="1", fillcolor=lightblue]; + INT_BOOL [label="[0...1]", fillcolor=lightblue,shape=oval]; + INT_LO [label="[min INT_TOP; + INT_TOP -> INT_HI; + INT_HI -> INT_XBOOL; + INT_XBOOL -> INT_CON0; + INT_XBOOL -> INT_CON1; + INT_HI -> INT_CON; + INT_CON0 -> INT_BOOL; + INT_CON1 -> INT_BOOL; + INT_BOOL -> INT_LO; + INT_CON -> INT_LO; + INT_LO -> INT_BOT; + INT_BOT -> BOT; + + INT_CON0 -> INT_CON1 -> INT_CON [style=invis]; + + // ---------------------- + // Floats + FLT_TOP [label=<⊤:flt>, fillcolor=aqua, shape=oval]; + FLT_BOT [label=<⊥:flt>, fillcolor=aqua, shape=oval]; + + FLT_CON64 [label="64b consts\n[excludes\n32b consts]" , fillcolor=aqua, shape=oval]; + FLT_CON32 [label="32b consts", fillcolor=aqua, shape=oval]; + FLT_CONPI [label="3.14159...", fillcolor=aqua, shape=oval]; + FLT_X32 [label="~f32", fillcolor=aqua]; + FLT_CON0 [label="0." , fillcolor=aqua]; + FLT_32 [label="f32" , fillcolor=aqua]; + + TOP -> FLT_TOP; + FLT_TOP -> FLT_CON64 + FLT_TOP -> FLT_CONPI + FLT_CON64 -> FLT_BOT + FLT_CONPI -> FLT_BOT + + FLT_TOP -> FLT_X32; + FLT_X32 -> FLT_CON0; + FLT_X32 -> FLT_CON32; + FLT_CON0 -> FLT_32; + FLT_CON32 -> FLT_32; + FLT_32 -> FLT_BOT + + FLT_BOT -> BOT; + + FLT_CON0 -> FLT_CON32 -> FLT_CONPI -> FLT_CON64 [style=invis]; + + + // ---------------------- + // Pointers, just a boolean nil/not and a struct + PTR [shape=none, fillcolor=none, label=< + + + +
*ptr
struct
+ >]; + PTR0 [shape=none, fillcolor=none, label=< + + + +
*ptr?
struct
+ >]; + + TOP -> PTR; + PTR -> PTR0; + PTR0 -> BOT; + + // ---------------------- + // Structs + STRUCT_TOP [label=<⊤:struct>, fillcolor=lightgreen, shape=oval]; + STRUCT_BOT [label=<⊥:struct>, fillcolor=lightgreen, shape=oval]; + + STRUCT_S1 [shape=none, fillcolor=none, label=< + + +
fieldint/ptr
+ >]; + STRUCT_S2 [shape=none, fillcolor=none, label=< + + + +
fieldint/ptr
fieldint/ptr
+ >]; + STRUCT_SN [shape=none, fillcolor=none, label=< + + + + +
fieldint/ptr
... int/ptr
fieldint/ptr
+ >]; + + + TOP -> STRUCT_TOP; + STRUCT_TOP -> STRUCT_S1; + STRUCT_TOP -> STRUCT_S2; + STRUCT_TOP -> STRUCT_SN; + STRUCT_S1 -> STRUCT_BOT; + STRUCT_S2 -> STRUCT_BOT; + STRUCT_SN -> STRUCT_BOT; + STRUCT_BOT -> BOT; + + STRUCT_S1 -> STRUCT_S2 -> STRUCT_SN [style=invis]; + + // ---------------------- + // Memory + MEM_TOP [label=<⊤:mem>, fillcolor=blue, fontcolor=white, shape=oval]; + MEM_BOT [label=<⊥:mem>, fillcolor=blue, fontcolor=white, shape=oval]; + MEM_ALIAS1 [label="#1" , fillcolor=blue, fontcolor=white]; + MEM_ALIASDOTS [label="..." , fillcolor=blue, fontcolor=white, shape=oval]; + MEM_ALIASN [label="#n" , fillcolor=blue, fontcolor=white]; + + TOP -> MEM_TOP; + MEM_TOP -> MEM_ALIAS1; + MEM_TOP -> MEM_ALIASDOTS; + MEM_TOP -> MEM_ALIASN; + MEM_ALIAS1 -> MEM_BOT; + MEM_ALIASDOTS -> MEM_BOT; + MEM_ALIASN -> MEM_BOT; + MEM_BOT -> BOT; + + MEM_ALIAS1 -> MEM_ALIASDOTS -> MEM_ALIASN [style=invis]; + + // ---------------------- + // Tuples + + TUPLE_TOP [label=<⊤:tuple>, fillcolor=pink, shape=oval]; + TUPLE_BOT [label=<⊥:tuple>, fillcolor=pink, shape=oval]; + + TUPLE1 [shape=none, fillcolor=none, label=< + + + +
Tuple
type
+ >]; + TUPLE2 [shape=none, fillcolor=none, label=< + + + + +
Tuple
type
type
+ >]; + TUPLEN [shape=none, fillcolor=none, label=< + + + + + +
Tuple
type
...
type
+ >]; + + + TOP -> TUPLE_TOP; + TUPLE_TOP -> TUPLE1; + TUPLE_TOP -> TUPLE2; + TUPLE_TOP -> TUPLEN; + TUPLE1 -> TUPLE_BOT; + TUPLE2 -> TUPLE_BOT; + TUPLEN -> TUPLE_BOT; + TUPLE_BOT -> BOT; + + // ---------------------- + // Additional customization + {rank=same; TOP;} + {rank=same; INT_TOP; FLT_TOP; XCTRL; PTR; STRUCT_TOP; MEM_TOP; TUPLE_TOP} + {rank=same; INT_CON; INT_CON0; INT_CON1; + FLT_CON32; FLT_CON64; FLT_CON0; FLT_CONPI; + STRUCT_S1; STRUCT_S2; STRUCT_SN; + MEM_ALIAS1; MEM_ALIASDOTS; MEM_ALIASN; + TUPLE1; TUPLE2; TUPLEN; + } + {rank=same; INT_BOT; FLT_BOT; CTRL; PTR0; STRUCT_BOT; MEM_BOT; TUPLE_BOT} + {rank=same; BOT;} +} diff --git a/docs/chapter24a/lattice.svg b/docs/chapter24a/lattice.svg new file mode 100644 index 00000000..e72b473b --- /dev/null +++ b/docs/chapter24a/lattice.svg @@ -0,0 +1,691 @@ + + + + + + +Lattice + + + +TOP + +⊤ + + + +XCTRL + +⊤ +:ctrl + + + +TOP->XCTRL + + + + + +INT_TOP + +⊤ +:int + + + +TOP->INT_TOP + + + + + +FLT_TOP + +⊤ +:flt + + + +TOP->FLT_TOP + + + + + +PTR + + + +*ptr + + +struct + + + +TOP->PTR + + + + + +STRUCT_TOP + +⊤ +:struct + + + +TOP->STRUCT_TOP + + + + + +MEM_TOP + +⊤ +:mem + + + +TOP->MEM_TOP + + + + + +TUPLE_TOP + +⊤ +:tuple + + + +TOP->TUPLE_TOP + + + + + +BOT + +⊥ + + + +CTRL + +⊥ +:ctrl + + + +XCTRL->CTRL + + + + + +CTRL->BOT + + + + + +INT_HI + +[min>max] + + + +INT_TOP->INT_HI + + + + + +INT_BOT + +⊥ +:int + + + +INT_BOT->BOT + + + + + +INT_XBOOL + +[1...0] + + + +INT_HI->INT_XBOOL + + + + + +INT_CON + +constants + + + +INT_HI->INT_CON + + + + + +INT_CON0 + +0 + + + +INT_XBOOL->INT_CON0 + + + + + +INT_CON1 + +1 + + + +INT_XBOOL->INT_CON1 + + + + + +INT_LO + +[min<max] + + + +INT_CON->INT_LO + + + + + + +INT_BOOL + +[0...1] + + + +INT_CON0->INT_BOOL + + + + + + +INT_CON1->INT_BOOL + + + + + +INT_BOOL->INT_LO + + + + + +INT_LO->INT_BOT + + + + + +FLT_CON64 + +64b consts +[excludes +32b consts] + + + +FLT_TOP->FLT_CON64 + + + + + +FLT_CONPI + +3.14159... + + + +FLT_TOP->FLT_CONPI + + + + + +FLT_X32 + +~f32 + + + +FLT_TOP->FLT_X32 + + + + + +FLT_BOT + +⊥ +:flt + + + +FLT_BOT->BOT + + + + + +FLT_CON64->FLT_BOT + + + + + +FLT_CON32 + +32b consts + + + + +FLT_32 + +f32 + + + +FLT_CON32->FLT_32 + + + + + +FLT_CONPI->FLT_BOT + + + + + + +FLT_X32->FLT_CON32 + + + + + +FLT_CON0 + +0. + + + +FLT_X32->FLT_CON0 + + + + + + +FLT_CON0->FLT_32 + + + + + +FLT_32->FLT_BOT + + + + + +PTR0 + + + +*ptr? + + +struct + + + +PTR->PTR0 + + + + + +PTR0->BOT + + + + + +STRUCT_S1 + + + +field + + + + + + + + +int/ptr + + + +STRUCT_TOP->STRUCT_S1 + + + + + +STRUCT_S2 + + + +field + + + + + + + + +int/ptr + + +field + + + + + + + + +int/ptr + + + +STRUCT_TOP->STRUCT_S2 + + + + + +STRUCT_SN + + + +field + + + + + + + + +int/ptr + + +...   + + + + + + + + +int/ptr + + +field + + + + + + + + +int/ptr + + + +STRUCT_TOP->STRUCT_SN + + + + + +STRUCT_BOT + +⊥ +:struct + + + +STRUCT_BOT->BOT + + + + + +STRUCT_S1->STRUCT_BOT + + + + + + +STRUCT_S2->STRUCT_BOT + + + + + + +STRUCT_SN->STRUCT_BOT + + + + + +MEM_ALIAS1 + +#1 + + + +MEM_TOP->MEM_ALIAS1 + + + + + +MEM_ALIASDOTS + +... + + + +MEM_TOP->MEM_ALIASDOTS + + + + + +MEM_ALIASN + +#n + + + +MEM_TOP->MEM_ALIASN + + + + + +MEM_BOT + +⊥ +:mem + + + +MEM_BOT->BOT + + + + + +MEM_ALIAS1->MEM_BOT + + + + + + +MEM_ALIASDOTS->MEM_BOT + + + + + + +MEM_ALIASN->MEM_BOT + + + + + +TUPLE1 + + + +Tuple + + +type + + + +TUPLE_TOP->TUPLE1 + + + + + +TUPLE2 + + + +Tuple + + +type + + +type + + + +TUPLE_TOP->TUPLE2 + + + + + +TUPLEN + + + +Tuple + + +type + + +... + + +type + + + +TUPLE_TOP->TUPLEN + + + + + +TUPLE_BOT + +⊥ +:tuple + + + +TUPLE_BOT->BOT + + + + + +TUPLE1->TUPLE_BOT + + + + + +TUPLE2->TUPLE_BOT + + + + + +TUPLEN->TUPLE_BOT + + + + + diff --git a/docs/chapter24a/lattice2.gv b/docs/chapter24a/lattice2.gv new file mode 100644 index 00000000..6aa37fa0 --- /dev/null +++ b/docs/chapter24a/lattice2.gv @@ -0,0 +1,85 @@ +digraph Lattice { + compound = true; + // Define nodes + splines=false; + node [shape=oval, style=filled]; + nodesep=0.2; + ranksep=0.4; + + TOP [label="~scalar\n+int+tmp+0", fillcolor=black, fontcolor=white, group=center]; + + // ------------------------ + PTRHQ [label="~tmp\n+tmp+0", fillcolor=green, fontcolor=white, group=left]; + TOP -> PTRHQ + + VALH_ [label="~nscalar\n+int+tmp", fillcolor=white, group=center]; + TOP -> VALH_ + + INTHQ [label="~int\n+int+0", fillcolor=lightblue, group=right]; + TOP -> INTHQ + + LEFTHI [label="junk", style=invis, group=junkleft] + + + PTRHQ -> LEFTHI-> VALH_ -> INTHQ [style=invis]; + { rank=same; PTRHQ; LEFTHI; VALH_; INTHQ } + + // ------------------------ + PTRH_ [label="~ntmp\n+tmp", fillcolor=green, fontcolor=white, group=left]; + VALH_ -> PTRH_ + PTRHQ -> PTRH_ + + INTH_ [label="~nint\n+int", fillcolor=lightblue, group=right]; + VALH_ -> INTH_ + INTHQ -> INTH_ + { rank=same; PTRH_; INTH_ } + + // ------------------------ + NILX_ [label="~nil\n[int,tmp]+0", fillcolor=aqua, group=junkleft]; + INTHQ -> NILX_ + PTRHQ -> NILX_ + + NIL__ [label="nil\n[+int+tmp],0", fillcolor=pink]; + VALH_ -> NIL__; + + NILX_ -> NIL__ [style=invis]; + { rank=same; NIL__; NILX_ } + + // ------------------------ + PTRL_ [label="ntmp\ntmp", fillcolor=green, fontcolor=white, group=left]; + PTRH_ -> PTRL_ + + INTL_ [label="nint\nint", fillcolor=lightblue, group=right]; + INTH_ -> INTL_ + { rank=same; PTRL_; INTL_ } + + // ------------------------ + PTRL0 [label="tmp\ntmp,0", fillcolor=green, fontcolor=white, group=left]; + PTRL_ -> PTRL0 + NIL__ -> PTRL0 + + VALL_ [label="nscalar\nint,tmp", fillcolor=white, group=center]; + PTRL_ -> VALL_ + INTL_ -> VALL_ + NILX_ -> VALL_ + + INTL0 [label="int\nint,0", fillcolor=lightblue, group=right]; + INTL_ -> INTL0 + NIL__ -> INTL0 + + PTRL0 -> VALL_ -> INTL0 [style=invis]; + { rank=same; PTRL0; VALL_; INTL0 } + + // ------------------------ + BOT [label="scalar\nint,tmp,0", fillcolor=black, fontcolor=white, group=center]; + PTRL0 -> BOT + INTL0 -> BOT + VALL_ -> BOT + + // ------------------------ + // Verticle alignment + TOP -> VALH_ -> VALL_ -> BOT [style=invis]; + PTRHQ -> PTRH_ -> PTRL_ -> PTRL0 [style=invis]; + INTHQ -> INTH_ -> INTL_ -> INTL0 [style=invis]; + LEFTHI -> NILX_ [style=invis] +} diff --git a/docs/chapter24a/lattice2.svg b/docs/chapter24a/lattice2.svg new file mode 100644 index 00000000..8b682aa7 --- /dev/null +++ b/docs/chapter24a/lattice2.svg @@ -0,0 +1,260 @@ + + + + + + +Lattice + + + +TOP + +~scalar ++int+tmp+0 + + + +PTRHQ + +~tmp ++tmp+0 + + + +TOP->PTRHQ + + + + + +VALH_ + +~nscalar ++int+tmp + + + +TOP->VALH_ + + + + + + +INTHQ + +~int ++int+0 + + + +TOP->INTHQ + + + + + + + +PTRH_ + +~ntmp ++tmp + + + +PTRHQ->PTRH_ + + + + + + +NILX_ + +~nil +[int,tmp]+0 + + + +PTRHQ->NILX_ + + + + + + +VALH_->PTRH_ + + + + + +INTH_ + +~nint ++int + + + +VALH_->INTH_ + + + + + +NIL__ + +nil +[+int+tmp],0 + + + +VALH_->NIL__ + + + + + +VALL_ + +nscalar +int,tmp + + + + +INTHQ->INTH_ + + + + + + +INTHQ->NILX_ + + + + + + + +PTRL_ + +ntmp +tmp + + + +PTRH_->PTRL_ + + + + + + +INTL_ + +nint +int + + + +INTH_->INTL_ + + + + + + + +NILX_->VALL_ + + + + + +PTRL0 + +tmp +tmp,0 + + + +NIL__->PTRL0 + + + + + +INTL0 + +int +int,0 + + + +NIL__->INTL0 + + + + + +PTRL_->PTRL0 + + + + + + +PTRL_->VALL_ + + + + + +INTL_->VALL_ + + + + + +INTL_->INTL0 + + + + + + + +BOT + +scalar +int,tmp,0 + + + +PTRL0->BOT + + + + + + +VALL_->BOT + + + + + + +INTL0->BOT + + + + + diff --git a/docs/chapter24a/pardoe.docx b/docs/chapter24a/pardoe.docx new file mode 100644 index 00000000..24fde921 Binary files /dev/null and b/docs/chapter24a/pardoe.docx differ diff --git a/docs/chapter24a/webtcp.min.js b/docs/chapter24a/webtcp.min.js new file mode 100644 index 00000000..bf23ee5a --- /dev/null +++ b/docs/chapter24a/webtcp.min.js @@ -0,0 +1,65 @@ +function Http(j){this.cID=Math.random().toString(36).substr(2);this.webtcp=j;this.webtcp.httpClients[this.cID]=this;this.createPacket=function(){return{cID:this.cID,type:"http",host:this.remoteAddress,port:this.remotePort,method:null,data:null}};this.ondata=function(){};this.get=function(g,c){this.on("data",c);this.rpc("httpGet",[g])};this.post=function(g,c,j){this.on("data",j);this.rpc("httpPost",[g,c])}}Http.prototype=new WebTCPIO;function Socket(j,g,c,p){this.sID=Math.random().toString(36).substr(2);this.webtcp=j;this.closed=this.ready=!1;this.options=p;this.sockOpts={_updating:!1};this.remoteAddress=g;this.remotePort=c;this.webtcp.sockets[this.sID]=this;this.createPacket=function(){return{id:Math.random().toString(36).substr(2),sID:this.sID,type:"tcp",options:this.options,host:this.remoteAddress,port:this.remotePort,data:null}};this.onconnect=function(){this.webtcp.sockets[sID].ready=!0;this.webtcp.sockets[sID].closed=!1}; +this.ondata=function(){};this.onend=function(){};this.ontimeout=function(){};this.ondrain=function(){};this.onclose=function(){this.webtcp.sockets[sID].ready=!1;this.webtcp.sockets[sID].closed=!0};this.getSockOpts=function(){this.sockOpts._updating=!0;this.rpc("getSockOpts")};this.onSockOptsRcv=function(c){this.sockOpts=c;this.sockOpts._updating=!1}}Socket.prototype=new WebTCPIO;var JSON;JSON||(JSON={}); +(function(){function j(c,p){var q,t,n,x,i=k,e,l=p[c];l&&"object"==typeof l&&"function"==typeof l.toJSON&&(l=l.toJSON(c));"function"==typeof r&&(l=r.call(p,c,l));switch(typeof l){case "string":return g(l);case "number":return isFinite(l)?String(l):"null";case "boolean":case "null":return String(l);case "object":if(!l)return"null";k+=v;e=[];if("[object Array]"===Object.prototype.toString.apply(l)){x=l.length;for(q=0;qc?"0"+c:c}"use strict";"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+c(this.getUTCMonth()+1)+"-"+c(this.getUTCDate())+"T"+c(this.getUTCHours())+":"+c(this.getUTCMinutes())+":"+c(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var p=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, +n=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,k,v,D={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},r;"function"!=typeof JSON.stringify&&(JSON.stringify=function(c,g,p){var n;v=k="";if("number"==typeof p)for(n=0;n=a};c.countRTO=function(a){var b;return 100b;b++)d.push(String.fromCharCode(b));B=(r.lastIndex=0,d.join("").replace(r,function(a){return c[a]="\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4),""}),r.lastIndex=0,c)}a=a.replace(r,function(a){return B[a]})}return a};var q="websocket xdr-streaming xhr-streaming iframe-eventsource iframe-htmlfile xdr-polling xhr-polling iframe-xhr-polling jsonp-polling".split(" "); +c.probeProtocols=function(){for(var a={},b=0;b