The Stack is a reserved area of memory for keeping temporary data. The Stack is used when the Branch/Jump to Subroutine instructions are used to keep the return address for the next instruction in the main programme. The Return from Subroutine (RTS) instruction gets this value from the stack and returns to that address. The same thing happens when a Software Interrupt (SWI) instruction or hardware interrupt occurs. The Return from Interrupt (RTI) instruction is used to return from an interrupt call.
The Stack is a Last In First Out (LIFO) memory. Data is placed onto the Stack with a Push instruction and removed with a Pull instruction. The Stack memory is maintained by the Stack Pointer (SP) register. The Stack Pointer (SP) is used to point at the next available location in the Stack. Pushing data onto the Stack decrements the SP and Pulling data from the Stack increments the SP.
When a return address is Pushed onto the stack the the High order 8-bit Byte is placed in location SP-1 and the Low 8-bit Byte is placed in location SP-2. The SP is then decremented by 2. The reverse sequence occurs when data is Pulled from the Stack. When the return address is Pulled from the stack the High order 8-bit Byte is obtained in location SP-1 and the Low 8-bit Byte is obtained in location SP-2. The SP is then incremented by 2.
The stack uses LIFO (Last In First Out) algorithm, this means that if we Push
registers or data one by one onto the stack as 1, 2, 3, 4, 5 then the first value that we will get on
Pull will be 5, then 4, 3, 2, and
finally 1.