Sometimes when reverse engineering old devices I come across clever decades old 8-bit code that deserves a tip of the hat. This example 6805 code is a clever way of providing multiple carefully tuned delays without modifying either of the only two registers (A, X). That eliminates code for saving, loading, and restoring those registers for each jsr call.
It's a chain of nested bsr (branch subroutine) that give specific delays for each entry point. I had to write the following perl script simulator to determine those delays. Maximum stack usage is 26 bytes. The 6805 code disassembly is in the comments.
#!/usr/bin/perl
# usage: ./bsr.pl
#
# simulate nested bsr delay (6805 code)
# 1073: AD 00 bsr $1075 ; 64000 cyc
# 1075: AD 00 bsr $1077 ; 32000 cyc
# 1077: AD 00 bsr $1079 ; 16000 cyc
# 1079: AD 00 bsr $107B ; 8000 cyc
# 107B: AD 00 bsr $107D ; 4000 cyc
# 107D: AD 00 bsr $107F ; 2000 cyc
# 107F: AD 00 bsr $1081 ; 1000 cyc
# 1081: AD 02 bsr $1085 ; 500 cyc
# 1083: AD 02 bsr $1087 ; 300 cyc
# 1085: AD 00 bsr $1087 ; 200 cyc
# 1087: AD 00 bsr $1089 ; 100 cyc
# 1089: 9D nop ; 50 cyc
# 108A: AD 00 bsr $108C ; 48 cyc
# 108C: AD 00 bsr $108E ; 24 cyc
# 108E: 81 rts
use strict;
my $count = 6; # include cycles for jsr to entry point
my $pc = 0x1073; # entry point
my @stack = ( 0x999 ); # exit pc
while ($pc != 0x999) {
SWITCH: {
if ($pc == 0x1089) { ++$pc; $count += 2; last SWITCH; } # nop
$count += 6; # rts|bsr
if ($pc == 0x108E) { $pc = pop @stack; last SWITCH; } # rts
push @stack, ($pc + 2); # all bsr
if ($pc == 0x1073) { $pc = 0x1075; last SWITCH; }
if ($pc == 0x1075) { $pc = 0x1077; last SWITCH; }
if ($pc == 0x1077) { $pc = 0x1079; last SWITCH; }
if ($pc == 0x1079) { $pc = 0x107B; last SWITCH; }
if ($pc == 0x107B) { $pc = 0x107D; last SWITCH; }
if ($pc == 0x107D) { $pc = 0x107F; last SWITCH; }
if ($pc == 0x107F) { $pc = 0x1081; last SWITCH; }
if ($pc == 0x1081) { $pc = 0x1085; last SWITCH; }
if ($pc == 0x1083) { $pc = 0x1087; last SWITCH; }
if ($pc == 0x1085) { $pc = 0x1087; last SWITCH; }
if ($pc == 0x1087) { $pc = 0x1089; last SWITCH; }
if ($pc == 0x108A) { $pc = 0x108C; last SWITCH; }
if ($pc == 0x108C) { $pc = 0x108E; last SWITCH; }
printf("ERROR, unknown pc=%04X\n", $pc); # default
exit;
}
}
print $count, " cycles\n";