6

I'm writing a Z80 emulator in Swift for Mac OS and I have got as far as implementing the 16 bit pop instruction. The documentation I have found (i.e. The Z80 CPU User manual UM008011-0816 and also this document about undocumented Z80 instructions) says that the flags are not affected by pop dd (where dd is a 16 byte register).

However, one of the pop instructions is pop af (opcode 0xf1) where f in af is the flags register. Does the Z80 toss the low byte or does it set the flags in apparent contradiction to the documentation.

1
  • 4
    When it says that it doesn't affect the flags, it means that it doesn't affect flags incidentally in the way that many other instructions do, not that it won't write to the flags register if that's what it's told to.
    – hobbs
    Apr 16, 2017 at 5:42

1 Answer 1

11

One of the main purposes of the POP AF and the EX AF,AF' instructions actually is to be able to move the flags to a safe place and restore them afterwards. So, opposite to what you have read, POP AF actually does affect the flags (but only if the destination register is AF). Apparently, the writers assumed this as a given.

Here is an article on how Z80 instructions affect the flags.

7
  • Thanks. I'd sort of come to the same conclusion especially as I noticed that the official manual doesn't even mention that sp changes as a result of the pop.
    – JeremyP
    Apr 15, 2017 at 20:53
  • 1
    Also note that the flags register holds a full 8 bits. So a sequence like "PUSH BC; POP AF; PUSH AF; POP BC" will not alter BC even though 2 bits of the flag register are officially undefined. Apr 16, 2017 at 19:22
  • @GeorgePhillips Oh well, yes. POPing single bits would be a bit "extravagant"
    – tofro
    Apr 17, 2017 at 22:23
  • 2
    @tofro What I mean is that you could reasonably think that bit 3 and bit 5 of the flag register are always zero or one or undefined. That would cost the hardware nothing as it simply wouldn't have storage for those bits. Thus passing data through F register might result in bit 3 and bit 5 being changed. Apr 17, 2017 at 23:07
  • @GeorgePhillips Ah, geddid. Yes, that's true. You shouldn't use AF to save some other register from the stack.
    – tofro
    Apr 18, 2017 at 6:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .