TAOCP 1.4.3.2 Exercise 1

We are asked to modify the trace routine so that it restores register J upon leaving, assuming $rJ \neq 0$.

Section 1.4.3.2: Trace Routines

Exercise 1. [22] Modify the trace routine of the text so that it restores register J when leaving. (You may assume that register J is not zero.)

Verified: no
Solve time: -


Solution

We are asked to modify the trace routine so that it restores register J upon leaving, assuming $rJ \neq 0$. By examining the routine in Section 1.4.3.2, we see that JREG holds the simulated contents of the J-register. When the traced program executes a jump, the current value of rJ is stored in JREG(0:2) (line 45). Upon normal execution, rJ is never explicitly restored before leaving (line 49 LEAVEX JMP *), which violates the requirement of the exercise.

We introduce a restoration step immediately before leaving the trace routine. We need to move the value stored in JREG back into the actual J-register rJ. MIX provides the ENTA instruction to load a value into rA and the STA instruction to store rA into memory. To restore rJ, we can exploit ENTA with indirect addressing for rJ. A minimal solution is to add a line before LEAVEX:

LEAVEX  LDA  JREG(0:2)   rA <- saved J
        ENTA *           rJ <- rA
        JMP  *           leave

We now integrate this into the trace routine. The modified leaving sequence becomes:

48 LEAVE   LDA  AREG        Restore register A.
49 LEAVEX  LDA  JREG(0:2)   Restore register J.
50          ENTA *          
51          JMP  *
50 AREG    CON  0           Simulated rA contents

Step justification:

  1. LDA JREG(0:2) loads the saved contents of rJ into rA. This is necessary because ENTA transfers the value of rA into rJ.
  2. ENTA * sets rJ to the saved value. This restores rJ to the value it had before tracing began.
  3. JMP * leaves the trace routine and resumes the original program.

This modification preserves all invariants of the original routine: rA is restored, no other registers are affected, and the trace routine remains minimal in space. Every register, including rJ, now has its proper contents when tracing ends.

This completes the proof.

Final modified sequence for leaving the trace routine:

48 LEAVE   LDA  AREG
49 LEAVEX  LDA  JREG(0:2)
50          ENTA *
51          JMP  *
50 AREG    CON  0