Exercise 3: Why EXX Beats Manual PHA/PLA for Interrupt Entry/Exit — Possible Solution ==================================================================== WHAT THE 6502 HANDLER MUST DO ------------------------------ Per this chapter's own explanation, a 6502 interrupt handler that needs to use any register for its own work first has to protect whatever the interrupted program had stored there — using PHA to push the accumulator, and (since X and Y have no native push instruction of their own) transferring X or Y into A first before pushing, per cpu8bit1-3's own TXS-style register-transfer pattern. Each of these is a SEPARATE instruction, executed individually, each costing its own real cycles — and the same set of operations has to be reversed (PLA, transferring back into X/Y) before the handler returns, costing the same overhead again on the way out. WHAT THE Z80 HANDLER DOES INSTEAD ------------------------------ Per cpu8bit1-6's own explanation, EXX swaps the ENTIRE BC/DE/HL group with their shadow counterparts in a single instruction. A Z80 interrupt handler needing registers for its own work can execute one EXX at the very start, immediately gaining a completely separate, already-available set of BC/DE/HL that the interrupted program was never using in the first place — nothing about the main program's own register values needs to be touched, saved, or restored at all. A single EXX at the end restores the original set before returning. WHY THIS IS GENUINELY FASTER ------------------------------ The comparison is: the 6502 needs one separate PUSH-style instruction PER REGISTER it wants to protect, on entry, and the mirror-image POP- style instruction per register on exit — the total cost scales with how many registers the handler actually needs. The Z80's EXX handles ALL of BC/DE/HL (three full registers' worth of protection) in exactly one instruction on entry, and one instruction on exit, regardless of how many of those three registers the handler actually ends up using. The more registers a handler needs, the bigger this gap becomes: a 6502 handler needing three registers protected pays for three separate push instructions and three separate pop instructions, while a Z80 handler needing the same protection pays for exactly one EXX each way, covering all three at once. WHY THIS WORKS AS AN ANSWER ------------------------------ It contrasts the 6502's per-register manual save/restore against the Z80's single-instruction whole-group swap, and explains specifically why the gap between the two approaches gets larger the more registers a given handler actually needs — not just that EXX is "one instruction" in the abstract.