-
Notifications
You must be signed in to change notification settings - Fork 8
/
xas99.py
executable file
·3663 lines (3324 loc) · 157 KB
/
xas99.py
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
#!/usr/bin/env python3
# xas99: A TMS9900 cross-assembler
#
# Copyright (c) 2015-2024 Ralph Benzinger <r@0x01.de>
#
# This program is part of the TI 99 Cross-Development Tools (xdt99).
#
# xdt99 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
import re
import math
import os
import argparse
import zipfile
from functools import reduce
from xcommon import Util, RFile, CommandProcessor, Warnings, Console
VERSION = '3.6.5'
CONFIG = 'XAS99_CONFIG'
# Exception Class
class AsmError(Exception):
pass
# Misc. Objects
class Address:
"""absolute or relocatable address"""
def __init__(self, addr, bank=None, reloc=False, unit_id=0):
self.addr = addr
self.bank = bank
self.reloc = reloc
self.unit_id = unit_id # -1 for predefined and command-line defined symbols
def __eq__(self, other):
"""required for externally defined symbols in Symbols"""
return (isinstance(other, Address) and
self.addr == other.addr and self.bank == other.bank and self.reloc == other.reloc and
self.unit_id == other.unit_id)
def hex(self):
return '{:04X}{:s}'.format(self.addr, 'r' if self.reloc else ' ')
@staticmethod
def val(n):
"""dereference address"""
return n.addr if isinstance(n, Address) else n
class Local:
"""local label reference"""
def __init__(self, name, distance):
self.name = name
self.distance = distance
class AutoConstant(Address):
def __init__(self, value, size='W', bank=None, symbols=None):
super().__init__(None, unit_id=symbols.unit_id)
self.value = value
self.size = size
self.bank = bank
self.name = self.get_name(size, value, bank)
self.addr = None
self.symbols = symbols # for finding address of auto-constant later
@staticmethod
def get_name(size, value, bank):
return '_%auto' + size + str(value) + 'b' + str(bank)
def resolve_addr(self):
self.addr = self.symbols.get_symbol(self.name)
return self.addr
class Reference:
"""external reference"""
def __init__(self, name):
self.name = name
class Value:
"""wraps value of auto-constants"""
def __init__(self, value):
self.value = value
class Block:
"""reserved block of bytes"""
def __init__(self, size):
self.size = size
class Word:
"""auxiliary class for word arithmetic"""
def __init__(self, value):
self.value = value % 0x10000 # always between >0000 and >ffff, but signed
def sign(self):
return -1 if self.value & 0x8000 else +1
def abs(self):
return -self.value % 0x10000 if self.value & 0x8000 else self.value
def add(self, arg):
self.value = (self.value + arg.value) % 0x10000
def sub(self, arg):
self.value = (self.value - arg.value) % 0x10000
def mul(self, op, arg):
sign = arg.sign() if op == '%' else self.sign() * arg.sign()
val = self.abs() * arg.abs()
self.value = (val if sign > 0 else -val) % 0x10000
def div(self, op, arg):
if arg.value == 0:
raise AsmError('Division by zero')
sign = arg.sign() if op == '%' else self.sign() * arg.sign()
val = (self.abs() // arg.abs() if op == '/' else
self.abs() % arg.abs() if op == '%' else None)
self.value = (val if sign > 0 else -val) % 0x10000
def udiv(self, op, arg):
if arg.value == 0:
raise AsmError('Division by zero')
if op == '%%':
self.value %= arg.value
else:
self.value //= arg.value
def bit(self, op, arg):
val = (self.value & arg.value if op == '&' else
self.value | arg.value if op == '|' else
self.value ^ arg.value if op == '^' else None)
self.value = val % 0x10000
def shift(self, op, arg):
if arg < 0:
AsmError('Cannot shift by negative values')
if op == '>>':
self.value >>= arg
else:
self.value = (self.value << arg) & 0xffff
# Opcodes and Directives
class Timing:
OPCODE = 1
MEMORY = 2
MEMORY_2 = 3
REGISTER = 4 # e.g., write without read-before-write
REGISTER_2 = 5 # e.g., read-before-write
ROM = 6
CRU = 7
UNKNOWN_S = 8 # e.g., *r1, @s(r1)
UNKNOWN_D = 9
MUX_WAITSTATES = 4
asm = None # current assembler
def __init__(self, cycles, mem_accesses, byte=False, read=False):
"""capture the basic timing information for instruction execution
All timing data is derived from TMS 9900 Microprocessor Data Manual, section 3.6.
mem_accesses does not include accesses for arguments, including register accesses.
Do not modify these instance variables, since this instrance is shared among all
usages of a certain mnemonic.
"""
self.LC = 0
self.WP = 0
self.byte = byte # is byte-access?
self.read = read # if single argument read or write?
self.cycles = cycles # number of cycles needed w/o arguments
self.mem_accesses = mem_accesses # number of memory accesses needed w/o arguments
@staticmethod
def demuxed(addr):
"""addr is muxed (slow) or not (fast)?"""
# don't know if demuxed for not-integer addresses (e.g., None when memory access for B *R11)
return 0x2000 <= addr < 0x8000 or 0x9000 <= addr if isinstance(addr, int) else True
@staticmethod
def unknown(dest=False, count=1):
"""unknown memory accesses (could be demuxed or not)"""
return (Timing.UNKNOWN_D,) * count if dest else (Timing.UNKNOWN_S,) * count
def operand_cycles(self, t, byte=False):
"""additional cycles for operand (cycles in table A and B)
Note that the additional cycles for writing the result has already been included in the
base number of cycles in Opcodes, which corresponds to the listing in the Data Manual.
"""
return (2, 6, 10, 8)[t] if byte else (2, 6, 10, 10)[t] # symbolic and indexed have same number of cycles
def operand_mem_accesses(self, t, index=0, read=False, dest=False):
"""additional memory accesses for operand (mem accesses in table A and B)
Here we still need an additional memory access for write arguments.
"""
# note that for write access, only the last address is written to
if t == 0b00: # register
return (Timing.REGISTER,) if read else (Timing.REGISTER_2,)
elif t == 0b01: # indirect
# read/write register and target addr
return (Timing.REGISTER,) + self.unknown(dest) if read else (Timing.REGISTER,) + self.unknown(dest, count=2)
elif t == 0b11: # indirect auto-increment
# read/write register and target addr, then write register
return ((Timing.REGISTER_2,) + self.unknown(dest) if read else
(Timing.REGISTER_2,) + self.unknown(dest, count=2))
elif t == 0b10: # symbolic/indexed
if index:
# indexed: read/write symbol value, register, and target addr
return ((Timing.REGISTER, Timing.OPCODE,) + self.unknown(dest) if read else
(Timing.REGISTER, Timing.OPCODE,) + self.unknown(dest, count=2))
else:
# symbolic: read/write symbol value and target addr
return (Timing.OPCODE, Timing.MEMORY) if read else (Timing.OPCODE, Timing.MEMORY_2)
def memory_cycles(self, accesses, addr=None):
"""number of waitstates based on address"""
cycles = 0
for access in accesses:
if access == Timing.OPCODE:
cycles += Timing.MUX_WAITSTATES if Timing.demuxed(self.LC) else 0
elif access == Timing.REGISTER:
cycles += Timing.MUX_WAITSTATES if Timing.demuxed(self.WP) else 0
elif access == Timing.REGISTER_2:
cycles += 2 * Timing.MUX_WAITSTATES if Timing.demuxed(self.WP) else 0 # read and write
elif access == Timing.MEMORY:
cycles += Timing.MUX_WAITSTATES if Timing.demuxed(addr) else 0
elif access == Timing.MEMORY_2:
cycles += 2 * Timing.MUX_WAITSTATES if Timing.demuxed(addr) else 0 # read and write
elif access == Timing.ROM:
pass # no waitstates for ROM >0000->1FFF
elif access == Timing.CRU:
pass # no waitstates for CRU
elif access == Timing.UNKNOWN_S: # source memory access to unknown address
if self.asm.demux['S']:
cycles += Timing.MUX_WAITSTATES
elif access == Timing.UNKNOWN_D: # destination memory access to unknown address
if self.asm.demux['D']:
cycles += Timing.MUX_WAITSTATES
return cycles
def time_noop(self):
"""number of cycles for execution (no operands)"""
if self.asm.symbols.pass_no == 1:
return 0
return self.cycles + self.memory_cycles(self.mem_accesses)
def time_1op(self, ts, s, sa):
"""number of cycles for execution (one operand)"""
if self.asm.symbols.pass_no == 1:
return 0
# NOTE: represents tables A/B, but compensates for register read with zero wait state
cycles = self.cycles + self.operand_cycles(ts, byte=self.byte)
mem_cycles = (self.memory_cycles(self.mem_accesses, addr=Address.val(sa)) +
self.memory_cycles(self.operand_mem_accesses(ts, index=s, read=self.read), addr=Address.val(sa)))
return cycles + mem_cycles
def time_2ops(self, ts, s, sa, td, d, da):
"""number of cycles for execution (two operands)"""
if self.asm.symbols.pass_no == 1:
return 0
cycles = self.cycles + self.operand_cycles(ts, byte=self.byte) + self.operand_cycles(td, byte=self.byte)
mem_cycles = (self.memory_cycles(self.mem_accesses) +
self.memory_cycles(self.operand_mem_accesses(ts, index=s, read=True),
addr=Address.val(sa)) +
self.memory_cycles(self.operand_mem_accesses(td, index=d, read=self.read, dest=True),
addr=Address.val(da)))
return cycles + mem_cycles
def time_shift(self, count):
"""number of cycles for shift instruction"""
if self.asm.symbols.pass_no == 1:
return 0
mem_accesses = self.mem_accesses + (Timing.REGISTER_2,)
if count == 0:
count = 16 # worst case, since contents of R0 unknown
mem_accesses += (Timing.REGISTER,) # also read R0
self.cycles += 8 # more cycles for processing R0
cycles = self.cycles + 2 * count
mem_cycles = self.memory_cycles(mem_accesses)
return cycles + mem_cycles
def time_mcru(self, ts, s, sa, count, ldcr=False):
"""number of cycles for multi-cru instructions"""
if self.asm.symbols.pass_no == 1:
return 0
if count == 0:
count = 16 # worst case, since contents of R0 unknown
byte_ = count <= 8 # do not modify self, as this object is shared among all LDCR or STCR mnemonics, resp.
cycles = self.cycles + self.operand_cycles(ts, byte=byte_)
mem_cycles = (self.memory_cycles(self.mem_accesses) +
self.memory_cycles(self.operand_mem_accesses(ts, index=s, read=self.read), addr=Address.val(sa)))
if ldcr: # LDCR
cru_cycles = 2 * count
else: # STCR
if count <= 8:
cru_cycles = 2 * 8 # C and C' subtract each other out
else:
cru_cycles = 2 * 16
if count == 8 or count == 16:
cru_cycles += 2 # extra cycle if no shifting required
return cycles + cru_cycles + mem_cycles
@staticmethod
def process(asm, mnemonic, source, destination):
"""check for special mnemonics"""
if mnemonic == 'LWPI':
asm.symbols.WP = source
class Opcodes:
op_ga = lambda parser, x: parser.address(x) # [0x0000 .. 0xFFFF]
op_wa = lambda parser, x: parser.register(x) # [0 .. 15]
op_imm = lambda parser, x: parser.expression(x, iop=True) # [0x0000 .. 0xFFFF]
op_cru = lambda parser, x: parser.expression(x, iop=True) # [-128 .. 127]
op_disp = lambda parser, x: parser.relative(x) # [-254 .. 256]
op_cnt = lambda parser, x: parser.expression(x, iop=True) # [0 .. 15]
op_scnt = lambda parser, x: parser.expression(x, iop=True, allow_r0=True) # [0 .. 15]
op_xop = lambda parser, x: parser.expression(x, iop=True) # [1 .. 2]
opcodes_9900 = {
# 6. arithmetic
'A': (0xa000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,))),
'AB': (0xb000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,), byte=True)),
'ABS': (0x0740, 6, op_ga, None, Timing(12, (Timing.OPCODE,))), # timing for worst case
'AI': (0x0220, 8, op_wa, op_imm, Timing(14, (Timing.OPCODE,) * 2 + (Timing.REGISTER_2,))),
'DEC': (0x0600, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'DECT': (0x0640, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'DIV': (0x3c00, 9, op_ga, op_wa, Timing(122, (Timing.OPCODE,) + (Timing.REGISTER_2,) * 2, read=True)),
'INC': (0x0580, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'INCT': (0x05c0, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'MPY': (0x3800, 9, op_ga, op_wa, Timing(52, (Timing.OPCODE, Timing.REGISTER_2, Timing.REGISTER), read=True)),
'NEG': (0x0500, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'S': (0x6000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,))),
'SB': (0x7000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,), byte=True)),
# 7. jump and branch
'B': (0x0440, 6, op_ga, None, Timing(6, (Timing.OPCODE,), read=True)),
'BL': (0x0680, 6, op_ga, None, Timing(10, (Timing.OPCODE, Timing.REGISTER), read=True)),
'BLWP': (0x0400, 6, op_ga, None, Timing(24, (Timing.OPCODE,) + (Timing.REGISTER,) * 3, read=False)),
# "new PC" memory read depends on operand, so treat it as write argument
'JEQ': (0x1300, 2, op_disp, None, Timing(10, (Timing.OPCODE,))), # 8 cycles if jump not taken
'JGT': (0x1500, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JHE': (0x1400, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JH': (0x1b00, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JL': (0x1a00, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JLE': (0x1200, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JLT': (0x1100, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JMP': (0x1000, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JNC': (0x1700, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JNE': (0x1600, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JNO': (0x1900, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JOP': (0x1c00, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'JOC': (0x1800, 2, op_disp, None, Timing(10, (Timing.OPCODE,))),
'RTWP': (0x0380, 7, None, None, Timing(14, (Timing.OPCODE,) + (Timing.REGISTER,) * 3)),
'X': (0x0480, 6, op_ga, None, None), # cannot measure reliably
'XOP': (0x2c00, 9, op_ga, op_xop, # timing difference between Datasheet and Hardware Design
Timing(34, (Timing.OPCODE,) + (Timing.ROM,) * 2 + (Timing.REGISTER,) * 4, read=True)),
# 8. compare instructions
'C': (0x8000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,), read=True)),
'CB': (0x9000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,), byte=True, read=True)),
'CI': (0x0280, 8, op_wa, op_imm, Timing(14, (Timing.OPCODE,) * 2 + (Timing.REGISTER,), read=True)),
'COC': (0x2000, 3, op_ga, op_wa, Timing(12, (Timing.OPCODE, Timing.REGISTER), read=True)),
'CZC': (0x2400, 3, op_ga, op_wa, Timing(12, (Timing.OPCODE, Timing.REGISTER), read=True)),
# 9. control and cru instructions
'LDCR': (0x3000, 4, op_ga, op_cnt, Timing(18, (Timing.OPCODE, Timing.REGISTER), read=True)),
'SBO': (0x1d00, 2, op_cru, None, Timing(12, (Timing.OPCODE, Timing.REGISTER), read=True)),
'SBZ': (0x1e00, 2, op_cru, None, Timing(12, (Timing.OPCODE, Timing.REGISTER), read=True)),
'STCR': (0x3400, 4, op_ga, op_cnt, Timing(24, (Timing.OPCODE, Timing.REGISTER))),
'TB': (0x1f00, 2, op_cru, None, Timing(12, (Timing.OPCODE, Timing.REGISTER), read=True)), # read R12
'CKOF': (0x03c0, 7, None, None, Timing(12, (Timing.OPCODE,))),
'CKON': (0x03a0, 7, None, None, Timing(12, (Timing.OPCODE,))),
'IDLE': (0x0340, 7, None, None, Timing(12, (Timing.OPCODE,))),
'RSET': (0x0360, 7, None, None, Timing(12, (Timing.OPCODE,))),
'LREX': (0x03e0, 7, None, None, Timing(12, (Timing.OPCODE,))),
# 10. load and move instructions
'LI': (0x0200, 8, op_wa, op_imm, Timing(12, (Timing.OPCODE,) * 2 + (Timing.REGISTER,))), # no read-before-write
'LIMI': (0x0300, 81, op_imm, None, Timing(14, (Timing.OPCODE,) * 2, read=True)),
'LWPI': (0x02e0, 82, op_imm, None, Timing(10, (Timing.OPCODE,) * 2, read=True)),
'MOV': (0xc000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,))),
'MOVB': (0xd000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,), byte=True)),
'STST': (0x02c0, 8, op_wa, None, Timing(8, (Timing.OPCODE,))), # writes internally
'STWP': (0x02a0, 8, op_wa, None, Timing(8, (Timing.OPCODE,))), # writes internally
'SWPB': (0x06c0, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
# 11. logical instructions
'ANDI': (0x0240, 8, op_wa, op_imm, Timing(14, (Timing.OPCODE,) * 2 + (Timing.REGISTER_2,))),
'ORI': (0x0260, 8, op_wa, op_imm, Timing(14, (Timing.OPCODE,) * 2 + (Timing.REGISTER_2,))),
'XOR': (0x2800, 3, op_ga, op_wa, Timing(12, (Timing.OPCODE, Timing.REGISTER_2), read=True)),
'INV': (0x0540, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'CLR': (0x04c0, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'SETO': (0x0700, 6, op_ga, None, Timing(8, (Timing.OPCODE,))),
'SOC': (0xe000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,))),
'SOCB': (0xf000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,), byte=True)),
'SZC': (0x4000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,))),
'SZCB': (0x5000, 1, op_ga, op_ga, Timing(10, (Timing.OPCODE,), byte=True)),
# 12. shift instructions
'SRA': (0x0800, 5, op_wa, op_scnt, Timing(12, (Timing.OPCODE,))), # CNT stored in opcode
'SRL': (0x0900, 5, op_wa, op_scnt, Timing(12, (Timing.OPCODE,))), # ops and count timing added
'SLA': (0x0a00, 5, op_wa, op_scnt, Timing(12, (Timing.OPCODE,))), # in special time function
'SRC': (0x0b00, 5, op_wa, op_scnt, Timing(12, (Timing.OPCODE,)))
# end of opcodes
}
opcodes_f18a = {
# F18A GPU instructions
'CALL': (0x0c80, 6, op_ga, None, None),
'RET': (0x0c00, 7, None, None, None),
'PUSH': (0x0d00, 6, op_ga, None, None),
'POP': (0x0f00, 6, op_ga, None, None),
'SLC': (0x0e00, 5, op_wa, op_scnt, None)
}
opcodes_9995 = {
# 9995 instructions
'MPYS': (0x01c0, 6, op_ga, None, None), # Note that 9900 timing and 9995 timing
'DIVS': (0x0180, 6, op_ga, None, None), # cannot be compared
'LST': (0x0080, 8, op_wa, None, None),
'LWP': (0x0090, 8, op_wa, None, None)
}
opcodes_99000 = {
# 99105 and 99110 instructions
'MPYS': (0x01c0, 6, op_ga, None, None), # Note that 9900 timing and 99000 timing
'DIVS': (0x0180, 6, op_ga, None, None), # cannot be compared
'LST': (0x0080, 8, op_wa, None, None),
'LWP': (0x0090, 8, op_wa, None, None),
'BIND': (0x0140, 106, op_ga, None, None),
'BLSK': (0x00b0, 108, op_wa, op_imm, None),
'TMB': (0x0c09, 103, op_ga, op_cnt, None),
'TCMB': (0xc0a, 103, op_ga, op_cnt, None),
'TSMB': (0x0c0b, 103, op_ga, op_cnt, None),
'AM': (0x002a, 101, op_ga, op_ga, None),
'SM': (0x0029, 101, op_ga, op_ga, None),
'SLAM': (0x001d, 109, op_ga, op_scnt, None),
'SRAM': (0x001c, 109, op_ga, op_scnt, None)
}
pseudos = {
# 13. pseudo instructions
'NOP': ('JMP', ['$+2'], 0),
'RT': ('B', ['*<R>11'], 0),
'SLL': ('SRL', None, 2),
'PIX': ('XOP', None, 2)
}
def __init__(self, use_9995=False, use_f18a=False, use_99000=False):
"""create opcode set; note that asm and parser might change over lifetime of opcodes"""
self.opcodes = Opcodes.opcodes_9900
if use_9995:
self.opcodes.update(Opcodes.opcodes_9995)
if use_f18a:
self.opcodes.update(Opcodes.opcodes_f18a)
if use_99000:
self.opcodes.update(Opcodes.opcodes_99000)
self.asm = None
def use_asm(self, asm):
"""set assembler to use"""
self.asm = asm
Timing.asm = asm
def process(self, label, mnemonic, operands):
"""get assembly asm for mnemonic"""
self.asm.even()
self.asm.process_label(label)
try:
m, ops, op_count = Opcodes.pseudos[mnemonic]
if self.asm.symbols.pass_no == 2 and self.asm.parser.relaxed and len(operands) != op_count:
raise AsmError('Bad operand count')
if ops is not None:
ops = [o.replace('<R>', 'R' if self.asm.parser.r_prefix else '') for o in ops]
mnemonic, operands = m, ops or operands
except KeyError:
try:
mode = self.asm.parser.symbols.xops[mnemonic]
mnemonic, operands = 'XOP', [operands[0], mode]
except KeyError:
pass
try:
opcode, fmt, parse_op1, parse_op2, timing = self.opcodes[mnemonic]
except KeyError:
raise AsmError('Invalid mnemonic: ' + mnemonic)
if parse_op1 and len(operands) != (1 if parse_op2 is None else 2):
raise AsmError('Bad operand count')
arg1 = parse_op1(self.asm.parser, operands[0]) if parse_op1 else None
arg2 = parse_op2(self.asm.parser, operands[1]) if parse_op2 else None
Optimizer.process(self.asm, mnemonic, opcode, fmt, arg1, arg2)
Timing.process(self.asm, mnemonic, arg1, arg2)
self.generate(opcode, fmt, arg1, arg2, timing)
return True
def generate(self, opcode, fmt, arg1, arg2, timing):
"""generate byte asm"""
if timing is not None:
timing.LC = self.asm.symbols.effective_LC()
timing.WP = self.asm.symbols.WP
# I. two general address instructions
if fmt == 1:
ts, s, sa = arg1
td, d, da = arg2
b = opcode | td << 10 | d << 6 | ts << 4 | s
t = 0 if timing is None else timing.time_2ops(ts, s, sa, td, d, da)
self.asm.emit(b, sa, da, cycles=t)
# II. jump and bit I/O instructions
elif fmt == 2:
b = opcode | arg1 & 0xff
t = 0 if timing is None else timing.time_noop()
self.asm.emit(b, cycles=t)
# III. logical instructions
elif fmt == 3:
ts, s, sa = arg1
d = arg2
b = opcode | d << 6 | ts << 4 | s
t = 0 if timing is None else timing.time_1op(ts, s, sa)
self.asm.emit(b, sa, cycles=t)
# IV. CRU multi-bit instructions
elif fmt == 4:
ts, s, sa = arg1
c = arg2
b = opcode | c << 6 | ts << 4 | s
t = 0 if timing is None else timing.time_mcru(ts, s, sa, c, ldcr=opcode == 0x3000)
self.asm.emit(b, sa, cycles=t)
# V. register shift instructions
elif fmt == 5:
w = arg1
c = arg2
b = opcode | c << 4 | w
t = 0 if timing is None else timing.time_shift(c)
self.asm.emit(b, cycles=t)
# VI. single address instructions
elif fmt == 6:
ts, s, sa = arg1
b = opcode | ts << 4 | s
t = 0 if timing is None else timing.time_1op(ts, s, sa)
self.asm.emit(b, sa, cycles=t)
# VII. control instructions
elif fmt == 7:
b = opcode
t = 0 if timing is None else timing.time_noop()
self.asm.emit(b, cycles=t)
# VIII. immediate instructions
elif fmt == 8:
b = opcode | arg1
t = 0 if timing is None else timing.time_noop()
self.asm.emit(b, arg2, cycles=t)
elif fmt == 81 or fmt == 82:
b = opcode
t = 0 if timing is None else timing.time_noop()
self.asm.emit(b, arg1, cycles=t)
if fmt == 82:
self.asm.symbols.WP = arg1 # change workspace
# IX. extended operations; multiply and divide
elif fmt == 9:
ts, s, sa = arg1
r = arg2
b = opcode | r << 6 | ts << 4 | s
t = 0 if timing is None else timing.time_1op(ts, s, sa)
self.asm.emit(b, sa, cycles=t)
# TMS99000
elif fmt == 101: # AM/SM
ts, s, sa = arg1
td, d, da = arg2
b = td << 10 | d << 6 | ts << 4 | s
self.asm.emit(opcode, b, sa, da)
elif fmt == 103: # T*B
ts, s, sa = arg1
if ts == 3:
raise AsmError('Indirect autoincrement addressing not defined for T*MB mnemonics')
disp = arg2
b = disp << 6 | ts << 4 | s
self.asm.emit(opcode, b, sa)
elif fmt == 106: # BIND
ts, s, sa = arg1
b = opcode | ts << 4 | s
self.asm.emit(b, sa)
elif fmt == 108: # BLSK
w = arg1
imm = arg2
b1 = opcode | w
b2 = imm
self.asm.emit(b1, b2)
elif fmt == 109: # S*AM
ts, s, sa = arg1
scnt = arg2
b = scnt << 6 | ts << 4 | s
self.asm.emit(opcode, b, sa)
else:
raise AsmError('Invalid opcode format ' + str(fmt))
class Directives:
ignores = ['', 'PSEG', 'PEND', 'CSEG', 'CEND', 'DSEG', 'DEND', 'UNL', 'LIST', 'PAGE', 'TITL', 'LOAD', 'SREF']
@staticmethod
def DEF(asm, label, ops):
if asm.symbols.pass_no == 1:
asm.process_label(label)
else:
for op in ops:
asm.symbols.add_def(op[:6] if asm.parser.strict else op)
@staticmethod
def REF(asm, label, ops):
if asm.symbols.pass_no != 1:
return
for op in ops:
asm.symbols.add_ref(op[:6] if asm.parser.strict else op)
@staticmethod
def EQU(asm, label, ops):
if asm.symbols.pass_no != 1:
value = asm.symbols.get_symbol(label)
asm.listing.add(asm.symbols.LC, text1='', text2=value)
return
Directives.check_ops(asm, ops, min_count=1, max_count=1, warning_only=True)
if not label:
raise AsmError('Missing label')
value = asm.parser.expression(ops[0], well_defined=True)
asm.symbols.add_symbol(label, value, equ=Symbols.EQU, lino=asm.parser.lino, filename=asm.parser.filename)
@staticmethod
def WEQU(asm, label, ops):
"""weak EQU, may be redefined"""
if asm.symbols.pass_no != 1:
value = asm.symbols.get_symbol(label)
asm.listing.add(asm.symbols.LC, text1='', text2=value)
return
Directives.check_ops(asm, ops, min_count=1, max_count=1, warning_only=True)
if not label:
raise AsmError('Missing label')
value = asm.parser.expression(ops[0], well_defined=True)
asm.symbols.add_symbol(label, value, equ=Symbols.WEQU, lino=asm.parser.lino, filename=asm.parser.filename)
@staticmethod
def REQU(asm, label, ops):
if asm.symbols.pass_no != 1:
try:
value = asm.symbols.registers[label]
except KeyError:
value = 0 # error already reported by pass 1
asm.listing.add(asm.symbols.LC, text1='', text2=value)
return
Directives.check_ops(asm, ops, min_count=1, max_count=1, warning_only=True)
if not label:
raise AsmError('Missing label')
value = asm.parser.register(ops[0], well_defined=True)
asm.symbols.add_register_alias(label, value)
@staticmethod
def DATA(asm, label, ops):
asm.even() # required for s# modifier
asm.process_label(label, tracked=True)
Directives.check_ops(asm, ops, min_count=1)
for op in ops:
word = asm.parser.expression(op)
asm.word(word)
@staticmethod
def BYTE(asm, label, ops):
asm.process_label(label, tracked=True)
Directives.check_ops(asm, ops, min_count=1)
for op in ops:
byte_ = asm.parser.expression(op)
asm.byte(byte_)
@staticmethod
def TEXT(asm, label, ops):
asm.process_label(label, tracked=True)
Directives.check_ops(asm, ops, min_count=1)
for op in ops:
text = asm.parser.text(op)
for char_ in text:
asm.byte(ord(char_))
@staticmethod
def STRI(asm, label, ops):
asm.process_label(label, tracked=True)
Directives.check_ops(asm, ops, min_count=1)
text = ''.join(asm.parser.text(op) for op in ops)
asm.byte(len(text))
for char_ in text:
asm.byte(ord(char_))
@staticmethod
def FLOA(asm, label, ops):
asm.process_label(label, tracked=True)
Directives.check_ops(asm, ops, min_count=1)
for op in ops:
bytes_ = asm.parser.radix100(op)
for b in bytes_:
asm.byte(b)
@staticmethod
def BSS(asm, label, ops):
Directives.check_ops(asm, ops, min_count=1, max_count=1, warning_only=True)
asm.process_label(label, tracked=True)
size = asm.parser.value(ops[0])
asm.block(size)
@staticmethod
def BES(asm, label, ops):
Directives.check_ops(asm, ops, min_count=1, max_count=1, warning_only=True)
size = asm.parser.value(ops[0])
asm.block(size, offset=size)
asm.process_label(label, tracked=True)
@staticmethod
def EVEN(asm, label, ops):
asm.even()
asm.process_label(label) # differs from E/A manual!
@staticmethod
def AORG(asm, label, ops):
Directives.check_ops(asm, ops, max_count=2)
base = asm.parser.value(ops[0]) if ops else None
if len(ops) > 1:
raise AsmError('Cannot use bank with AORG directive (deprecated use)')
asm.org(base, reloc=False)
asm.process_label(label)
@staticmethod
def RORG(asm, label, ops):
Directives.check_ops(asm, ops, max_count=1)
base = asm.parser.value(ops[0]) if ops else None
asm.org(base, reloc=True)
asm.process_label(label)
@staticmethod
def DORG(asm, label, ops):
Directives.check_ops(asm, ops, max_count=1)
base = asm.parser.expression(ops[0], well_defined=True)
reloc = isinstance(base, Address) and base.reloc
asm.org(Address.val(base), dummy=True, reloc=reloc)
asm.process_label(label)
@staticmethod
def XORG(asm, label, ops):
Directives.check_ops(asm, ops, min_count=1, max_count=1)
asm.process_label(label, real_LC=True)
base = asm.parser.value(ops[0])
asm.org(base, reloc=False, xorg=True)
@staticmethod
def BANK(asm, label, ops):
Directives.check_ops(asm, ops, min_count=1, max_count=2)
bank = asm.parser.bank(ops[0])
if bank > Symbols.BANK_ALL or (bank == Symbols.BANK_ALL and not ops[0].isalpha()):
raise AsmError(f'Bank number too large, must be less than { Symbols.BANK_ALL }')
base = asm.symbols.switch_bank(bank, asm.parser.expression(ops[1], well_defined=True) if len(ops) > 1 else None)
asm.org(base, bank=bank)
asm.process_label(label, real_LC=True)
@staticmethod
def COPY(asm, label, ops):
if asm.parser.symbols.pass_no == 2:
return
asm.process_label(label)
Directives.check_ops(asm, ops, min_count=1, max_count=1)
filename = asm.parser.get_filename(ops[0])
asm.parser.open(filename=filename)
@staticmethod
def END(asm, label, ops):
Directives.check_ops(asm, ops, max_count=1)
asm.process_label(label)
if ops and asm.symbols.pass_no > 1:
asm.program.set_entry(asm.symbols.get_symbol(ops[0][:6] if asm.parser.strict else ops[0]))
asm.parser.stop()
@staticmethod
def IDT(asm, label, ops):
if asm.symbols.pass_no > 1:
return
Directives.check_ops(asm, ops, max_count=1)
asm.process_label(label)
text = asm.parser.text(ops[0]) if ops else ' '
asm.program.set_name(text[:8])
@staticmethod
def SAVE(asm, label, ops):
if asm.symbols.pass_no < 2:
return
Directives.check_ops(asm, ops, min_count=2, max_count=2)
try:
first = asm.parser.expression(ops[0]) if ops[0] else None
last = asm.parser.expression(ops[1]) if ops[1] else None
except IndexError:
raise AsmError('Invalid arguments')
if isinstance(first, Reference) or isinstance(last, Reference):
raise AsmError('Invalid arguments')
asm.program.saves.append((first, last))
@staticmethod
def DXOP(asm, label, ops):
if asm.symbols.pass_no != 1:
return
Directives.check_ops(asm, ops, min_count=2, max_count=2)
asm.process_label(label)
try:
mode = asm.parser.expression(ops[1], well_defined=True)
asm.symbols.add_XOP(ops[0], str(mode))
except IndexError:
raise AsmError('Invalid arguments')
@staticmethod
def BCOPY(asm, label, ops):
"""extension: include binary file as BYTE stream"""
Directives.check_ops(asm, ops, min_count=1, max_count=1)
asm.process_label(label)
# also process in pass 2, since BCOPY includes no source!
filename = asm.parser.get_filename(ops[0])
path = asm.parser.find(filename)
try:
with open(path, 'rb') as f:
bs = f.read()
for b in bs:
asm.byte(b)
except IOError as e:
raise AsmError(e)
@staticmethod
def AUTO(asm, label, ops):
"""place auto-generated constants here"""
if asm.symbols.pass_no == 1 and asm.symbols.bank == Symbols.BANK_ALL:
raise AsmError('Directive AUTO cannot be placed in shared bank area')
asm.process_label(label)
asm.auto_constants()
@staticmethod
def check_ops(asm, ops, min_count=None, max_count=None, warning_only=False):
if min_count and len(ops) < min_count:
raise AsmError('Missing operand(s)')
if max_count and len(ops) > max_count:
if warning_only:
asm.console.warn('Ignoring extra operands')
elif asm.symbols.pass_no == 1:
raise AsmError('Bad operand count')
@staticmethod
def process(asm, label, mnemonic, operands):
if mnemonic in Directives.ignores:
asm.process_label(label)
return True
try:
fn = getattr(Directives, mnemonic)
except AttributeError:
return False
try:
fn(asm, label, operands)
except (IndexError, ValueError):
raise AsmError('Syntax error')
return True
# Symbol table
class Externals:
"""externally defined and referenced symbols"""
def __init__(self, target):
self.target = target
self.references = []
self.definitions = {}
self.builtins = { # const
'SCAN': 0x000e,
'PAD': 0x8300,
'GPLWS': 0x83e0,
'SOUND': 0x8400,
'VDPRD': 0x8800,
'VDPSTA': 0x8802,
'VDPWD': 0x8c00,
'VDPWA': 0x8c02,
'SPCHRD': 0x9000,
'SPCHWT': 0x9400,
'GRMRD': 0x9800,
'GRMRA': 0x9802,
'GRMWD': 0x9c00,
'GRMWA': 0x9c02,
}
class Symbols:
"""symbol table and line counter
Each symbol entry is a tuple (value, equ-kind, used).
Equ-kind symbols may be redefined, if EQU by the same value only.
Used tracks if a symbol has been used (True/False). If set to None, usage is not tracked.
Each program unit owns its own symbol table.
"""
g_unit_id = 0
# symbol kind
NONE = 0 # not an EQU symbol
EQU = 1 # EQU symbols (can be redefined by same value)
WEQU = 2 # weak EQU symbol (can be redefined by other value)
BANK_ALL = 411 # shared code
def __init__(self, externals, console, extdefs=(), add_registers=False, strict=False, target=None):
self.externals = externals
self.console = console
self.registers = {'R' + str(i): i for i in range(16)} if add_registers else {}
self.strict = strict
# symbols = {name: value, equ-kind, tracked-or-unused}
# tracked-or-used = None=don't care, True=unused, False=used
self.symbols = {n: (v, False, None) for n, v in self.registers.items()} # registers are _also_ just symbols
self.target = '_XAS99_' + (target or '')
self.symbols[self.target] = 1, Symbols.NONE, None
self.symbol_def_location = {} # symbol locations (lino, filename)
self.saved_LC = {True: 0, False: 0} # key == relocatable
self.xops = {}
self.locations = []
self.unit_id = Symbols.g_unit_id
Symbols.g_unit_id += 1
self.local_lid = 0
self.pass_no = 0
self.lidx = 0
self.autoconsts = set() # set of auto-generated constants
self.autos_defined = set()
self.autos_generated = set()
self.WP = None # current workspace pointer (for timing)
self.LC = None # current line counter
self.bank = None # current bank, or None
self.bank_LC = None # next LC for each bank
self.bank_base = 0 # base addr of BANK <addr>
self.segment_reloc = self.xorg_offset = self.pad_idx = None
self.add_env(extdefs)
self.reset()
def add_env(self, extdefs):
"""add external symbol definitions (-D)"""
for def_ in extdefs:
try:
name, value_str = def_.split('=')
value = Parser.external(value_str)
except ValueError:
name, value = def_, 1
self.add_symbol(name.upper(), Address(value, reloc=False))
def reset(self):
"""initialize some properties before each pass"""
self.LC = 0
self.WP = 0x83e0
self.bank = None
self.segment_reloc = True
self.xorg_offset = None
self.pad_idx = 0
self.reset_banks()
def reset_banks(self):
"""reset LC for all banks"""
self.bank_LC = {Symbols.BANK_ALL: 0} # next LC for each bank
def effective_LC(self):
"""compute effective LC inside and outside of XORG sections"""
return self.LC + (self.xorg_offset or 0)
def save_LC(self):
"""save current reloc or non-reloc LC"""
self.saved_LC[self.segment_reloc] = self.LC
def restore_LC(self, base, reloc, bank):
"""restore LC for new segment"""
self.xorg_offset = None
self.segment_reloc = reloc
if base is None:
self.LC = self.saved_LC[reloc]
elif bank is None:
self.LC = base
else:
self.LC = base + self.bank_LC.get(bank, 0) if reloc else base # bank is set in BANK dir
def valid(self, name):