読者です 読者をやめる 読者になる 読者になる

(wat-aro)

無職から有職者にランクアップしました

SICP 問題 5.06

scheme SICP

Fibonacci計算機の余分なsaveとrestoreを取り除く

  afterfib-n-1
    (restore n)
    (restore continue)                  ;ここでcontinueをrestoreしているのに
    (assign n (op -) (reg n) (const 2))
    (save continue)                     ;ここでそのままcontinueをsaveして
    (assign continue (label afterfib-n-2)) ;ここでcontinueを上書きしている.
    (save val)
    (goto (label fib-loop))

余分なところを削除すると

  afterfib-n-1
    (restore n)
    (assign n (op -) (reg n) (const 2))
    (assign continue (label afterfib-n-2))
    (save val)
    (goto (label fib-loop))

こうなる. 全文は以下の通り.

(controller
    (assign continue (label fib-done))
  fib-loop
    (test (op <) (reg n) (const 2))
    (branch (label immediate-answer))
    (save continue)
    (assign continue (label afterfib-n-1))
    (save n)
    (assign n (op -) (reg n) (const 1))
    (goto (label fib-loop))
  afterfib-n-1
    (restore n)
    (assign n (op -) (reg n) (const 2))
    (assign continue (label afterfib-n-2))
    (save val)
    (goto (label fib-loop))
  afterfib-n-2
    (assign n (reg val))
    (restore val)
    (restore continue)
    (assign val
            (op +) (reg val) (reg n))
    (goto (reg continue))
  immediate-answer
    (assign val (reg n))
    (goto (reg continue))
    fib-done)