A Stack CPU is a fascinating piece of hardware that operates on a unique principle. It primarily comprises of three essential components:
-
Memory (MEM) - This is where the instructions for operations are stored.
-
Data Stack (DS) - A stack-based data structure used for storing intermediate results.
-
Return Stack (RS) - Another stack-based structure utilized for storing return addresses.
The stack CPU operates based on the instructions stored in the Memory, starting from the instruction pointed to by the Program Counter (PC). A single instruction is made up of two parts:
-
The opcode - This indicates the type of instruction. The subsequent memory location will serve as the operand, which may or may not be present.
-
The operand - Depending on the instruction, the operation may require zero to two operands.
Once an instruction execution is complete, the PC advances to point to the next instruction, and the process continues by executing that instruction. This cycle repeats continuously, making the CPU work.
You can access the code for both the 8-bit and 16-bit versions on their respective branches
Symbol | Description |
---|---|
LIT | ds.push(oper) pc = pc + 2 |
LOAD (@) | addr = ds.pop() ds.push(mem[addr]) pc = pc + 1 |
STORE (!) | addr = ds.pop() mem[addr] = ds.pop() pc = pc + 1 |
DROP | ds.pop() pc = pc + 1 |
DUP | ds.push(ds.peek()) pc = pc + 1 |
OVER | ds.push(ds.nextToPeek()) pc = pc + 1 |
SWAP | tmpl = ds.pop() tmp2 = ds.pop() ds.push(tmpl) ds.push(tmp2) pc = pc + 1 |
ADD (+) SUB (-) AND OR XOR |
tmp2 = ds.pop() tmpl = ds.pop() ds.push(tmpl op tmp2) pc = pc + 1 |
IF | tmp = ds.pop() if tmp = 0 then pc = oper else pc = pc + 2 |
CALL | pc = oper rs.push(pc + 2) |
EXIT | pc = rs.pop() |
HALT | stop cpu |
>R | move value from the DS to the RS |
R> | move value from the RS to the DS |
Check out these simulations in action:
16 bit - stack-cpu-16-bit.netlify.app
8 bit - stack-cpu-8-bit.netlify.app
Here is an example of a multiplication program that is used in the preview MUL.txt
The original version can be found in Course 2301274 Computer Systems