rgbds icon indicating copy to clipboard operation
rgbds copied to clipboard

[Feature request] `ALIGNOF` and `OFFSETOF` functions

Open Rangi42 opened this issue 3 years ago • 3 comments

These would be useful for both sections and labels.

For a section named "S", ALIGNOF("S") and OFFSETOF("S") would just return the values specified by its ALIGNment, or 0s if it's unaligned. Note that OFFSETOF("S") would be equal to STARTOF("S") & ((1 << ALIGNOF("S")) - 1).

For a label L within a section "S", ALIGNOF(L) would be ALIGNOF("S"), and OFFSETOF(L) would be L & ((1 << ALIGNOF(L)) - 1).

Rangi42 avatar Dec 29 '21 16:12 Rangi42

What makes these useful is that they'd be known at assembly time even if the exact address of a section or label is only determined at link time. For example, you want to align two successive tables in the middle of an aligned section:

SECTION "S", WRAMX, ALIGN[8]
    ds various stuff
    ds $24 ; found this padding value manually
MyTable:: ds $40
assert (MyTable & $ff) == 0
    ds some more stuff
    ds $5 ; found this padding value manually
MyTable2:: ds $40
assert (MyTable2 & $ff) == 0

This could be accomplished without needing manual padding, even though "S" isn't fixed to an exact starting address:

SECTION "S", WRAMX, ALIGN[8]
    ds various stuff
    ds ($100 - OFFSETOF(@)) & $ff
MyTable:: ds $40
assert (MyTable & $ff) == 0
    ds some more stuff
    ds ($100 - OFFSETOF(@)) & $ff
MyTable2:: ds $40
assert (MyTable2 & $ff) == 0

Rangi42 avatar Dec 29 '21 16:12 Rangi42

Or a case where ALIGNOF is useful:

MACRO realign
    ds ((1 << ALIGNOF(@)) - OFFSETOF(@)) & ((1 << ALIGNOF(@)) - 1)
ENDM

SECTION "S", WRAMX, ALIGN[8, +$13]
    ds various stuff
    realign
    assert OFFSETOF(@) == OFFSETOF("S")

Rangi42 avatar Dec 29 '21 16:12 Rangi42

The docs should make it clear that only the low aligned bits of OFFSETOF are significant. If ALIGNOF(X) is 6 and OFFSETOF(X) is $1d, then that's effectively $xxxx_xxxx_xx01_1101. It doesn't mean LOW(X) == $1d; it means X & ((1 << 6) - 1) == $1d. So X could be $c09d.

Rangi42 avatar Dec 29 '21 16:12 Rangi42

Since the low-aligned bits of addresses are now asm-time constant, ALIGNOF and OFFSET of are not necessary.

SECTION "S", ROMX, ALIGN[8]
	ds ...various stuff...
	ds (1 << 8 - (@ & (1 << 8 - 1)) % (1 << 8)
	align 8 ; this will not fail

Rangi42 avatar Sep 28 '22 19:09 Rangi42