Software - 65816 - Relocatable code using BRL and PER

Relative JMP abs

A BRL is like JMP abs that uses relative instead of absolute addressing. However, BRL takes 4 cycles, whereas JMP abs takes 3 cycles.

Relative JSR abs

The equivalent of JSR SUBROUTINE is:

;
         PER CONTINUE-1
         BRL SUBROUTINE
CONTINUE

If the address of the BRL is close enough to SUBROUTINE, the BRL can be replaced with BRA.

Relative JSL

The equivalent of JSL SUBROUTINE is:

;
         PHK
         PER CONTINUE-1
         BRL SUBROUTINE
CONTINUE

Again, if the address of the BRL is close enough to SUBROUTINE, the BRL can be replaced with BRA.

Relative data

Example 1: The equivalent of

;
      PHX
      ASL
      TAX
      LDA TABLE,X
      PLX
      RTS
TABLE DW 1,2,4,8
      DW $10,$20,$40,$80
      DW $100,$200,$400,$800
      DW $1000,$2000,$4000,$8000

is:

;
      PHY
      ASL
      TAY
      PHD
      PER TABLE
      LDA (1,S),Y
      PLD         ; discard the value pushed by PER
      PLD
      PLY
      RTS
TABLE DW 1,2,4,8
      DW $10,$20,$40,$80
      DW $100,$200,$400,$800
      DW $1000,$2000,$4000,$8000

PLD is useful in that it always pulls a two byte value, and unlike PLY, does not depend on the value of the x flag. (Likewise PLA depends on the value of the m flag.) However, to preserve the original value of the D register, the PER to (first) PLD sequence is wrapped in a PHD-PLD pair.

The code above assumes that the data bank register is not the same as the program bank register. If that is not the case, the following can be used:

;
      PHB
      PHK
      PLB
      PHY
      ASL
      TAY
      PER TABLE
      LDA (1,S),Y
      PLB         ; discard the value pushed by the PER
      PLB
      PLY
      PLB
      RTS
TABLE DW 1,2,4,8
      DW $10,$20,$40,$80
      DW $100,$200,$400,$800
      DW $1000,$2000,$4000,$8000

Example 2: The equivalent of:

;
     PHX
     LDX #0
LOOP LDA TEXT,X
     JSR OUTPUT_CHAR
     INX
     CPX #TEND-TEXT
     BCC LOOP
     PLX
     RTS
TEXT DB  "Hello world"
TEND

is:

;
     PHB
     PHK
     PLB
     PHY
     LDY #0
     PER TEXT
LOOP LDA (1,S),Y
     PER NEXT-1
     BRL OUTPUT_CHAR
NEXT INY
     CPY #TEND-TEXT
     BCC LOOP
     PLB      ; discard the value pushed by the PER
     PLB
     PLY
     PLB
     RTS
TEXT DB  "Hello world"
TEND
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License