summaryrefslogtreecommitdiff
path: root/Optimizing-assembly-code.md
diff options
context:
space:
mode:
Diffstat (limited to 'Optimizing-assembly-code.md')
-rw-r--r--Optimizing-assembly-code.md70
1 files changed, 70 insertions, 0 deletions
diff --git a/Optimizing-assembly-code.md b/Optimizing-assembly-code.md
index e7bf5a9..a6d0d65 100644
--- a/Optimizing-assembly-code.md
+++ b/Optimizing-assembly-code.md
@@ -24,6 +24,7 @@ WikiTI's advice fully applies here:
- [Rotate the bits of `a`](#rotate-the-bits-of-a)
- [Set `a` to some constant minus `a`](#set-a-to-some-constant-minus-a)
- [Set `a` to one constant or another depending on the carry flag](#set-a-to-one-constant-or-another-depending-on-the-carry-flag)
+ - [Increment or decrement `a` depending on the carry flag](#increment-or-decrement-a-depending-on-the-carry-flag)
- [Divide `a` by 8 (shift `a` right 3 bits)](#divide-a-by-8-shift-a-right-3-bits)
- [Divide `a` by 16 (shift `a` right 4 bits)](#divide-a-by-16-shift-a-right-4-bits)
- [Set `a` to some value plus carry](#set-a-to-some-value-plus-carry)
@@ -226,6 +227,16 @@ And if either is 0, don't do:
.carry
```
+And if either is 1 more or less than the other, don't do:
+
+```asm
+ ; 5 bytes, 5 or 6 cycles
+ ld a, CVAL ; nor NCVAL
+ jr c, .carry ; nor jr nc
+ inc a ; nor dec a
+.carry
+```
+
Instead use `sbc a`, which copies the carry flag to all bits of `a`. Thus do:
```asm
@@ -303,6 +314,65 @@ If `CVAL` is 0 and `NCVAL` is 1 (i.e. set `a` to 0 if carry, or 1 if not carry),
```
+### Increment or decrement `a` depending on the carry flag
+
+Don't do:
+
+```asm
+ ; 3 bytes, 3 or 4 cycles
+ jr nc, .ok
+ inc a
+.ok
+```
+
+```asm
+ ; 3 bytes, 3 or 4 cycles
+ jr nc, .ok
+ dec a
+.ok
+```
+
+But do:
+
+```asm
+ adc 0 ; 2 bytes, 2 cycles
+```
+
+```asm
+ sbc 0 ; 2 bytes, 2 cycles
+```
+
+And don't do:
+
+```asm
+ ; 3 bytes, 3 or 4 cycles
+ jr c, .ok
+ inc a
+.ok
+```
+
+```asm
+ ; 3 bytes, 3 or 4 cycles
+ jr c, .ok
+ dec a
+.ok
+```
+
+But do:
+
+```asm
+ ; 3 bytes, 3 cycles
+ ccf
+ adc 0
+```
+
+```asm
+ ; 3 bytes, 3 cycles
+ ccf
+ sbc 0
+```
+
+
### Divide `a` by 8 (shift `a` right 3 bits)
Don't do: