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
|
Most tricks come from either [Jeff's GB Assembly Code Tips v1.0](http://www.devrs.com/gb/files/asmtips.txt), or [the page on Z80 Optimization on WikiTI](http://wikiti.brandonw.net/index.php?title=Z80_Optimization)
## Registers
### Set A to zero
```asm
ld a, 0 ; 2 bytes, 2 cycles, no changes to flags
;;;
xor a ; 1 byte, 1 cycle, sets flags C to 0 and Z to 1
sub a ; 1 byte, 1 cycle, sets flags C to 0 and Z to 1
```
### Set A to some constant subtracted by A
```asm
ld b,a ; 4 bytes, 4 cycles
ld a,CONST
sub b
;;;
cpl ; 3 bytes, 3 cycles
add CONST+1
```
### Add A to HL
```asm
add l ; 6 bytes, 6 cycles
ld l, a
ld a, 0
adc h
ld h,a
;;;
add l ; 5 bytes, 5 cycles
ld l, a
jr nc, .NoCarry
inc h
.NoCarry:
```
### Loading from an offset to HL
```asm
ld a, [offset] ; 8 bytes, 10 cycles
ld l, a
ld a, [offset+1]
ld h, a
;;;
ld hl, offset ; 6 bytes, 8 cycles
ld a, [hli]
ld h, [hl]
ld l, a
```
### Exchanging HE and DL
```asm
ld a,d ; 6 bytes, 6 cycles
ld d,h
ld h,a
ld a,e
ld e,l
ld l,a
;;;
push de ; 4 bytes, 9 cycles
ld d,h
ld e,l
pop hl
```
## Branching
### Compare A to zero
```asm
cp 0 ; 2 bytes, 2 cycles
;;;
or a ; 1 byte, 1 cycle
and a ; 1 byte, 1 cycle
```
### Compare A-1 to zero
```asm
cp 1 ; 2 bytes, 2 cycles
;;;
dec a ; 1 byte, 1 cycle, decrements a
```
## Functions
### Tail call optimization
```asm
call Function ; 4 bytes, 10 cycles
ret
;;;
jp Function ; 3 bytes, 4 cycles
```
## Executing subroutines
```asm
ld hl, param1
call Function1
ld hl, param2
call Function2
ld hl, param3
call Function1
...
...
.Function1:
...
ret
.Function2:
...
ret
;;;
ld sp, calltable
ret ; jump to sp (first entry on calltable)
.Function1:
pop hl
...
ret
.Function2:
pop hl
...
ret
calltable:
dw Function1, param1
dw Function2, param2
dw Function1, param3
```
### Calling HL
```asm
ld de, .retadr ; 5 bytes, 8 cycles
push de
jp [hl]
.retadr:
...
;;;
call DoJump ; 4 bytes, 7 cycles
...
DoJump:
jp [hl]
```
|