In a stack architecture, machine registers are organized as a stack. Arithmetic and logical instructions pop two source operands from the stack, perform the operation, and push the result back onto the stack. These operations do not need any code to specify the operands.
For memory access, a push instuction is used to move data from memory to the new stack top, and a pop instruction moves the stack top to memory and then removes the stack top. These instructions require coding for the memory operand.
Stack architectures for hardware have had little success, but stack architectures for virtual machines have been and still are popular. The p-machine was a virtual machine that made porting Pascal code easy across a variety of 8-bit microprocessors. The Java Virtual Machine is a modern example of a stack architecture that is widely used today.
A = B*(C + D)
| Instruction | Code Size | Data | |
|---|---|---|---|
| push | C | 3 (1 + 2) | 4 |
| push | D | 3 (1 + 2) | 4 |
| add | 1 | 0 | |
| push | B | 3 (1 + 2) | 4 |
| mul | 1 | 0 | |
| pop | A | 3 (1 + 2) | 4 |
| Total | 14 | 16 | |