Stack

From C64-Wiki
Jump to navigationJump to search

In the Commodore 64, the Stack is a 256-byte (1 page) section of fixed memory located from $0100 to $01FF in RAM. The stack is a Last In First Out (LIFO) data structure used directly by the 6502/6510 processor to store and retrieve processor words (bytes). The memory area works in tandem with an 8-bit register in the processor called the Stack Pointer. The stack pointer (SP) always points to the next available location on the stack. As with many modern computers, the stack in the Commodore 64 "grows" downward. That is, the first entry in the stack is $01FF and the last entry is $0100. When the stack is empty SP = $FF.

Two operations are possible with the Commodore 64 stack. They are Push and Pop. When a word/byte is "pushed" onto the stack, its value is stored at the memory location addressed by $0100+SP and SP is decremented. When a value is "popped" off the stack, SP is incremented and the value is read from $0100+SP. The stack is said to overflow if the Stack Pointer is decremented from a value of $00 to a value of $FF, meaning that the stack has run out of space. Similarly, the stack is said to underflow if the value of SP is incremented from $FF to $00.

Several operations and conditions in the Commodore 64 make use of the stack and the Stack Pointer. The most basic use of the Stack Pointer is storing (pushing) the "return address" to be used (popped) when a subroutine or interrupt handler "returns" the Instruction Pointer (IP) to the location prior to the subroutine call or interrupt.

For example, when an interrupt signal is received, the processor completes the current instruction and then "pushes" two things onto the stack. First, the processor pushes the memory address of the next instruction onto the stack (using two stack locations because memory addresses are 16 bits long). Then the processor pushes the Status Register (8 bits) onto the stack. Finally the processor jumps to the interrupt vector for the appropriate type of interrupt.

When the interrupt handler finishes, it executes an RTI instruction. RTI pops the Status Register from the stack and the pops the Instruction Pointer (IP) from the stack to restore execution to the next instruction where the processor was when the interrupt occurred.

Similarly, when a subroutine is called using the JSR instruction, the location of the instruction following JSR is pushed onto the stack. When the subroutine ends and executes an RTS instruction, the Instruction Pointer (IP) is popped from the stack so execution resumes where the JSR instruction left off.

The PHA and PLA instructions allow pushing the value in the Accumulator onto and popping the Accumulator off of the stack, respectively. In the same way, PHP and PLP allow pushing the processor's Status Register onto and popping the Status Register off of the stack, respectively.