Compare commits

...
3 Commits
15 changed files with 559 additions and 62 deletions

No files matched your search

+9
View File
@@ -207,6 +207,15 @@ syntax feature that you could not verify against one of these sources.
`long` or `float` math in code that does not need the range or precision
- generic pointer or struct field access where a typed pointer or a plain
array would generate less code; `structs`/pointers are not free on 6502
- copying or assigning a struct instance variable by value (``a = b`` where
both are struct instances, or ``Country tmp = countries[i]``) performs a
full memory copy of the struct (via ``sys.memcopy``), including float fields
that go through the FAC. In a loop (iterating, sorting, swapping elements)
this is very expensive: prefer typed pointers (``^^T``) and operate on the
instance in place, or swap pointer entries instead of whole structs. This
applies to both reads and writes of whole struct values. Note that ``swap()``
on struct instances is desugared to three such memcopies (through a compiler
temp), so it carries the same cost; prefer swapping pointer entries.
- flags and truth values held in `ubyte` instead of `bool`: logical
expressions on `bool` operands compile more efficiently than on integers,
which have to be converted to 0 or 1. Conversely, a `bool` array costs one
@@ -145,6 +145,14 @@ easygfx {
return true
}
sub active_screen() -> ^^intuition.Screen {
if screen != 0
return screen
if window != 0
return window.WScreen
return 0
}
sub close() {
; close window and screen (if ours), back to Workbench/textmode
if window != 0 {
+24 -5
View File
@@ -1,8 +1,9 @@
; gfxtext - bare-metal 8x8 text renderer for the Amiga (CPU-only, no OS calls).
; Shared by amiga500 and amiga1200 targets.
;
; Rendering is limited to the embedded 8x8 font (font8x8_basic, 128 glyphs).
; Custom fonts, variable-size glyphs, and font switching are NOT supported.
; The embedded 8x8 font (font8x8_basic, 128 glyphs) is the default.
; set_font() selects a caller-owned 1024-byte table, set_font(0) restores the default.
; set_glyph() edits one glyph of the active font.
; Reverse video is available via bit 7 of the character byte (no second font).
%import math
@@ -14,6 +15,7 @@ gfxtext {
private uword @shared pitch
private ubyte @shared depth
private pointer[8] @shared planes
private pointer @shared active_font
sub init(uword p, ubyte d, ^^pointer bitplanes) {
pitch = p
@@ -24,6 +26,23 @@ gfxtext {
planes[i] = bitplanes[i]
i = i + 1
}
active_font = &font8x8
}
sub set_font(pointer font) {
if font == 0
active_font = &font8x8
else
active_font = font
}
sub set_glyph(ubyte codepoint, pointer rows) {
if codepoint > 127
return
uword base = (codepoint as uword) * 8
ubyte i
for i in 0 to 7
@(active_font + base + i) = rows[i]
}
sub char(uword x, uword y, ubyte chr, ubyte color) {
@@ -73,12 +92,12 @@ gfxtext {
moveq #0,d0
move.w gfxtext.pitch,d0
move.l d0,a2
; a3 = font8x8 + (chr & $7f) * 8
; a3 = active_font + (chr & $7f) * 8
moveq #0,d0
move.b d2,d0
andi.w #$7f,d0
lsl.w #3,d0
lea gfxtext.font8x8,a3
move.l gfxtext.active_font,a3
add.l d0,a3
lea gfxtext.planes,a4
; d6 = depth
@@ -166,7 +185,7 @@ gfxtext {
bool reverse = (chr & $80) != 0
ubyte row
for row in 0 to 7 {
ubyte g = font8x8[glyphIndex + row]
ubyte g = active_font[glyphIndex + row]
if reverse { g = ~g }
if g == 0 {
rowBase += pitch
@@ -2693,36 +2693,32 @@ internal class AstChecker(private val program: Program,
}
}
val rightType = right.inferType(program).getOrUndef()
val offsetIsByte = when(right) {
is TypecastExpression -> right.expression.inferType(program).getOrUndef().isUnsignedByte
else -> rightType.isUnsignedByte
}
val leftIdentifier = left as? IdentifierReference
val leftType = left.inferType(program).getOrUndef()
val leftIsPointerIdentifier = leftIdentifier!=null && (leftType.isUnsignedWord || leftType.isPointer)
val rightType = right.inferType(program).getOrUndef()
val leftIsByteIndex = leftType.isUnsignedByte ||
(left is TypecastExpression && left.expression.inferType(program).getOrUndef().isUnsignedByte)
val rightIsByteIndex = rightType.isUnsignedByte ||
(right is TypecastExpression && right.expression.inferType(program).getOrUndef().isUnsignedByte)
val leftIsByteConstant = left.constValue(program)?.number?.toLong()?.let { it in 0L..0xffL } == true
val rightIsByteConstant = rightValue?.number?.toLong()?.let { it in 0L..0xffL } == true
if(leftIsPointerIdentifier) {
if(offsetIsByte && isDefinitelyInZeropage(leftIdentifier))
val baseExpr = when {
(leftType.isUnsignedWord || leftType.isPointer) && (rightIsByteIndex || rightIsByteConstant) -> left
(rightType.isUnsignedWord || rightType.isPointer) && (leftIsByteIndex || leftIsByteConstant) -> right
else -> return
}
val baseIdentifier = baseExpr as? IdentifierReference
if(baseIdentifier!=null) {
if(isDefinitelyInZeropage(baseIdentifier))
return
errors.warn("this store may rebuild a scratch pointer (many cpu cycles); consider a zero-page uword base with a byte index, or a fixed-address page array", memwrite.position)
// An undecided or preferred zeropage wish may still be allocated there; don't claim it is slow.
if(!isDefinitelyNotInZeropage(baseIdentifier))
return
} else if(baseExpr is NumericLiteral) {
return
}
val baseValue = left.constValue(program)?.number?.toLong()
val byteIndexIdentifier = when (right) {
is IdentifierReference -> right.takeIf { offsetIsByte }
is TypecastExpression -> (right.expression as? IdentifierReference)?.takeIf {
offsetIsByte && it.inferType(program).getOrUndef().isUnsignedByte
}
else -> null
}
val p4FastAddress = baseValue!=null && baseValue in 0x100L..0xffffL &&
offsetIsByte && byteIndexIdentifier!=null
if(p4FastAddress)
return
errors.warn("this store may rebuild a scratch pointer (many cpu cycles); consider a zero-page uword base with a byte index, or a fixed-address page array", memwrite.position)
errors.info("slow store; use a zero-page base with a ubyte index if possible", memwrite.position)
}
private fun isDefinitelyInZeropage(identifier: IdentifierReference): Boolean {
@@ -2736,6 +2732,17 @@ internal class AstChecker(private val program: Program,
return false
}
private fun isDefinitelyNotInZeropage(identifier: IdentifierReference): Boolean {
val decl = identifier.targetVarDecl() ?: return false
if(decl.zeropage == ZeropageWish.NOT_IN_ZEROPAGE)
return true
if(decl.type == VarDeclType.MEMORY) {
val address = decl.value?.constValue(program)?.number?.toLong()
return address!=null && address !in 0L..0xffL
}
return false
}
override fun visit(memwrite: DirectMemoryWrite) {
if(!allowedMemoryAccessAddressExpression(memwrite.addressExpression, program))
errors.err("invalid address type for memory access", memwrite.position)
+7 -6
View File
@@ -445,6 +445,9 @@ main {
@(zp_cursor + byte_offset) = 45
@(non_zp_cursor + byte_offset) = 46
@(zp_cursor + word_offset) = 47
@(byte_offset + word_offset) = 48
@(byte_offset + non_zp_cursor) = 49
@(non_zp_cursor + word_offset) = 50
}
}
""".trimIndent()
@@ -452,8 +455,7 @@ main {
val errors = ErrorReporterForTests(keepMessagesAfterReporting = true)
compileText(C64Target(), false, src, outputDir, writeAssembly = false, errors = errors) shouldNotBe null
errors.errors.size shouldBe 0
errors.warnings.size shouldBe 3
errors.warnings.all { "scratch pointer" in it } shouldBe true
errors.infos.count { "slow store" in it } shouldBe 2
}
test("slow store with a constant on the right is warned") {
@@ -461,10 +463,10 @@ main {
%zeropage basicsafe
main {
sub start() {
uword @shared word_offset = 7
uword @shared @nozp word_offset = 7
ubyte @shared byte_offset = 3
uword @requirezp zp_cursor = $2000
@(word_offset + 1024) = 1
@(word_offset + 4) = 1
@(byte_offset + 1024) = 2
@(1024 + 5) = 3
@(zp_cursor + 4) = 4
@@ -475,8 +477,7 @@ main {
val errors = ErrorReporterForTests(keepMessagesAfterReporting = true)
compileText(C64Target(), false, src, outputDir, writeAssembly = false, errors = errors) shouldNotBe null
errors.errors.size shouldBe 0
errors.warnings.size shouldBe 1
errors.warnings[0] shouldContain "scratch pointer"
errors.infos.count { "slow store" in it } shouldBe 1
}
test("reg params R0-R15 cannot be used for invalid types") {
@@ -1,6 +1,6 @@
Prog8 compiler v14.0-BETA4 by Irmen de Jong (irmen@razorvine.net)
Prerelease version from git commit 35de1c32 in branch master
Prerelease version from git commit 0b3aaa51 in branch master
This software is licensed under the GNU GPL 3.0, see https://www.gnu.org/licenses/gpl.html
Compiling program import-all-amiga1200.p8
@@ -2310,6 +2310,7 @@ easygfx {
^^graphics.RastPort rastport
uword width
^^intuition.Window window
active_screen () -> ^^intuition.Screen
circle (word cx, word cy, word radius, ubyte pen)
clear (ubyte pen)
close ()
@@ -2907,6 +2908,8 @@ gfxtext {
char (uword x, uword y, ubyte chr, ubyte color)
init (uword p, ubyte d, ^^pointer bitplanes)
print (uword x, uword y, str message, ubyte color)
set_font (long font)
set_glyph (ubyte codepoint, long rows)
}
@@ -1,6 +1,6 @@
Prog8 compiler v14.0-BETA4 by Irmen de Jong (irmen@razorvine.net)
Prerelease version from git commit 35de1c32 in branch master
Prerelease version from git commit 0b3aaa51 in branch master
This software is licensed under the GNU GPL 3.0, see https://www.gnu.org/licenses/gpl.html
Compiling program import-all-amiga500.p8
@@ -2084,6 +2084,7 @@ easygfx {
^^graphics.RastPort rastport
uword width
^^intuition.Window window
active_screen () -> ^^intuition.Screen
circle (word cx, word cy, word radius, ubyte pen)
clear (ubyte pen)
close ()
@@ -2681,6 +2682,8 @@ gfxtext {
char (uword x, uword y, ubyte chr, ubyte color)
init (uword p, ubyte d, ^^pointer bitplanes)
print (uword x, uword y, str message, ubyte color)
set_font (long font)
set_glyph (ubyte codepoint, long rows)
}
+18 -2
View File
@@ -408,7 +408,14 @@ modules. Import them the same way as any other library::
pointers, ``char()`` draws one glyph and ``print()`` draws a string with
LF handling and reverse video (bit 7 of the character byte). CPU-only, no
OS calls, transparent glyph background, exact foreground color including 0.
Limited to the embedded 8x8 font; no clipping is performed.
The embedded 8x8 font (128 glyphs) is the default after each ``init()``.
``set_font()`` points the renderer at a caller-owned 1024-byte table with
8 rows per glyph, and ``set_font(0)`` restores the built-in font.
``set_glyph()`` overwrites one glyph, codepoint 0-127, in the active table
from an 8-byte buffer; invalid codepoints are ignored. Bit 7 selects
reverse video and is not part of the codepoint. Call the font routines
after ``init()`` because ``init()`` resets the font. The active table must
be writable RAM when ``set_glyph()`` is used. No clipping is performed.
``sound``
Direct Paula audio: hardware-banging 4-channel 8-bit PCM playback with no
@@ -443,7 +450,16 @@ modules. Import them the same way as any other library::
blocking and returns 0 when the queue is empty; drain messages with
``imsg_poll()``/``imsg_reply()`` in animation loops. ``imsg_wait()`` blocks
until a message arrives. The ``rastport`` and ``window`` variables expose the
handles for direct library calls and IDCMP message handling. See
handles for direct library calls and IDCMP message handling.
``active_screen()`` returns the screen associated with the current window:
the custom screen in fullscreen mode, the Workbench screen in windowed mode,
or 0 when closed. The returned pointer is borrowed; use it to access the
screen's bitmap or viewport, but let ``easygfx.close()`` close the screen.
For example, after opening the display::
^^graphics.BitMap bitmap = intuition.GetScreenBitMap(easygfx.active_screen())
See
``examples/amiga/penrose-triangle.p8`` for a polling loop. Kickstart 1.3
compatible.
+1
View File
@@ -282,6 +282,7 @@ Major breaking changes that require code modifications when upgrading:
- **``-o`` / ``--output`` compiler option** - choose the exact file name and path of the output program file;
all auxiliary output files (assembly, listing, monitor list, IR) are placed alongside it.
Mutually exclusive with ``-out``.
- **Enhanced bmx.py script tool** - 1/2/4/8 bpp, dithering options, and palette output in ``info``.
*This document summarizes major and minor releases. Bugfix releases (e.g., v12.0.1, v12.1.1) are omitted for brevity.*
+7 -7
View File
@@ -28,9 +28,9 @@ Romable (%option romable)
IR/VM
^^^^^
Missing VM Implementations (VirtualMachine.kt)
Missing VM Implementations (VirtualMachine.kt):
- An ``asmsub`` on the virtual target is only rejected when the VM loads the program (``VmProgramLoader.kt``), not at compile time. The rejection cannot simply move into ``AstChecker`` because an ``asmsub`` with an IR body has to stay compilable - the IR-codegen tests use the virtual target to inspect the generated IR of asmsub calls (register and status-flag returns). ``IRInlineBinaryChunk`` (``%binary`` include) stays deferred: the program is not loaded as data, so an embedded blob has no place.
Source line tracking in new codegen backends
Source line tracking in new codegen backends:
- Improve source line tracking across the IR into the generated assembly code in the new codegen backends (new6502, m68k). Currently, the IR preserves some source position information, but this is not consistently propagated through to the final assembly output. Better tracking would improve debugging experience (e.g., in monitor/debugger tools) and make it easier to correlate generated assembly back to the original Prog8 source code. Consider adding source location metadata to IR instructions and ensuring code generators emit appropriate ``.line`` directives or comments in the assembly output.
Libraries
@@ -46,12 +46,11 @@ Optimizations
- Compilation speed: try to join multiple modifications in 1 result in the AST processors instead of returning it straight away every time
- the remaining 6502-specific AST optimizations can't be removed: the old 6502 codegen is still the default backend (``-newcodegen`` is opt-in), so it still depends on them. Revisit once the IR-based 6502 codegen becomes the default.
- m68k/Amiga dead-code elimination: vasm does not strip unreachable routines from the final HUNK output, and ``IRUnusedCodeRemover`` currently keeps assembly subroutines from library modules conservatively (see its TODO). Improve IR reachability analysis so imported library routines are retained only when reachable from program entry points, inline assembly references, address-taken symbols, or other live routines. Keep the existing conservative fallback for opaque assembly references, and add size-regression tests for examples such as ``lowlevel-timer``.
- m68k/Amiga codegen: eliminate redundant pointer reloads in the IR. For example, ``wavc``'s ``read_le_word`` loads its ``addr`` argument twice because the optimizer rewrites the second ``loadm.p`` as ``loadm.l`` and existing CSE does not merge different types. See the IR-peephole section in ``ideas/m68k-better-codegen.md`` for a plan.
- IR optimization: investigate restricted common-subexpression elimination within a single basic block for identical pure arithmetic expressions whose inputs are unchanged. Initially exclude memory reads, calls, and control-flow boundaries. The qemu68k maze BFS repeats ``idx +/- H`` to update ``cells``, ``pathdirs``, and ``solveQueue``; sharing that computed neighbor index could be a focused benchmark.
- optimize the small integer division routines in ``compiler/res/prog8lib/math.asm`` (``divmod_b_asm``, ``divmod_ub_asm``, ``divmod_w_asm``, ``divmod_uw_asm``) using the constant-divisor reciprocal-multiply / fast-division tricks from https://forums.nesdev.org/viewtopic.php?t=11336 . Division by a known small constant (or a small variable divisor) can often be replaced by a multiply and a shift, which is much faster than the current subtractive loops. For the 68000 targets this is likely only relevant for the software 32-bit helpers in ``amiga500/m68k_prog8_longmath.asm``, since native ``DIVU``/``DIVS`` already cover small divisions; evaluate and adapt as warranted.
- 6502 codegen: cheap memory stores for ``@(const + expr)`` style accesses, measured and ranked in ``ideas/betterpointers.md``. P1, P2, P3, P4 and P9 are implemented; still open are P5 (three byte arguments in A/X/Y), P6 (inline shift-add policy for ``*const``), P7a/P7b (address strength reduction within a loop and across calls, the general fix for the per-store rebuild), P8 (branch-chain compound conditions), P10 (page-boundary loop splitting) and P11 (6502 multi-parameter inlining, currently capped at one parameter).
- 6502 codegen: reuse the computed element address of an array-of-struct-instances access within a basic block. Both backends currently re-emit ``lda idx / jsr prog8_math.mul_word_<size> / 16-bit add to scratch`` per field access (about 20 bytes per field); the ``sorting.p8`` example's bubble sort and dump loop pay roughly 400 extra bytes for this on the classic backend, where it is large relative to the compact per-access code. Hoisting a typed pointer ``^^T p = &&arr[i]`` in the source avoids it (see the cost note in ``structpointers.rst``).
- language-level companion to the above, not implemented: named memory regions (``&ubyte[40][25] screen = $0400``) with a fixed base, a zero-page cursor contract and 2D indexing, so a hot memory access does not depend on whether a base variable happens to be placed in zero page. See Appendix C in ``ideas/betterpointers.md``, which lists the open design questions that must be answered before implementing it.
- 6502 codegen: cheap memory stores for ``@(const + expr)`` style accesses, measured and ranked in ``ideas/betterpointers.md``. P1, P2, P3, P4 and P9 are implemented; still open are P5 (three byte arguments in A/X/Y), P6 (inline shift-add policy for ``*const``), P7a/P7b (reuse a computed address instead of rebuilding it per access: within a loop, across calls, and for each field of an array-of-struct-instances access in a single basic block), P8 (branch-chain compound conditions), P10 (page-boundary loop splitting) and P11 (6502 multi-parameter inlining, currently capped at one parameter). For the struct case, both backends still re-emit ``lda idx / jsr prog8_math.mul_word_<size> / 16-bit add to scratch`` per field (about 20 bytes per field); the ``sorting.p8`` bubble sort and dump loop pay roughly 400 extra bytes for this on the classic backend. Hoisting a typed pointer ``^^T p = &&arr[i]`` in the source avoids it (see the cost note in ``structpointers.rst``).
- m68k/Amiga IR peephole: eliminate double pointer reloads. For example, ``wavc``'s ``read_le_word`` loads its ``addr`` argument twice because the optimizer rewrites the second ``loadm.p`` as ``loadm.l`` and existing CSE does not merge different types. Repeated memory loads are the only thing in scope here; see the IR-peephole section in ``ideas/m68k-better-codegen.md`` for the type compatibility rules and the plan.
- IR optimization: investigate restricted common-subexpression elimination within a single basic block for identical pure arithmetic expressions whose inputs are unchanged. Memory reads, calls, and control-flow boundaries are intentionally out of scope; the repeated typed memory load is tracked separately above. The qemu68k maze BFS repeats ``idx +/- H`` to update ``cells``, ``pathdirs``, and ``solveQueue``; sharing that computed neighbor index could be a focused benchmark.
- Language-level companion to the 6502 address work, not implemented: named memory regions (``&ubyte[40][25] screen = $0400``) with a fixed base, a zero-page cursor contract and 2D indexing, so a hot memory access does not depend on whether a base variable happens to be placed in zero page or on the optimizer reusing a computed address. Unlike the compiler-only items above, this is a source-visible design change. See Appendix C in ``ideas/betterpointers.md``, which lists the open design questions that must be answered before implementing it.
- Direct struct instances on the classic 6502 codegen: word augmented assignment (``+=``/``-=`` on word fields) and float augmented assignment still build a zp pointer instead of using absolute addressing.
@@ -68,6 +67,7 @@ Won't do's or deferred
- Deferred: support ``&array[i].field`` syntax to take the address of a struct field in an array. Currently only ``&array[i] + offsetof(Struct.field)`` works; ``&array[i].field`` is parsed as a field access on the resulting pointer and rejected by the checker.
- Deferred: support typed pointer arrays as struct fields, curretly requires untyped pointers arrays.
- Deferred: make a form of "manual generics" possible, see ``ideas/polymorphism.md``
- Won't do unless a concrete need appears: variadic subroutines with compile-time rest parameters, see ``ideas/variadic-subroutines.md``. The M68K calling-convention motivation disappears once calls are lowered to ordinary fixed-arity calls; a typed ``print(...)`` intrinsic gives the useful printf-style ergonomics, and homogeneous lists are already expressible as array plus length.
- Deferred: when implementing unsigned longs: remove the unsigned-long constant "hack" that lets unsigned long constants be used as values for signed longs without needing a cast (the ``Antlr2KotlinVisitor.kt:508``/``:548`` "TODO hack" comments, ``AstExpressions.kt:145`` "TODO should be ULONG, but we don't have that type yet", and ``AsmAssignment.kt:129`` ``TODO("unsigned long $pos")``)
- Deferred: make the fixed zero-page scratch locations (``P8ZP_SCRATCH_B1``/``_REG``/``_W1``/``_W2``/``_PTR``) dynamic rather than hardcoded per target. Right now they live at fixed per-target addresses and are always reserved; a ``%zpreserved``/``%zpallowed`` range that excludes them only produces a warning (the codegen would still overwrite that memory). Relocating scratch to an available low-address byte (or making it configurable) when not in conflict would let ``%zpreserved``/``%zpallowed`` fully protect the desired areas. See ``MemoryRegions.kt`` (``Zeropage.checkScratchConflicts`` and the scratch-byte list it maintains) and the per-target ``*Zeropage`` classes.
- Deferred: really fixing the pointer dereferencing issues (cursed hybrid between IdentifierReference, PtrDereferece and PtrIndexedDereference), which may require getting rid of scoped identifiers altogether and treating '.' as a "scope or pointer following operator".
+15
View File
@@ -70,6 +70,12 @@ main {
gfxtext.print(15, 210, iso:"reverse: \x82\x81", 0)
gfxtext.print(16, 220, iso:"some byte aligned text", 0)
; Install a custom heart glyph and draw it in the white bottom quarter.
gfxtext.set_glyph(1, &heart)
gfxtext.char(200, 200, 1, 0)
gfxtext.char(210, 201, 1, 0)
gfxtext.char(220, 202, 1, 0)
; Build the copper list with the copper helper (bitplane slots,
; display registers and the raster gradient) and start it.
uword planeBase = build_copperlist(regs)
@@ -90,6 +96,15 @@ main {
const ubyte BAR_TOP = 90
const ubyte BAR_LINES = 24
ubyte[8] heart = [%00000000,
%01100110,
%11111111,
%11111111,
%01111110,
%00111100,
%00011000,
%00000000]
; Static purple-to-magenta raster gradient, one COLOR00 per line.
uword[BAR_LINES] gradient = [
$0010, $0104, $0207, $0309, $050b, $070d, $090e, $0b0f,
+13 -11
View File
@@ -710,27 +710,29 @@ short-circuit cases with side effects in the right operand.
Target: diagnostics.
Where: `AstChecker.visit(DirectMemoryWrite)` in
`compiler/src/prog8/compiler/astprocessing/AstChecker.kt`. Warnings go through
`errors.warn(msg, position)` and are gated by `-ignorefootguns`.
`compiler/src/prog8/compiler/astprocessing/AstChecker.kt`. Infos go through
`errors.info(msg, position)` and are gated by `-ignorefootguns`.
Original state: there was no lint for slow `@(...)` stores or address arithmetic.
Implemented: on 6502-family targets, direct stores with a dynamic `+` address
offset warn when they may rebuild a scratch pointer. The checker skips library
code, constant offsets, the P4 absolute-indexed form, and byte-indexed accesses
through a base known to be in zero page.
offset are reported when the suggested fast form can actually be used. The
checker skips library code, constant-only addresses, the P4 absolute-indexed
form, and byte-indexed accesses through a base known to be in zero page, in
either operand order. It also stays quiet when the base is only *possibly*
allocated to zero page (the real allocation happens later, during codegen) or
when the index is a word whose range is not known to fit a byte.
The diagnostic is:
> this store may rebuild a scratch pointer (many cpu cycles); consider a
> zero-page uword base with a byte index, or a fixed-address page array
> (`&ubyte[256] page = ADDRESS`).
> slow store; use a zero-page base with a ubyte index if possible
It is advisory only; it does not change code generation.
Tests: `TestAstChecks` verifies warnings for word-indexed numeric bases and
non-zero-page pointer bases, and no warning for the P4 byte-indexed path,
constant offsets, or a required-zero-page cursor.
Tests: `TestAstChecks` verifies infos for explicitly non-zero-page pointer bases
with a byte index, and no info for the P4 byte-indexed path, constant offsets,
a required-zero-page cursor, the reversed byte-plus-pointer form with a
possibly zero-page pointer, or a word index that cannot be narrowed safely.
### P10 (stretch). Split loops at page boundaries
+362
View File
@@ -0,0 +1,362 @@
# Compile-time Variadic Subroutines [won't do]
**Status: won't do unless a concrete need appears.** This is a design exploration
only; no compiler or library files are changed by this document. The M68K
calling-convention motivation disappears once calls are lowered to ordinary
fixed-arity calls. The useful part is printf-style output, which is better
served by a standalone typed `print(...)` intrinsic; homogeneous lists remain
expressible as array plus length.
## Overview
Prog8 has no variadic subroutines, no default parameters, and no user-defined
overloading. The only printf-like mechanism is the Copperline debug queue in
`compiler/res/prog8lib/shared_amiga_emudbg.p8`: callers queue values with
`debug_arg` / `debug_arg_str`, then call `debug_printf(str format)`. The queue is
bounded to 32 values, the values are typeless, and the format string carries
all type information.
That is a reasonable emulator debug facility, but it is not a good language
feature. C-style varargs are also a poor fit: the caller must supply manual type
tags, the callee walks an untyped runtime argument area, and neither side is
type-checked against the other.
This proposal adds variadic subroutines that are fully resolved at compile
time. Each call shape becomes an ordinary fixed-arity subroutine before IR
generation. There is no runtime argument list, no `va_list`, no tagged union,
and no format string.
The design was explored with these constraints:
- The original motivation came from M68K frame-based calling conventions, but
the chosen lowering is backend-independent.
- The mechanism would work on 6502 and virtual targets without a new ABI.
- Variadic subroutines may not be recursive, directly or indirectly.
- All argument type information is known at compile time.
## Assessment
The design is workable but is not worth implementing as a general Prog8
language feature right now:
- The main ergonomic win, printf-style output, can be delivered by a typed
`print(...)` intrinsic without user-defined variadics, specialization of user
routines, or a recursion ban.
- Homogeneous rest is mostly array plus length with extra compiler machinery.
- Per-call-shape specialization hides arity and code-size cost, which conflicts
with Prog8's explicit size/cost style.
- The compiler and tooling surface is large relative to the benefit.
- `debug_arg` / `debug_arg_str` / `debug_printf` already covers bounded debug
output.
If a concrete program appears where these alternatives are inadequate, this
design is the fallback.
## Goals
- Let a caller write `sum(a, b, c)` or `log("x=", x, "\n")` naturally.
- Keep full compile-time type checking of every argument.
- Let a callee iterate a homogeneous argument list when that is useful.
- Let a user-defined wrapper process a heterogeneous argument list with
compile-time unrolling, without runtime tags or type tests.
- Generate ordinary subroutines and ordinary calls for every backend.
- Avoid static scratch buffers that nested calls could corrupt.
## Non-goals
- No runtime-determined argument count.
- No C `...` ABI, `va_start` / `va_end`, or stack walking.
- No caller-written type letters beyond a future optional checked format
string; the initial printf-like sink has no format string at all.
- No runtime `variant` or tagged descriptor array.
- No dynamic indexing or storage of a heterogeneous tuple; compile-time
iteration is allowed.
- No variadic `asmsub`, `extsub`, builtin function, or bank subroutine.
- No recursion in or through a variadic subroutine.
## Proposed syntax
### Homogeneous, iterable rest
```prog8
sub sum(...values: uword) -> uword {
total = 0
for value in values {
total += value
}
return total
}
x = sum(a, b, c)
y = sum()
```
A rest parameter may follow ordinary parameters:
```prog8
sub sum_with_seed(uword seed, ...values: uword) -> uword
```
The rest element type is explicit. All trailing arguments are coerced to that
type by the normal cast-insertion pass. `len(values)` folds to the call-site
arity, and `for value in values` can be unrolled.
### Heterogeneous, forward-only rest
```prog8
sub log(...parts) {
if enabled {
print("[LOG] ")
for part in parts {
print(part)
print(" ")
}
print("\n")
}
}
log("x=", x, " y=", y)
```
`...parts` has no element type. It is a compile-time tuple of the caller's
argument expressions. Inside the callee it can be:
- expanded in a call argument list, written `parts...`, including in the middle
of the list: `print("[LOG] ", parts..., "\n")`;
- iterated with `for part in parts`, which is unrolled per element and
type-checked with that element's concrete type.
It cannot be assigned, dynamically indexed, compared as a whole, or stored. A
body that is not valid for every element type is a compile-time error in the
specialization.
This is what makes a generic printf-style wrapper possible: `log` accepts any
mix of printable values, adds its own prefix and separators, and may choose a
different sink intrinsic, while all type information stays known at compile
time.
### Typed print
`print(...)` is proposed as a compiler intrinsic with no format string. Each
expression is printed using its own static type:
```prog8
print("x=", x, " y=", y, "\n")
```
It lowers roughly to:
```prog8
txt.print("x=")
txt.print_uw(x)
txt.print(" y=")
txt.print_uw(y)
txt.print("\n")
```
Initial mapping:
| Static type | Routine |
| --- | --- |
| `str` | `txt.print` |
| `byte` / `ubyte` | `txt.print_b` / `txt.print_ub` |
| `word` / `uword` | `txt.print_w` / `txt.print_uw` |
| `long` | `txt.print_l` |
| `bool` | `txt.print_bool` |
| float | `floats.print` |
A type without a printable lowering is a compile-time error at the print call.
The intrinsic is not a normal subroutine and cannot be redefined. A later,
separate proposal could also accept multi-argument `txt.print(...)` as sugar
for this intrinsic; the first implementation should use the unambiguous
builtin name.
## Lowering
Both rest modes are lowered to ordinary parameters in a generated
specialization. The specialization name is an implementation detail, for
example `sum$3` or `log$2_str_uword_str`.
### Typed rest
For `sum(a, b, c)` with `...values: uword`, emit an ordinary subroutine:
```prog8
sub sum$3(uword v0, uword v1, uword v2) -> uword { ... }
```
References to `values[i]` in the cloned body become `v0`, `v1`, `v2`.
`len(values)` becomes the constant `3`. The call site becomes a call to
`sum$3(a, b, c)` with three ordinary arguments.
### Forward-only rest
For `log("x=", x, "\n")` where `x` is a `uword`, emit:
```prog8
sub log$3(str p0, uword p1, str p2) {
if enabled
print(p0, p1, p2)
}
```
Then the print intrinsic lowers to ordinary typed print calls. The
specialization is cached by the sequence of concrete argument types, so calls
with the same type shape share it while different expressions are passed as
ordinary arguments.
A `for part in parts` loop is unrolled into one statement per generated
parameter. In `log$4(str p0, uword p1, str p2, str p3)`, `part` is bound to
`p0`, then `p1`, and so on, and the loop body is type-checked separately for
each concrete type. No runtime type test or descriptor is emitted.
### Nested variadic calls
A variadic routine may call another variadic routine by forwarding its rest
tuple. Discovery of needed specializations therefore walks cloned bodies too.
Because variadic call graphs are acyclic, this terminates. The implementation
can use a worklist and stop when no new specialization is created.
## Recursion ban
A variadic subroutine may not call itself, directly or indirectly. The compiler
checks the call graph and rejects any cycle containing a variadic subroutine
with a clear diagnostic, for example:
```text
variadic subroutine 'main.log' may not be recursive
```
This keeps the number of specializations finite and avoids infinite template
expansion. Ordinary non-variadic recursion is unaffected.
## Arity and diagnostics
- Zero trailing arguments are valid.
- The minimum arity is the number of fixed parameters.
- The maximum arity is capped, proposed default 16, with a clear diagnostic
beyond it.
- Calls to `asmsub`, `extsub`, builtins, and bank subroutines keep exact arity
checks.
- The generated specialization names are not visible or callable from Prog8
source. Symbol dumps and language-server hover show the original rest
signature.
## Compiler design
The feature is mostly frontend and optimizer work. It happens before
`SimplifiedAstMaker`, so IR, the VM, and both code generators see only ordinary
fixed-arity subroutines. No IR format bump is needed.
Likely implementation areas:
- `parser/src/main/antlr/Prog8ANTLR.g4`: `sub_param`, `sub_params`, and the call
syntax. Calls already allow arbitrary argument lists.
- `compilerAst/src/prog8/ast/antlr/Antlr2KotlinVisitor.kt`: `visitSub_param`
records the rest mode.
- `compilerAst/src/prog8/ast/statements/AstStatements.kt`: `SubroutineParameter`
gains a rest mode and propagates it through `copy` and `equals`.
- `compiler/src/prog8/compiler/astprocessing/AstIdentifiersChecker.kt`: replace
exact arity with minimum arity for ordinary variadic subroutines.
- `compiler/src/prog8/compiler/astprocessing/AstExtensions.kt`: diagnostics for
"at least N" arguments.
- `compiler/src/prog8/compiler/astprocessing/TypecastsAdder.kt`: coerce typed
rest arguments to the declared element type; leave forwarded arguments with
their own types.
- `compiler/src/prog8/compiler/astprocessing/AstChecker.kt`: keep strict checks
for asmsub, extsub, builtins, and bank subroutines.
- `compilerAst/src/prog8/compiler/CallGraph.kt`: reject variadic recursion and
drive specialization discovery.
- A new specialization pass before `SimplifiedAstMaker.kt`: clone the routine
per call shape, add ordinary parameters, rewrite `values[i]`, `len(values)`,
and `parts...`, and unroll `for part in parts`.
- `compiler/src/prog8/compiler/astprocessing/SimplifiedAstMaker.kt` and
`simpleAst` symbol tables: register generated routines with generated names.
- `codeOptimizers/src/prog8/optimizer/Inliner.kt` and other optimizers: treat
generated specializations as ordinary code; skip the original variadic
template.
- `codeCore/src/prog8/code/core/BuiltinFunctions.kt` and IR codegen for the
`print(...)` intrinsic lowering.
- `languageServer` and `AstToSourceTextConverter`: display rest signatures.
After adding or cloning AST nodes, call `symbolTable.resetCachedFlat()` so
symbol lookups remain correct.
## Target scope
M68K is the first target for implementation and validation because its
frame-based calling convention was the original motivation for looking at
variadics. However, this design does not depend on the M68K stack ABI. Since
every variadic call is lowered to ordinary fixed-arity calls before IR, the
same source works on 6502 and virtual targets with no extra codegen support.
A future runtime-count extension would be different: an M68K-only frame-slot
temporary array passed as pointer plus count. That would need changes to
`StackFrameLayout.rewriteCallArgumentLocations`, `CallLocation`, the IR text
codec, and the IR format version. It is explicitly out of scope here.
## Rejected alternatives
### C-style varargs
Rejected: manual type letters, no argument type checking, and runtime stack
walking. This is the ergonomics problem the proposal exists to avoid.
### Typed rest as a runtime slice
The earlier idea of materializing the trailing arguments into a temporary
array and passing pointer plus count was rejected. On 6502 and virtual targets
there are no call frames, so a static scratch array is corrupted by nested
calls such as `sum(1, sum(2, 3), 4)`. It also requires a new slice type, a
runtime count, IR serialization changes, and VM support.
### Runtime tagged descriptors
A `variant`-like descriptor array would allow arbitrary heterogeneous runtime
values, but it introduces type erasure, tag dispatch, payload-size problems
across targets, and a new ABI. The forward-only tuple plus compile-time
unrolled iteration covers prefixes, separators, conditional logging, sink
choice, and uniform per-element processing without that machinery. Truly
type-specific behavior for one element still needs an explicit wrapper at the
call site.
### Fixed maximum arity expansion
Generating `log1` through `log16` is mechanically simple and type-safe, but
the callee cannot iterate a homogeneous rest list, and code size grows for all
arities whether used or not. Per-call-shape specialization grows only for
shapes that are actually used.
### Keeping only the debug queue
Keeping `debug_arg` / `debug_arg_str` / `debug_printf` avoids language changes,
but it remains typeless, capped at 32 values, and tied to Copperline debug
ports. It is not a general-purpose language feature.
## Testing
- Compiler AST and diagnostic tests for minimum arity, arity cap, recursion ban,
and fixed-arity checks on asmsub, extsub, builtins, and bank subs.
- Specialization tests that inspect generated routine names and parameter
types, without dumping raw assembly.
- Homogeneous tests using the virtual target where possible, for example
`sum(1, 2, 3)` and `sum()`.
- Print-lowering tests that inspect the call sequence by parsing generated
lines, not by string-matching full assembly listings.
- Nested forwarding tests such as an outer wrapper calling an inner wrapper.
- M68K tests should use `writeAssembly = true, assemble = false` so they do not
depend on `vasm`, which is not available in CI.
- No IR round-trip changes are expected because no IR format change is needed.
## Open questions
- Exact spelling of the rest marker: `...values: T` versus an alternative such
as `values...: T`.
- Exact name and namespace of the print intrinsic: proposed `print(...)`, with
optional multi-argument `txt.print(...)` sugar later.
- Which operations are allowed in a `for part in parts` body. Initially,
anything that type-checks for each concrete element type.
- Default arity cap: 16 is proposed; 32 would match the existing debug queue
but increases code-size risk.
- Whether a checked format-string variant should be added later for programs
that want printf-compatible output rather than expression-list printing.
+54 -5
View File
@@ -12,6 +12,9 @@ if __package__:
BAYER_4X4,
BAYER_8X8,
apply_ordered_dither,
default_colors,
flat_palette_to_rgb,
palette_8to4,
)
else:
from cx16images import (
@@ -19,6 +22,9 @@ else:
BAYER_4X4,
BAYER_8X8,
apply_ordered_dither,
default_colors,
flat_palette_to_rgb,
palette_8to4,
)
@@ -50,7 +56,8 @@ class Bmx:
return f"[BMX image {self.width}*{self.height}, {self.bpp} bpp, {self.pal_used} colors, {cmpr}]"
def read(self, filename: str):
data = open(filename, "rb").read()
with open(filename, "rb") as inp:
data = inp.read()
self.__parse_header(data)
self.palette_data = data[32: 32 + self.pal_used * 2]
self.bitmap_data = data[32 + self.pal_used * 2:]
@@ -124,7 +131,15 @@ class Bmx:
print(f"Warning: cropping {bitmap_image.width - aligned_width} right-edge pixels for {bpp}bpp byte alignment")
bitmap_image = bitmap_image.crop(0, 0, aligned_width, bitmap_image.height)
preserve_palette = bitmap_image.has_palette() and bpp == 8 and not preserve_first_16_colors and dither == "none"
preserve_palette = bitmap_image.has_palette() and bpp == 8 and dither == "none"
if preserve_first_16_colors and bitmap_image.has_palette() and bpp == 8:
# Leave an existing palette untouched; only warn if it doesn't start
# with the CX16 defaults that --preserve16 asks for.
preserve_palette = True
palette = palette_8to4(bitmap_image.get_palette())
if palette[:16] != default_colors[:16]:
print("warning: --preserve16 has no effect on an image with a palette; "
"the first 16 colors are not the CX16 defaults. Leaving the palette unchanged.")
if not preserve_palette:
if dither in ("ordered4", "ordered8"):
source_image = bitmap_image.get_image().convert("RGB")
@@ -229,10 +244,44 @@ def bmx_show(filename: str) -> None:
img.show()
def bmx_palette_words(bmx: Bmx) -> List[int]:
return [int.from_bytes(bmx.palette_data[i:i + 2], "little")
for i in range(0, len(bmx.palette_data), 2)]
def image_palette_words(image: Image) -> List[int]:
palette = palette_8to4(flat_palette_to_rgb(image.getpalette() or []))
return [r << 8 | g << 4 | b for r, g, b in palette]
def print_palette(words: List[int]) -> None:
if not words:
print("no palette")
return
print(f"palette ({len(words)} colors, 0RGB hex):")
for start in range(0, len(words), 16):
row = words[start:start + 16]
print(f" {start:02x}: " + " ".join(f"{word:03x}" for word in row))
def bmx_info(filename: str) -> None:
bmx = Bmx()
bmx.read(filename)
print(f"{filename}: {bmx}")
with open(filename, "rb") as inp:
is_bmx = inp.read(3) == b"BMX"
if is_bmx:
bmx = Bmx()
bmx.read(filename)
print(f"{filename}: {bmx}")
print_palette(bmx_palette_words(bmx))
return
with Image.open(filename) as image:
if image.mode == "P":
print(f"{filename}: palette image {image.width}*{image.height}, "
f"{len(image.getpalette()) // 3} colors")
print_palette(image_palette_words(image))
else:
print(f"{filename}: {image.mode} image {image.width}*{image.height}, no palette")
def bmx_create(filename: str, outputfile: str, preserve16: bool, dither: str, bpp: int, hires: bool = False) -> None:
+2
View File
@@ -216,6 +216,8 @@ class BitmapImage:
palette_rgb = flat_palette_to_rgb(palette_image.getpalette() or [])
palette_rgb = list(dict.fromkeys(palette_8to4(palette_rgb)))
if preserve_first_16_colors:
# Don't waste palette entries on colors that are already defaults.
palette_rgb = [color for color in palette_rgb if color not in default_colors[:16]]
palette_rgb = default_colors[:16] + palette_rgb
elif fixed_color_zero:
assert fixed_color_zero[0]<16 and fixed_color_zero[1]<16 and fixed_color_zero[2]<16, "fixed color 0 must to be 4 bits per channel"