li one, 1
li f, fib
li two, 2
li sp, 0
li zero 0
read n
li cont, write-result
fib:
;; computes f(n) into return and jumps to cont, leaving sp as it found it,
;; without any guarantee what will be in the n register afterwards
slt test, n, two
jeqz test, main
add return n zero
j cont
main-label:
st n, sp
add sp sp one
sub n n one
st cont sp
add sp sp one
li cont fbranch
j f
fbranch:
sub sp sp one
ld cont sp
sub sp sp one
ld n sp
sub n n two
st return sp
add sp sp one
st cont sp
add sp sp one
li cont adding
j f
adding:
;; at this point, return contains f(n-2) and on top of the stack we
;; have the continuation and under that the value of f(n-1)
write-result:
write return
halt