Subroutines

Calling subroutines

The JSR & RTS instructions allows for subroutines to be implemented. The work by utilising 2 bytes on the stack consisting of the address before the next instruction to execute when the subroutine returns - not the actual address of that instruction.

On the 16-bit 65816 there are the JSL & RTL instructions. These use 3 bytes on the stack. The extra byte is the return bank address. Like RTS the address on the stack is the address before the next instruction not the actual instruction

For Interrupt routines there's the RTI instruction. That instruction is on the Interrupt page.

JSR - Jump to Subroutine

Transfer control to a subroutine, pushing the return address onto the stack. The 16-bit address placed on the stack is the address of the 3rd byte of the instruction, not the address of the next instruction.

Subroutines called by JSR must return using the RTS instruction.

Some assemblers recognise JSR as an alternate to the 65816 JSL instruction where if the address is greater than &FFFF then the 24 bit JSL instruction is used instead.

RTS - Return from Subroutine

Returns from a subroutine called by JSR. It pulls the 16-bit program counter from the stack, incrementing it by one so that the next instruction is the one immediately after the calling JSR instruction.

JSL - Jump to Subroutine Long

Transfer control to a subroutine, pushing the return address onto the stack. The 24-bit address placed on the stack is the address of the 4th byte of the instruction, not the address of the next instruction.

Subroutines called by JSL must return using the RTL instruction.

RTL - Return from Subroutine Long

Returns from a subroutine called by JSL. It pulls the 24-bit program counter from the stack, incrementing it by one so that the next instruction is the one immediately after the calling JSL instruction.

Flags Affected
None.
Instructions
SyntaxOpcode Available on: # of # of Addressing Mode
(hex) 6502 65C02 65816 bytes cycles
JSL long22 x 4 8 Absolute Long
JSR addr20 x x x 3 6 Absolute
JSR (addr,X)FC x 3 8 Absolute Indexed Indirect
RTL 6B x 1 6 Implied
RTS 60 x x x 1 6 Implied

Last modified November 5, 2021: Add instruction categories (6b74ff9)