m68k: extend store-reload to frame slots

This commit is contained in:
Irmen de Jong committed 2026-11-03 17:11:59 +01:00
1 parent 3cae5cfe4d
commit e845e789fd
3 files changed
+123 -14

No files matched your search

@@ -251,9 +251,26 @@ private sealed interface LeaBase {
private val addressArithOpPattern = Regex("^(addq|subq|adda|suba|add|sub)\\.([wl])$")
private val addressRegPattern = Regex("^a[0-7]$")
private val frameSlotPattern = Regex("^\\((-?\\d+),a5\\)$")
private val symbolBasePattern = Regex("^([^$():,\\s]+?)([+-]\\d+)?$")
/**
* Displacement of an `(off,a5)` frame-slot operand in any emitted form
* (`8(a5)`, `-2(a5)`, `(-8,a5)`, `(a5)`), or null. Frame slots are RAM by
* construction, so access has no side effects.
*/
private fun parseFrameSlot(text: String): Long? {
val t = text.trim()
val lower = t.lowercase()
val inner = when {
lower.endsWith("(a5)") -> t.substring(0, t.length - 4)
lower.endsWith(",a5)") && t.startsWith("(") -> t.substring(1, t.length - 4)
else -> return null
}
if (inner.isEmpty())
return 0L
return inner.toLongOrNull()
}
/**
* Split a `movea.l`/`move.l` source into a foldable lea base, or null when folding
* is unsafe or impossible. `$hex` sources are rejected (may be hardware registers
@@ -280,8 +297,8 @@ private fun parseLeaBase(src: String): LeaBase? {
}
if (text.lowercase().matches(addressRegPattern))
return LeaBase.Register(text.lowercase())
frameSlotPattern.matchEntire(text)?.let {
return LeaBase.Frame(it.groupValues[1].toLong())
parseFrameSlot(text)?.let {
return LeaBase.Frame(it)
}
if (text.startsWith("$"))
return null
@@ -583,6 +600,10 @@ private fun optimizeSwapBack(linesBy: Sequence<List<TrimmedLine>>): List<Modific
return mods
}
/** `(off,a5)` frame slot: RAM by construction, so the access has no read/write
* side effects and hits the same slot while a5 is untouched (consecutive lines). */
private fun String.isFrameSlotOperand(): Boolean = parseFrameSlot(this) != null
private fun optimizeStoreReloadToRegCopy(linesBy: Sequence<List<TrimmedLine>>): List<Modification> {
// move.S dN,M / move.S M,dK (K != N, same mem) -> keep store, replace reload with move.S dN,dK
val mods = mutableListOf<Modification>()
@@ -591,19 +612,25 @@ private fun optimizeStoreReloadToRegCopy(linesBy: Sequence<List<TrimmedLine>>):
val second = lines[1].instruction
if (hasLabel(lines[1].trimmed)) continue
if (!first.isMove() || !second.isMove()) continue
val m1 = first.moveOperands() ?: continue
val m2 = second.moveOperands() ?: continue
val (src1, dst1) = m1
val (src2, dst2) = m2
// paren-aware split: frame-slot operands embed a comma (`(-8,a5),d1`).
val m1 = first.instructionOperands()?.let(::splitOperands) ?: continue
val m2 = second.instructionOperands()?.let(::splitOperands) ?: continue
if (m1.size != 2 || m2.size != 2) continue
val (src1, dst1) = m1[0].trim() to m1[1].trim()
val (src2, dst2) = m2[0].trim() to m2[1].trim()
if (!src1.lowercase().matches(dataRegisterPattern)) continue
if (dst1.lowercase().matches(dataRegisterPattern)) continue
if (!dst2.lowercase().matches(dataRegisterPattern)) continue
if (src2.lowercase() != dst1.lowercase()) continue
if (dst2.lowercase() == src1.lowercase()) continue
if (first.moveSize() != second.moveSize()) continue
// memory safety: only plain memory operands, no indirect/indexing whose address or
// side effects (e.g. an (aX)+ increment) would differ between read and no-read
if (!dst1.isSafeMemoryOperand()) continue
// memory safety: plain memory operands or (off,a5) frame slots; anything
// else parenthesised (e.g. an (aX)+ increment) stays excluded since its
// address or side effects would differ between read and no-read.
// memory safety: plain memory operands or (off,a5) frame slots; anything
// else parenthesised (e.g. an (aX)+ increment) stays excluded since its
// address or side effects would differ between read and no-read.
if (!dst1.isSafeMemoryOperand() && !dst1.isFrameSlotOperand()) continue
val sz = first.moveSize()
val indent = lines[1].value.takeWhile { it.isWhitespace() }
val label = keepLabel(lines[1].trimmed)
@@ -1497,10 +1497,21 @@ class TestInstructionSelectionOptimizations : FunSpec({
" rts"
)
optimizeAssembly(lines)
println("FRAME-LINES:" + lines)
lines.any { it.trim() == "lea (-6,a5),a2" } shouldBe true
}
test("folds unsigned frame slot base plus arithmetic into lea") {
// real codegen emits `8(a5)`, not `(8,a5)`, for positive offsets.
val lines = mutableListOf(
" movea.l 8(a5),a2",
" addq.l #2,a2",
" move.w (a2),d0",
" rts"
)
optimizeAssembly(lines)
lines.any { it.trim() == "lea (10,a5),a2" } shouldBe true
}
test("M5 forgets a0 across a label") {
val lines = mutableListOf(
" lea arr,a0",
@@ -1716,14 +1727,50 @@ class TestInstructionSelectionOptimizations : FunSpec({
lines.count { it.contains("p8b_test.p8v_x,d1") } shouldBe 0
}
test("A2 keeps frame-slot reloads untouched") {
test("A2 replaces a frame-slot store-reload with a register copy") {
val lines = mutableListOf(
" move.l d0,8(a5)",
" move.l 8(a5),d1",
" rts"
)
optimizeAssembly(lines)
lines.count { it == " move.l 8(a5),d1" } shouldBe 1
lines.count { it == " move.l d0,8(a5)" } shouldBe 1
lines.count { it == " move.l d0,d1" } shouldBe 1
lines.count { it == " move.l 8(a5),d1" } shouldBe 0
}
test("A2 replaces a negative-offset frame-slot store-reload") {
val lines = mutableListOf(
" move.b d2,(-5,a5)",
" move.b (-5,a5),d3",
" rts"
)
optimizeAssembly(lines)
lines.count { it == " move.b d2,(-5,a5)" } shouldBe 1
lines.count { it == " move.b d2,d3" } shouldBe 1
}
test("A2 keeps mismatched frame-slot offsets untouched") {
val lines = mutableListOf(
" move.l d0,8(a5)",
" move.l 4(a5),d1",
" rts"
)
optimizeAssembly(lines)
lines.count { it == " move.l 8(a5),d0" } shouldBe 0
lines.count { it == " move.l 4(a5),d1" } shouldBe 1
}
test("A2 keeps post-increment store-reloads untouched") {
val lines = mutableListOf(
" move.l d0,(a0)+",
" move.l (a0)+,d1",
" rts"
)
optimizeAssembly(lines)
lines.count { it == " move.l d0,(a0)+" } shouldBe 1
lines.count { it == " move.l (a0)+,d1" } shouldBe 1
lines.count { it == " move.l d0,d1" } shouldBe 0
}
test("A2 drops a store-reload-into-source pair as a mirror") {
+36 -1
View File
@@ -166,7 +166,7 @@ effort. Status: proposal.
between accesses (see maze `cells` case) - that needs callee analysis,
i.e. item 4.4, not this pass.
### 2.6 Store-reload to reg copy (extend)
### 2.6 Store-reload to reg copy (extend) [DONE]
- Existing pass handles `move.S d0,(mem)` then `move.S (mem),d1` ->
`move.S d0,d1` for all sizes already (byte/word extension is done).
- Extend to frame slots (`(off,a5)`), currently rejected by
@@ -174,6 +174,17 @@ effort. Status: proposal.
- **Effort**: medium.
- **Note**: keep excluding `(aN)+` / `-(aN)` post/decrement operands
(dropping the read would break the pointer's advance).
- **Done**: new `parseFrameSlot` helper accepts all emitted forms (`8(a5)`,
`-2(a5)`, `(-8,a5)`, `(a5)`) and backs both the widened store-reload guard
and `parseLeaBase` (whose old `frameSlotPattern` only matched `(-d,a5)`,
missing every real positive/unsigned slot). Store-reload parsing switched
from naive comma-split to paren-aware `splitOperands` (identical for plain
operands; previously frame operands misparsed and silently never matched).
`(aN)+`/`-(aN)`, `$hex` and mismatched offsets/sizes stay excluded.
- **Measured** (frame half disabled vs enabled): 5 conversions, all in maze
(`move.w d4,-8(a5)` / `move.w -8(a5),d0` -> `move.w d4,d0`, etc.),
maze -12B; textelite/gfxdemo/tictactoe unchanged (zero consecutive
frame store-reload pairs there - stores and reloads never sit adjacent).
## Tier 3 - Instruction selection at lowering (days-weeks)
@@ -252,6 +263,30 @@ effort. Status: proposal.
call boundaries (when callee is known and small).
- **Effort**: high. Defer.
### 4.5 Eliminate p8_regfile / p8_fregfile entirely
- End state after 4.1/4.2 should be near-zero regfile traffic (today already 3
mentions each in textelite/maze: one variable plus the label itself). This
item removes the section, not just the traffic: stop emitting the
`p8_regfile` / `p8_fregfile` BSS labels (`AsmGen.kt` `emitBssVars` tail)
when nothing references them.
- **Where**: `AsmGen.kt` (emission + `resolveRegFileAddress` fallback),
`M68kCodeGenerator.kt` (spill-slot path), `VregRenumber.kt` (bails when the
regfile layout is observed).
- **Measure first**: enumerate remaining references after 4.1/4.2 by cause -
unallocated vregs (empty allocator map), `%option noframe` subs (cannot take
frame slots today), raw `%asm` textual refs (`inlineAsmMayReadRegisters`
can only see the regfile symbols textually), float spills.
- **Plan**: route unallocated vregs to frame slots (or keep the noframe error
when no frame is possible); emit the BSS labels conditionally - only when
codegen fallback or a raw-`%asm` textual scan still references them, so
hand-written library code keeps assembling; apply the same conditional to
`p8_fregfile`; revisit the `VregRenumber` bail-out once the layout can be
empty.
- **Benefit**: smaller BSS, no global mutable spill state (reentrant-safe),
cleaner listings; the assembler catches any missed reference as an
undefined symbol.
- **Effort**: medium, depends on 4.1/4.2.
## Tier 5 - Bigger structural work (months)
### 5.1 Better D0 reload cache