Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Game Boy: What is the purpose of instructions that don't modify anything (e.g. AND A)?

I've been working on a Game Boy emulator, and I've noticed that there are certain opcodes that exist that would never change any values, such as LD A, A, LD B, B, etc. and also AND A. The first ones obviously don't change anything as they load the value of registers into the same registers, and since the AND is being compared with the A register, AND A will always return A. Is there any purpose for these operations, or are the essentially the same as NOP after each cycle?

like image 941
Zach Brantmeier Avatar asked Oct 17 '14 02:10

Zach Brantmeier


3 Answers

As Jeffrey Bosboom and Hans Passant pointed out on their comments, the reason is simplicity. More specifically hardware simplicity.

LD r,r' instructions copy the content of source register (r') to destination register (r). LD r,r' opcodes follow this form:

        -------------------------------
BIT    | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
        -------------------------------
OPCODE | 0 | 1 |     r     |     r'    |
        -------------------------------

Destination and source registers can assume these values:

 -----------
| BIT | REG |
 -----------
| 111 |  A  |
 -----------
| 000 |  B  |
 -----------
| 001 |  C  |
 -----------
| 010 |  D  |
 -----------
| 011 |  E  |
 -----------
| 100 |  H  |
 -----------
| 101 |  L  |
 -----------

In order to implement these instructions in hardware we just need a multiplexer that receives bits 0-2 to select the source register and another multiplexer that receives bits 3-5 to select the destination register.

If you want to verify if bits 0-2 and bits 3-5 are pointing to the same register you would have to add more logic to the CPU. And as we all know, ressources were more limited in the 80's :P

Please note that loading instructions such as LD A,A, LD B,B, LD C,C, LD D,D, LD E,E, LD H,H, and LD L,L behave like NOP. However AND A and OR A DO NOT behave like NOP, since they affect the flag register, and their execution might change the internal machine state.

like image 189
GabrielOshiro Avatar answered Oct 17 '22 20:10

GabrielOshiro


Instructions like LD A,A and AND A may appear to be NOPs but they might also change the processor flags and be used for testing the value of a register.

Be sure to check the instruction set documentation carefully for such side effects.

like image 34
HBP Avatar answered Oct 17 '22 22:10

HBP


There is actually purpose in AND A (as well as OR A) instruction -- it sets flag Z when A is zero and clears otherwise. So both AND A and OR A are frequently used for this purpose.

like image 3
lvd Avatar answered Oct 17 '22 21:10

lvd