Extending Ben Eater’s CPU with Stack Mechanism and Function Call Support

Why add a stack and function call support?

In C-like languages, function calls require:

  • Saving the return address
  • Storing local variables and parameters
  • Executing CALL function and RET (return)

To support this, the CPU must have:

  • A Stack Pointer (SP) register
  • A reserved memory area used as the stack
  • New instructions: CALL, RET, PUSH, POP

New Instructions (Stack & Call Support)

OpcodeMnemonicDescription
0x60CALL addrPush return address to stack, then jump to addr
0x61RETPop return address from stack and jump back
0x62PUSH APush the contents of register A onto the stack
0x63POP APop the top of the stack into register A
0x64PUSH BPush the contents of register B onto the stack
0x65POP BPop the top of the stack into register B

Hardware Requirements

  • Add a new SP (Stack Pointer) register, e.g., using a 74LS173 or 74LS161
  • Stack grows downward, from 0xFF to 0xF0
  • Reserve upper memory for stack (e.g., 0xF0–0xFF)

Example: Simple Function Call

C-like logic:

cCopyEditvoid sub() {
    mem[0x20] = 42;
}

int main() {
    sub();
    return 0;
}

Corresponding DCPU-8-like code:

assemblyCopyEdit00: 60 08     ; CALL 0x08 (subroutine)
02: FF        ; HALT

; subroutine at 0x08
08: 10 2A     ; Load A with immediate 0x2A (e.g., via workaround or memory preset)
0A: 20 20     ; STORE A, [0x20]
0C: 61        ; RET

Benefits of Adding Stack + CALL/RET

  • Enables modular programming and code reuse
  • Simulates local variables and nested calls
  • Lays foundation for recursive functions and future C support