-
Notifications
You must be signed in to change notification settings - Fork 0
/
gameboy.lit
3213 lines (2705 loc) · 95.6 KB
/
gameboy.lit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Gameboy Overview
The Gameboy hardware is made up of several parts:
- A Z80-like CPU (Sharp LR35902)
- A graphics unit capable of hardware background scrolling and sprite blitting
- A 160x144 pixel LCD, capable of 3 gray shades
- A simple sound generator with 3 channels and stereo output
- 4-way directional pad, 4 push buttons (A, B, start, select)
The emulator is implemented as a library. It does not provide any user
interface, user input, or main loop. This is expected to be implemented in
programs which link against the library. The library is designed with no global
state; this allows multiple Gameboy systems to be emulated in the same process,
and makes the code easier to understand.
To this end a struct is defined which will contain all the state of the emulator:
<< gameboy state >>=
struct Gameboy
{
#ifndef NDEBUG
uint32_t (*trace_fn)(struct Gameboy* gb, struct gameboy_tp* tp);
#endif
<< state >>
};
[TOC]
# The CPU
The CPU has eight 8-bit core registers:
<< cpu registers >>=
uint8_t A, F;
uint8_t B, C;
uint8_t D, E;
uint8_t H, L;
`A` is the accumulator register and many instructions only support operating on
this register. Some instructions use pairs of registers to provide 16-bit
operands; the possible pairs as `BC`, `DE`, and `HL`.
The flags register `F` stores the additional state about the results of
(primarily) arithmetic operations. It is a bitmask of four values:
* `0x80` - `Z` - result was zero
* `0x40` - `S` - instruction is a subtraction
* `0x20` - `H` - a bit was carried between the low and high nibbles (e.g. `0x0F + 0x01 = 0x10`)
* `0x10` - `C` - a bit was carried out of the low byte of the result (e.g. `0xF0 + 0x11 = 0x01`)
There is a 16-bit stack pointer register used for stack operations. Few
instructions allow direct access to `SP`.
<< cpu registers >>=
uint16_t SP;
The CPU executes instructions from the current address in the program counter,
`PC`, register. This register is not directly accessable.
<< cpu registers >>=
uint16_t PC;
<< state >>=
struct GameboyCPU {
<< cpu registers >>
} cpu;
# Clocking
The clock runs at ~4.19MHZ, however most operations are measured in machine
cycles, which are 4 clock cycles (~1.05MHz). The shortest CPU operation is 1
machine cycle - this is the length of time to execute a `nop` instruction or
access a single byte of memory.
Each part of the emulator needs to perform work on every machine cycle.
<< clock functions >>=
void clock_increment(struct Gameboy* gb)
{
<< per machine cycle updates >>
}
A cycle count is maintained for external use only.
<< state >>=
uint64_t TotalCycles;
<< reset >>=
gb->TotalCycles = 0;
<< per machine cycle updates >>=
gb->TotalCycles += 4;
### Divider and Timer Registers
The Gameboy keeps a counter which increments on every clock cycle. This counter
is exposed in two ways: the divider and the timer registers. The divider
register increments at a fixed frequency (1 per 256 clock cycles = 1 per 64
machine cycles). The timer register increments at a configurable frequency and
can provide an interrupt when it overflows.
<< state >>=
struct {
uint16_t CycleCount;
bool TimerOverflow;
bool TimerLoading;
} clock;
<< reset >>=
gb->clock.CycleCount = 0;
gb->clock.TimerOverflow = false;
gb->clock.TimerLoading = false;
<a name="regff04"></a>The divider and timer actually share a single underlying
16-bit cycle counter which is incremented on each clock cycle. The top 8 bits of
this counter is exposed directly as the divider register at `0xFF04`. Writing
any value to the divider resets the internal 16-bit counter to zero.
<a name="regff05"></a><a name="regff06"></a><a name="regff07"></a>The timer
counter register increments at a rate configured by the timer control register.
When it overflows an interrupt is set and it is reloaded from the timer modulo
register. When to increment the timer counter is determined by a falling edge
detector, the input of which is a bit from the 16-bit cycle counter. The
specific bit is selected depending on the speed selected in bits `1:0` of the
timer control register.
<< clock functions >>=
static bool clock_getTimerBit(uint8_t control, uint16_t cycles)
{
switch(control & 0x03) { /* Timer clock select */
case 0: /* 4.096 KHz (1024 cycles) */
return cycles & (1u << 9);
case 1: /* 262.144 KHz (16 cycles) */
return cycles & (1u << 3);
case 2: /* 65.536 KHz (64 cycles) */
return cycles & (1u << 5);
case 3: /* 16.384 KHz (256 cycles) */
return cycles & (1u << 7);
}
assert(0);
}
If the timer counter register overflows when it is incremented an interrupt is
set and its value is loaded from the timer modulo register, after a delay of one
machine cycle. During the delay cycle the timer counter reads zero, but writes
to the counter will cancel the interrupt and the load from the modulo register.
During the machine cycle on which the modulo value is being loaded explicit
writes to the counter register will be ignored, but writes to the modulo
register will be respected (and that value will be loaded into the counter
register).
<< clock functions >>=
static void clock_timerIncrement(struct Gameboy* gb)
{
uint8_t timer = gb->mem.IO[IO_TimerCounter];
if(timer == 0xFF) {
gb->clock.TimerOverflow = true;
}
gb->mem.IO[IO_TimerCounter] = timer + 1;
}
<< per machine cycle updates >>=
gb->clock.TimerLoading = false;
if(gb->clock.TimerOverflow) {
/* Delayed overflow effects */
gb->mem.IO[IO_InterruptFlag] |= Interrupt_TIMA;
gb->clock.TimerOverflow = false;
/* In the next machine cycle the modulo is being loaded */
gb->mem.IO[IO_TimerCounter] = gb->mem.IO[IO_TimerModulo];
gb->clock.TimerLoading = true;
}
<< mmu write special cases >>=
case IO_TimerCounter:
/* Writes to the timer counter whilst it is loading are ignored */
if(!gb->clock.TimerLoading) {
gb->mem.IO[IO_TimerCounter] = value;
/* Writing to timer counter suppresses any pending overflow effects */
gb->clock.TimerOverflow = false;
}
break;
case IO_TimerModulo:
gb->mem.IO[IO_TimerModulo] = value;
/* Whilst the modulo is being loaded any writes are effective immediately */
if(gb->clock.TimerLoading) {
gb->mem.IO[IO_TimerCounter] = value;
}
Changing the speed of the timer or disabling it (by writing to the timer control
register) can change the input to the falling edge detector used to increment
the timer counter. If this produces a falling edge then there will be an "extra"
incremement of the counter.
<< clock functions >>=
static void clock_updateTimerControl(struct Gameboy* gb, uint8_t val)
{
uint8_t old = gb->mem.IO[IO_TimerControl];
gb->mem.IO[IO_TimerControl] = val;
/* When disabled the bit to the falling edge detector is zero */
bool const oldBit = (old & 0x04) && clock_getTimerBit(old, gb->clock.CycleCount);
bool const newBit = (val & 0x04) && clock_getTimerBit(val, gb->clock.CycleCount);
/* Check for falling edge */
if(oldBit && !newBit) {
clock_timerIncrement(gb);
}
}
<< mmu write special cases >>=
case IO_TimerControl:
clock_updateTimerControl(gb, value);
break;
When the underlying 16-bit cycle count changes (either when reset or when
incremented by the clock) this affects both the timer counter and the divider
register.
<< function declarations >>=
static void clock_countChange(struct Gameboy* gb, uint16_t new_value);
<< clock functions >>=
static void clock_countChange(struct Gameboy* gb, uint16_t new_value)
{
uint8_t tac = gb->mem.IO[IO_TimerControl];
if(tac & 0x04) { /* Timer enable */
if(!clock_getTimerBit(tac, new_value) && clock_getTimerBit(tac, gb->clock.CycleCount)) {
clock_timerIncrement(gb);
}
}
gb->clock.CycleCount = new_value;
gb->mem.IO[IO_Divider] = new_value >> 8u;
}
<< per machine cycle updates >>=
clock_countChange(gb, gb->clock.CycleCount + 4);
<< mmu write special cases >>=
case IO_Divider:
clock_countChange(gb, 0);
break;
# Interrupt handling
There are five interrupts. Each is assigned a bit in the interrupt control registers.
<< interrupt bits enum >>=
enum {
Interrupt_VBlank = 0x01,
Interrupt_LCDC = 0x02,
Interrupt_TIMA = 0x04,
Interrupt_Serial = 0x08,
Interrupt_Joypad = 0x10,
Interrupt_Mask = 0x1F,
};
<a name="regff0f"></a>
Interrupts are raised by setting in the appropriate bit in the interrupt flag
register (`0xFF0F`)
Typically this is done automatically by the Gameboy hardware, but software can
manually set (or clear) interrupts by writing to the interrupt flag register.
<a name="regffff"></a>
Each interrupt can be individually disabled by setting the appropriate bits in
the interrupt enable IO register (`0xFFFF`).
When an interrupt is disabled its service routine will not be called when it is
signalled; its bit will remain set in the interrupt flag register unless it is
manually cleared, and if the interrupt is re-enabled when its bit is set in the
interrupt flag register its service routine will be called.
In addition the CPU has an internal global interrupt enable flag which is
modified by the `ei`, `di`, and `reti` instructions.
<< cpu registers >>=
bool InterruptsEnabled;
The CPU services an interrupt by calling to a fixed address for each interrupt,
with interrupts disabled. An interrupt routine will typically return using the
`reti` instruction, which returns to the address on the top of the stack and
re-enables interrupts. Interrupts are serviced in order, from low bit to high
bit (`VBlank` to `Joypad`). The interrupt service routine table starts at
address `0x40` and provides 8 bytes per interrupt. When an interrupt is serviced
its bit is cleared from the interrupt flag register.
<< service highest priority interrupt >>=
// handle interrupts in priority order
for(unsigned int i = 0; i < 5; i += 1) {
uint8_t const bit = 1u << i;
if(irqs & bit) {
gb->cpu.InterruptsEnabled = false;
clock_increment(gb);
clock_increment(gb);
Call(gb, 0x40 + (i * 8));
iflag &= ~bit;
break;
}
}
gb->mem.IO[IO_InterruptFlag] = iflag;
When any enabled interrupt is raised it will bring the CPU out of halt mode to
service it, if required.
<< interrupt handler function >>=
void cpu_handleInterrupts(struct Gameboy* gb)
{
uint8_t iflag = gb->mem.IO[IO_InterruptFlag];
uint8_t irqs = (gb->mem.InterruptEnable & iflag & Interrupt_Mask);
if(irqs) {
gb->cpu.Halted = false;
if(gb->cpu.InterruptsEnabled) {
assert(!gb->cpu.InterruptEnablePending);
<< service highest priority interrupt >>
}
}
}
<< mmu write special cases >>=
case IO_InterruptFlag:
/* Top 5 bits of IF always read 1s */
gb->mem.IO[IO_InterruptFlag] = value | 0xE0;
break;
# CPU Emulation
<< cpu functions >>=
<< cpu helpers >>
<< interrupt handler function >>
<< cpu step >>
## Operand Types
Registers
* `$reg8` - one of the 8-bit registers `A`, `B`, `D`, `E`, `H`, `L`
* `$reg16` - one of the 16-bit register pairs `AF`, `DE`, `HL`
Immediate values directly follow the opcode in the instruction stream
* `imm8` - an 8-bit unsigned immediate operand
* `imm8i` - an 8-bit signed immediate operand
* `imm16` - a 16-bit immediate operand (little endian)
<< cpu helpers >>=
static inline uint8_t Imm8(struct Gameboy* gb)
{
gb->cpu.PC += 1;
return mmu_read(gb, gb->cpu.PC - 1);
}
static inline int8_t Imm8i(struct Gameboy* gb)
{
return (int8_t)Imm8(gb);
}
static inline uint16_t Imm16(struct Gameboy* gb)
{
uint8_t const lo = Imm8(gb);
uint8_t const hi = Imm8(gb);
return (hi << 8u) | lo;
}
Memory read/write is indicated by surrounding a operand description with
parenthesis, e.g. `(imm16)` refers to the data at memory address `imm16`.
Many instructions operate on a pair of registers as a single 16 bit value. There
are four possible pairings of the the Gameboy CPU registers: `AF`, `BC`, `DE`
and `HL`.
<< cpu helpers >>=
uint16_t ReadAF(struct Gameboy* gb) { return ((gb->cpu.A) << 8u) | (gb->cpu.F); }
uint16_t ReadBC(struct Gameboy* gb) { return ((gb->cpu.B) << 8u) | (gb->cpu.C); }
uint16_t ReadDE(struct Gameboy* gb) { return ((gb->cpu.D) << 8u) | (gb->cpu.E); }
uint16_t ReadHL(struct Gameboy* gb) { return ((gb->cpu.H) << 8u) | (gb->cpu.L); }
void WriteAF(struct Gameboy* gb, uint16_t af) { gb->cpu.A = (af >> 8u); gb->cpu.F = (af & 0xF0); }
void WriteBC(struct Gameboy* gb, uint16_t bc) { gb->cpu.B = (bc >> 8u); gb->cpu.C = (bc & 0xFF); }
void WriteDE(struct Gameboy* gb, uint16_t de) { gb->cpu.D = (de >> 8u); gb->cpu.E = (de & 0xFF); }
void WriteHL(struct Gameboy* gb, uint16_t hl) { gb->cpu.H = (hl >> 8u); gb->cpu.L = (hl & 0xFF); }
The flags register in the CPU contains four well-defined bits, and many
instructions read and/or write one or more of those bits.
<< cpu helpers >>=
void UpdateZ(struct Gameboy* gb, bool set) { if(set) { gb->cpu.F |= 0x80; } else { gb->cpu.F &= ~0x80; } }
void UpdateN(struct Gameboy* gb, bool set) { if(set) { gb->cpu.F |= 0x40; } else { gb->cpu.F &= ~0x40; } }
void UpdateH(struct Gameboy* gb, bool set) { if(set) { gb->cpu.F |= 0x20; } else { gb->cpu.F &= ~0x20; } }
void UpdateC(struct Gameboy* gb, bool set) { if(set) { gb->cpu.F |= 0x10; } else { gb->cpu.F &= ~0x10; } }
bool ReadZ(struct Gameboy* gb) { return gb->cpu.F & 0x80; }
bool ReadN(struct Gameboy* gb) { return gb->cpu.F & 0x40; }
bool ReadH(struct Gameboy* gb) { return gb->cpu.F & 0x20; }
bool ReadC(struct Gameboy* gb) { return gb->cpu.F & 0x10; }
void UpdateZNHC(struct Gameboy* gb, bool z, bool n, bool h, bool c)
{
UpdateZ(gb, z);
UpdateN(gb, n);
UpdateH(gb, h);
UpdateC(gb, c);
}
The CPU has instructions which push and pop 16-bit values from a stack, the top
of which is pointed to by the `SP` register. The stack grows towards address
zero as items and pushed onto it. The bytes within the 16-bit values are
arranged in little-endian order.
<< cpu helpers >>=
void Push16(struct Gameboy* gb, uint16_t val)
{
mmu_write(gb, gb->cpu.SP - 2, (uint8_t)(val));
mmu_write(gb, gb->cpu.SP - 1, (uint8_t)(val >> 8u));
gb->cpu.SP -= 2;
}
uint16_t Pop16(struct Gameboy* gb)
{
gb->cpu.SP += 2;
uint16_t val = mmu_read(gb, gb->cpu.SP - 2);
val |= mmu_read(gb, gb->cpu.SP - 1) << 8;
return val;
}
The main CPU loop executes a single instruction. Most of the implementation is a
large switch statement, with one case for each instruction encoding.
<< cpu step >>=
static uint8_t mmu_readDirect(struct Gameboy* gb, uint16_t addr);
void cpu_step(struct Gameboy* gb)
{
<< halt emulation >>
if(gb->cpu.InterruptEnablePending) {
gb->cpu.InterruptsEnabled = true;
gb->cpu.InterruptEnablePending = false;
}
uint8_t const opcode = Imm8(gb);
GBTRACE(gb, (&(struct gameboy_tp){ .point = GAMEBOY_TP_INSTR_START, .u = { .instr_start = { .opcode = opcode } } }));
<< halt bug emulation >>
switch(opcode) {
<< cpu instructions >>
default:
raise(SIGTRAP);
}
}
The number of cycles to execute an instruction is generally just the number of
cycles to read all the bytes of the instruction. For taken jumps there is an
additional 4 cycles, and 16bit arithmetic (e.g. adding two register pairs)
appears to take an extra 4 cycles.
## Load instructions (`ld`)
<a name="op_ldrr"></a>
### Register-to-register
A large number of instructions simply copy data from one register to another.
<< cpu instructions >>=
// ld $b, $reg8
case 0x40: gb->cpu.B = gb->cpu.B; break;
case 0x41: gb->cpu.B = gb->cpu.C; break;
case 0x42: gb->cpu.B = gb->cpu.D; break;
case 0x43: gb->cpu.B = gb->cpu.E; break;
case 0x44: gb->cpu.B = gb->cpu.H; break;
case 0x45: gb->cpu.B = gb->cpu.L; break;
case 0x47: gb->cpu.B = gb->cpu.A; break;
// ld $c, $reg8
case 0x48: gb->cpu.C = gb->cpu.B; break;
case 0x49: gb->cpu.C = gb->cpu.C; break;
case 0x4A: gb->cpu.C = gb->cpu.D; break;
case 0x4B: gb->cpu.C = gb->cpu.E; break;
case 0x4C: gb->cpu.C = gb->cpu.H; break;
case 0x4D: gb->cpu.C = gb->cpu.L; break;
case 0x4F: gb->cpu.C = gb->cpu.A; break;
// ld $d, $reg8
case 0x50: gb->cpu.D = gb->cpu.B; break;
case 0x51: gb->cpu.D = gb->cpu.C; break;
case 0x52: gb->cpu.D = gb->cpu.D; break;
case 0x53: gb->cpu.D = gb->cpu.E; break;
case 0x54: gb->cpu.D = gb->cpu.H; break;
case 0x55: gb->cpu.D = gb->cpu.L; break;
case 0x57: gb->cpu.D = gb->cpu.A; break;
// ld $e, $reg8
case 0x58: gb->cpu.E = gb->cpu.B; break;
case 0x59: gb->cpu.E = gb->cpu.C; break;
case 0x5A: gb->cpu.E = gb->cpu.D; break;
case 0x5B: gb->cpu.E = gb->cpu.E; break;
case 0x5C: gb->cpu.E = gb->cpu.H; break;
case 0x5D: gb->cpu.E = gb->cpu.L; break;
case 0x5F: gb->cpu.E = gb->cpu.A; break;
// ld $h, $reg8
case 0x60: gb->cpu.H = gb->cpu.B; break;
case 0x61: gb->cpu.H = gb->cpu.C; break;
case 0x62: gb->cpu.H = gb->cpu.D; break;
case 0x63: gb->cpu.H = gb->cpu.E; break;
case 0x64: gb->cpu.H = gb->cpu.H; break;
case 0x65: gb->cpu.H = gb->cpu.L; break;
case 0x67: gb->cpu.H = gb->cpu.A; break;
// ld $l, $reg8
case 0x68: gb->cpu.L = gb->cpu.B; break;
case 0x69: gb->cpu.L = gb->cpu.C; break;
case 0x6A: gb->cpu.L = gb->cpu.D; break;
case 0x6B: gb->cpu.L = gb->cpu.E; break;
case 0x6C: gb->cpu.L = gb->cpu.H; break;
case 0x6D: gb->cpu.L = gb->cpu.L; break;
case 0x6F: gb->cpu.L = gb->cpu.A; break;
// ld $a, $reg8
case 0x78: gb->cpu.A = gb->cpu.B; break;
case 0x79: gb->cpu.A = gb->cpu.C; break;
case 0x7A: gb->cpu.A = gb->cpu.D; break;
case 0x7B: gb->cpu.A = gb->cpu.E; break;
case 0x7C: gb->cpu.A = gb->cpu.H; break;
case 0x7D: gb->cpu.A = gb->cpu.L; break;
case 0x7F: gb->cpu.A = gb->cpu.A; break;
### Memory-to-Register and Register-to-Memory
<a name="op_ldrm"></a><a name="op_ldmr"></a>
Each register can be loaded with a single byte from memory, using the `HL`
register pair to specify the memory address. Conversely register values can be
stored to the address specified by `HL`.
<< cpu instructions >>=
// ld $reg8, ($hl)
case 0x46: gb->cpu.B = mmu_read(gb, ReadHL(gb)); break;
case 0x4E: gb->cpu.C = mmu_read(gb, ReadHL(gb)); break;
case 0x56: gb->cpu.D = mmu_read(gb, ReadHL(gb)); break;
case 0x5E: gb->cpu.E = mmu_read(gb, ReadHL(gb)); break;
case 0x66: gb->cpu.H = mmu_read(gb, ReadHL(gb)); break;
case 0x6E: gb->cpu.L = mmu_read(gb, ReadHL(gb)); break;
case 0x7E: gb->cpu.A = mmu_read(gb, ReadHL(gb)); break;
// ld ($hl), $reg8
case 0x70: mmu_write(gb, ReadHL(gb), gb->cpu.B); break;
case 0x71: mmu_write(gb, ReadHL(gb), gb->cpu.C); break;
case 0x72: mmu_write(gb, ReadHL(gb), gb->cpu.D); break;
case 0x73: mmu_write(gb, ReadHL(gb), gb->cpu.E); break;
case 0x74: mmu_write(gb, ReadHL(gb), gb->cpu.H); break;
case 0x75: mmu_write(gb, ReadHL(gb), gb->cpu.L); break;
case 0x77: mmu_write(gb, ReadHL(gb), gb->cpu.A); break;
An immediate value can be stored to memory at address `HL`.
<< cpu instructions >>=
case 0x36: mmu_write(gb, ReadHL(gb), Imm8(gb)); break; // ld ($hl), imm8
<a name="op_ldam"></a><a name="op_ldma"></a>
In addition there are more memory load/store instructions which are available only for the `A` register.
The register pairs `BC` and `DE` can be used to specify memory addresses:
<< cpu instructions >>=
// ld $a, ($reg16)
case 0x0A: gb->cpu.A = mmu_read(gb, ReadBC(gb)); break;
case 0x1A: gb->cpu.A = mmu_read(gb, ReadDE(gb)); break;
// ld ($reg16), $a
case 0x02: mmu_write(gb, ReadBC(gb), gb->cpu.A); break;
case 0x12: mmu_write(gb, ReadDE(gb), gb->cpu.A); break;
An immediate address can be used for load/store of `A`.
<< cpu instructions >>=
case 0xEA: mmu_write(gb, Imm16(gb), gb->cpu.A); break; // ld (imm16), $a
case 0xFA: gb->cpu.A = mmu_read(gb, Imm16(gb)); break; // ld $a, (imm16)
There are special variants of the indirect memory loads `ld ($hl), $a` and `ld $a, ($hl)` which perform the load and increment or decrement the value of `HL` in the same instruction.
<< cpu instructions >>=
case 0x22: // ld ($hl+), $a
mmu_write(gb, ReadHL(gb), gb->cpu.A);
WriteHL(gb, ReadHL(gb) + 1);
break;
case 0x2A: // ld $a, ($hl+)
gb->cpu.A = mmu_read(gb, ReadHL(gb));
WriteHL(gb, ReadHL(gb) + 1);
break;
case 0x32: // ld ($hl-), $a
mmu_write(gb, ReadHL(gb), gb->cpu.A);
WriteHL(gb, ReadHL(gb) - 1);
break;
case 0x3A: // ld $a, ($hl-)
gb->cpu.A = mmu_read(gb, ReadHL(gb));
WriteHL(gb, ReadHL(gb) - 1);
break;
Special variants of the immediate addressed load/stores are available which
load/store to an address at an unsigned 8bit offset from `0xFF00`. These are
usually referred to as "high memory loads".
<< cpu instructions >>=
case 0xE0: mmu_write(gb, 0xFF00 + Imm8(gb), gb->cpu.A); break; // ld (0xFF00 + imm8), $a
case 0xE2: mmu_write(gb, 0xFF00 + gb->cpu.C, gb->cpu.A); break; // ld (0xFF00 + $c), $a
case 0xF0: gb->cpu.A = mmu_read(gb, 0xFF00 + Imm8(gb)); break; // ld $a, (0xFF00 + imm8)
case 0xF2: gb->cpu.A = mmu_read(gb, 0xFF00 + gb->cpu.C); break; // ld $a, (0xFF00 + $c)
### Immediate-to-Register
<a name="op_ldri"></a>Each register can be loaded with an immediate value.
<< cpu instructions >>=
// ld $reg8, imm8
case 0x06: gb->cpu.B = Imm8(gb); break;
case 0x0E: gb->cpu.C = Imm8(gb); break;
case 0x16: gb->cpu.D = Imm8(gb); break;
case 0x1E: gb->cpu.E = Imm8(gb); break;
case 0x26: gb->cpu.H = Imm8(gb); break;
case 0x2E: gb->cpu.L = Imm8(gb); break;
case 0x3E: gb->cpu.A = Imm8(gb); break;
The 16-bit register pairs `BC`, `DE`, `HL` and the stack pointer `SP` can be loaded with immediate values.
<< cpu instructions >>=
// ld $reg16, imm16
case 0x01: WriteBC(gb, Imm16(gb)); break;
case 0x11: WriteDE(gb, Imm16(gb)); break;
case 0x21: WriteHL(gb, Imm16(gb)); break;
case 0x31: gb->cpu.SP = Imm16(gb); break;
## Stack and Stack Pointer
The stack pointer (`SP`) can be set to an immediate value or the value of `HL`.
<< cpu instructions >>=
case 0x08: { // ld (imm16), $sp
uint16_t addr = Imm16(gb);
mmu_write(gb, addr, (gb->cpu.SP & 0xFF));
mmu_write(gb, addr + 1, (gb->cpu.SP >> 8u));
} break;
case 0xF9: // ld $sp, $hl
clock_increment(gb);
gb->cpu.SP = ReadHL(gb);
break;
The stack pointer plus a signed immediate offset can be loaded into HL.
<< cpu instructions >>=
case 0xF8: { // ld $hl, $sp + imm8
uint16_t ea = gb->cpu.SP + Imm8i(gb);
clock_increment(gb);
WriteHL(gb, ea);
UpdateZNHC(gb, false, false, (ea & 0xF) < (gb->cpu.SP & 0xF), (ea & 0xFF) < (gb->cpu.SP & 0xFF));
} break;
### Stack push/pop
Each of the register pairs `BC`, `DE`, `HL` and `AF` can be pushed and popped
to/from the stack. Pushing a register pair takes an additional machine cycle.
<< cpu instructions >>=
// pop $reg16
case 0xC1: WriteBC(gb, Pop16(gb)); break;
case 0xD1: WriteDE(gb, Pop16(gb)); break;
case 0xE1: WriteHL(gb, Pop16(gb)); break;
case 0xF1: WriteAF(gb, Pop16(gb)); break;
// push $reg16
case 0xC5:
clock_increment(gb);
Push16(gb, ReadBC(gb));
break;
case 0xD5:
clock_increment(gb);
Push16(gb, ReadDE(gb));
break;
case 0xE5:
clock_increment(gb);
Push16(gb, ReadHL(gb));
break;
case 0xF5:
clock_increment(gb);
Push16(gb, ReadAF(gb));
break;
## 8bit Arithmetic
Addition of two 8 bit values is quite straight-forward. The output flags are calculated in a logical manner:
- `Z` flag is set when the output is zero
- `N` flag is cleared
- `H` flag is set if there is a carry from the bottom nibble addition
- `C` flag is set if there is a carry from the whole byte addition
<< cpu helpers >>=
uint8_t Add8(struct Gameboy* gb, uint8_t val0, uint8_t val1, bool carry)
{
unsigned int sum = val0 + val1 + carry;
unsigned int halfSum = (val0 & 0xF) + (val1 & 0xF) + carry;
UpdateZNHC(gb, (sum & 0xFF) == 0, false, halfSum > 0xF, sum > 0xFF);
return sum & 0xFF;
}
The `add` instruction adds two 8-bit operands, ignoring the current value of the carry flag.
<< cpu instructions >>=
// add $a, reg8
case 0x80: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.B, false); break;
case 0x81: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.C, false); break;
case 0x82: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.D, false); break;
case 0x83: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.E, false); break;
case 0x84: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.H, false); break;
case 0x85: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.L, false); break;
case 0x87: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.A, false); break;
// add $a, ($hl)
case 0x86: gb->cpu.A = Add8(gb, gb->cpu.A, mmu_read(gb, ReadHL(gb)), false); break;
// add $a, imm8
case 0xC6: gb->cpu.A = Add8(gb, gb->cpu.A, Imm8(gb), false); break;
The `adc` (add with carry) instruction adds the two operands and the current
value of the carry flag together. This allow implementation of extended
precision arithmetic by chaining multiple `add`/`adc` instructions.
<< cpu instructions >>=
// adc $a, reg8
case 0x88: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.B, ReadC(gb)); break;
case 0x89: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.C, ReadC(gb)); break;
case 0x8A: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.D, ReadC(gb)); break;
case 0x8B: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.E, ReadC(gb)); break;
case 0x8C: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.H, ReadC(gb)); break;
case 0x8D: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.L, ReadC(gb)); break;
case 0x8F: gb->cpu.A = Add8(gb, gb->cpu.A, gb->cpu.A, ReadC(gb)); break;
// adc $a, ($hl)
case 0x8E: gb->cpu.A = Add8(gb, gb->cpu.A, mmu_read(gb, ReadHL(gb)), ReadC(gb)); break;
// adc $a, imm8
case 0xCE: gb->cpu.A = Add8(gb, gb->cpu.A, Imm8(gb), ReadC(gb)); break;
Eight bit subtraction is very similar to addition; the meaning of the carry and
half-carry flags are better described as borrow and half-borrow.
<< cpu helpers >>=
uint8_t Sub8(struct Gameboy* gb, uint8_t val0, uint8_t val1, bool carry)
{
unsigned int sum = val0 - val1 - carry;
unsigned int halfSum = (val0 & 0xF) - (val1 & 0xF) - carry;
UpdateZNHC(gb, (sum & 0xFF) == 0, true, halfSum > 0xF, sum > 0xFF);
return sum;
}
The `sub` instruction subtracts two 8-bit operands, ignoring the current flags.
<< cpu instructions >>=
// sub $a, reg8
case 0x90: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.B, false); break;
case 0x91: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.C, false); break;
case 0x92: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.D, false); break;
case 0x93: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.E, false); break;
case 0x94: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.H, false); break;
case 0x95: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.L, false); break;
case 0x97: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.A, false); break;
// sub $a, ($hl)
case 0x96: gb->cpu.A = Sub8(gb, gb->cpu.A, mmu_read(gb, ReadHL(gb)), false); break;
// sub $a, imm8
case 0xD6: gb->cpu.A = Sub8(gb, gb->cpu.A, Imm8(gb), false); break;
The `sbc` (subtract with carry) subtracts two 8-bit operands and the current value of the carry flag.
<< cpu instructions >>=
// sbc $a, reg8
case 0x98: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.B, ReadC(gb)); break;
case 0x99: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.C, ReadC(gb)); break;
case 0x9A: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.D, ReadC(gb)); break;
case 0x9B: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.E, ReadC(gb)); break;
case 0x9C: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.H, ReadC(gb)); break;
case 0x9D: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.L, ReadC(gb)); break;
case 0x9F: gb->cpu.A = Sub8(gb, gb->cpu.A, gb->cpu.A, ReadC(gb)); break;
// sbc $a, ($hl)
case 0x9E: gb->cpu.A = Sub8(gb, gb->cpu.A, mmu_read(gb, ReadHL(gb)), ReadC(gb)); break;
// sbc $a, imm8
case 0xDE: gb->cpu.A = Sub8(gb, gb->cpu.A, Imm8(gb), ReadC(gb)); break;
Increment adds one to a register, but never considers or updates the carry flag.
<< cpu helpers >>=
uint8_t Inc8(struct Gameboy* gb, uint8_t val)
{
UpdateZ(gb, val == 0xFF);
UpdateN(gb, false);
UpdateH(gb, (val & 0xF) == 0xF);
return val + 1;
}
<< cpu instructions >>=
// inc reg8
case 0x04: gb->cpu.B = Inc8(gb, gb->cpu.B); break;
case 0x0C: gb->cpu.C = Inc8(gb, gb->cpu.C); break;
case 0x14: gb->cpu.D = Inc8(gb, gb->cpu.D); break;
case 0x1C: gb->cpu.E = Inc8(gb, gb->cpu.E); break;
case 0x24: gb->cpu.H = Inc8(gb, gb->cpu.H); break;
case 0x2C: gb->cpu.L = Inc8(gb, gb->cpu.L); break;
case 0x3C: gb->cpu.A = Inc8(gb, gb->cpu.A); break;
Conversely decrement subtracts one from a register, not considering or updating the carry flag.
<< cpu helpers >>=
uint8_t Dec8(struct Gameboy* gb, uint8_t val)
{
UpdateZ(gb, val == 0x01);
UpdateN(gb, true);
UpdateH(gb, (val & 0xF) == 0x0);
return val - 1;
}
<< cpu instructions >>=
// dec reg8
case 0x05: gb->cpu.B = Dec8(gb, gb->cpu.B); break;
case 0x0D: gb->cpu.C = Dec8(gb, gb->cpu.C); break;
case 0x15: gb->cpu.D = Dec8(gb, gb->cpu.D); break;
case 0x1D: gb->cpu.E = Dec8(gb, gb->cpu.E); break;
case 0x25: gb->cpu.H = Dec8(gb, gb->cpu.H); break;
case 0x2D: gb->cpu.L = Dec8(gb, gb->cpu.L); break;
case 0x3D: gb->cpu.A = Dec8(gb, gb->cpu.A); break;
The `cp` (compare) instruction performs a subtraction between two registers, but
does not store the result: its only change to the CPU state is to update the
flag register. This instruction is principally used to form the predicate for a
conditional jump.
<< cpu instructions >>=
// cp $a, reg8
case 0xB8: Sub8(gb, gb->cpu.A, gb->cpu.B, false); break;
case 0xB9: Sub8(gb, gb->cpu.A, gb->cpu.C, false); break;
case 0xBA: Sub8(gb, gb->cpu.A, gb->cpu.D, false); break;
case 0xBB: Sub8(gb, gb->cpu.A, gb->cpu.E, false); break;
case 0xBC: Sub8(gb, gb->cpu.A, gb->cpu.H, false); break;
case 0xBD: Sub8(gb, gb->cpu.A, gb->cpu.L, false); break;
case 0xBF: Sub8(gb, gb->cpu.A, gb->cpu.A, false); break;
// cp $a, ($hl)
case 0xBE: Sub8(gb, gb->cpu.A, mmu_read(gb, ReadHL(gb)), false); break;
// cp $a, imm8
case 0xFE: Sub8(gb, gb->cpu.A, Imm8(gb), false); break;
## Bitwise boolean logic operations
Bitwise `and`, `or` and `xor` all set the `Z` flag to reflect if the result is zero. Other flags are set to fixed values.
<< cpu helpers >>=
void BitAnd(struct Gameboy* gb, uint8_t value)
{
gb->cpu.A &= value;
UpdateZNHC(gb, gb->cpu.A == 0, false, true, false);
}
void BitOr(struct Gameboy* gb, uint8_t value)
{
gb->cpu.A |= value;
UpdateZNHC(gb, gb->cpu.A == 0, false, false, false);
}
void BitXor(struct Gameboy* gb, uint8_t value)
{
gb->cpu.A ^= value;
UpdateZNHC(gb, gb->cpu.A == 0, false, false, false);
}
<< cpu instructions >>=
// and/or/xor $a, $reg8
case 0xA0: BitAnd(gb, gb->cpu.B); break;
case 0xA1: BitAnd(gb, gb->cpu.C); break;
case 0xA2: BitAnd(gb, gb->cpu.D); break;
case 0xA3: BitAnd(gb, gb->cpu.E); break;
case 0xA4: BitAnd(gb, gb->cpu.H); break;
case 0xA5: BitAnd(gb, gb->cpu.L); break;
case 0xA7: BitAnd(gb, gb->cpu.A); break;
case 0xB0: BitOr(gb, gb->cpu.B); break;
case 0xB1: BitOr(gb, gb->cpu.C); break;
case 0xB2: BitOr(gb, gb->cpu.D); break;
case 0xB3: BitOr(gb, gb->cpu.E); break;
case 0xB4: BitOr(gb, gb->cpu.H); break;
case 0xB5: BitOr(gb, gb->cpu.L); break;
case 0xB7: BitOr(gb, gb->cpu.A); break;
case 0xA8: BitXor(gb, gb->cpu.B); break;
case 0xA9: BitXor(gb, gb->cpu.C); break;
case 0xAA: BitXor(gb, gb->cpu.D); break;
case 0xAB: BitXor(gb, gb->cpu.E); break;
case 0xAC: BitXor(gb, gb->cpu.H); break;
case 0xAD: BitXor(gb, gb->cpu.L); break;
case 0xAF: BitXor(gb, gb->cpu.A); break;
// and/or/xor $a, ($hl)
case 0xA6: BitAnd(gb, mmu_read(gb, ReadHL(gb))); break;
case 0xB6: BitOr(gb, mmu_read(gb, ReadHL(gb))); break;
case 0xAE: BitXor(gb, mmu_read(gb, ReadHL(gb))); break;
// and/or/xor $a, imm8
case 0xE6: BitAnd(gb, Imm8(gb)); break;
case 0xF6: BitOr(gb, Imm8(gb)); break;
case 0xEE: BitXor(gb, Imm8(gb)); break;
Single bit rotate left & right of `A`
<< cpu instructions >>=
case 0x07: { // rlca
UpdateZNHC(gb, false, false, false, (gb->cpu.A & 0x80));
gb->cpu.A = (gb->cpu.A << 1u) | (gb->cpu.A >> 7u);
} break;
case 0x0F: { // rrca
UpdateZNHC(gb, false, false, false, (gb->cpu.A & 0x01));
gb->cpu.A = (gb->cpu.A >> 1u) | (gb->cpu.A << 7u);
} break;
Single bit rotate left & right of `A`, considering the carry flag as an extra
bit (the most significant) of `A`.
<< cpu instructions >>=
case 0x17: { // rla
bool c = ReadC(gb);
UpdateZNHC(gb, false, false, false, (gb->cpu.A & 0x80));
gb->cpu.A = (gb->cpu.A << 1u) | (c? 1 : 0);
} break;
case 0x1F: { // rra
bool c = ReadC(gb);
UpdateZNHC(gb, false, false, false, (gb->cpu.A & 0x01));
gb->cpu.A = (gb->cpu.A >> 1u) | (c? 0x80 : 0x00);
} break;
Complement (bitwise invert) all bits in `A`.
<< cpu instructions >>=
case 0x2F: { // cpl
UpdateN(gb, true);
UpdateH(gb, true);
gb->cpu.A ^= UINT8_MAX;
} break;
### Extended Bitwise Operations (`0xCB`)
The CPU provides an additional set of bitwise operations via an extended
instruction sequence: the `0xCB` is a two-byte instruction which performs an
operation determined by the second byte. The operation encoding is quite
regular: the bits of the extension byte (MSB to LSB) `OOIIIRRR` encode a 2bit
operation field `OO`, a three bit sub-operation or bit index (`III`), and a
three bit register index (`RRR`).
<< cpu instructions >>=
case 0xCB: {
cpu_cb_op(gb);
} break;
The register operated on is selected by the register field:
Value | Register
------|---------
0 | B
1 | C
2 | D
3 | E
4 | H
5 | L
6 | (HL) - memory at address HL
7 | A
<< cpu helpers >>=
uint8_t ReadRegN(struct Gameboy* gb, unsigned int regNum)
{
switch(regNum) {
case 0: return gb->cpu.B;
case 1: return gb->cpu.C;
case 2: return gb->cpu.D;
case 3: return gb->cpu.E;
case 4: return gb->cpu.H;
case 5: return gb->cpu.L;
case 6: return mmu_read(gb, ReadHL(gb));
case 7: return gb->cpu.A;
}
assert(false);
}
void WriteRegN(struct Gameboy* gb, unsigned int regNum, uint8_t newVal)
{
switch(regNum) {
case 0: gb->cpu.B = newVal; break;
case 1: gb->cpu.C = newVal; break;
case 2: gb->cpu.D = newVal; break;
case 3: gb->cpu.E = newVal; break;
case 4: gb->cpu.H = newVal; break;
case 5: gb->cpu.L = newVal; break;
case 6: mmu_write(gb, ReadHL(gb), newVal); break;
case 7: gb->cpu.A = newVal; break;
}
}
<< cpu helpers >>=
void cpu_cb_op(struct Gameboy* gb)
{
uint8_t const cb_opcode = Imm8(gb);
// XX XXX XXX
// ~~ operation