-
Notifications
You must be signed in to change notification settings - Fork 6
/
mkasm_aarch64.py
executable file
·4034 lines (3347 loc) · 133 KB
/
mkasm_aarch64.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
# -*- coding: utf-8 -*-
import os
import re
import sys
import textwrap
from typing import cast
from typing import Literal
from typing import Iterator
from typing import NamedTuple
from enum import StrEnum
from functools import cached_property
from collections import OrderedDict
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
DOC_FILE = 'isa_docs/ISA_A64_xml_A_profile-2023-03_OPT/onebigfile.xml'
LOG_QUIET = '-q' in sys.argv
MAX_TEXT_WIDTH = 80
MAX_LINE_WIDTH = 120
class CodeGen:
def __init__(self):
self.buf = []
self.level = 0
@property
def src(self) -> str:
return '\n'.join(self.buf)
def line(self, src: str = ''):
self.buf.append(' ' * (self.level * 4) + src)
def dedent(self):
self.level -= 1
def indent(self):
self.level += 1
def status(*args):
if not LOG_QUIET:
sys.stdout.write('\x1b[#F\x1b[K')
print(*args)
if not LOG_QUIET:
print()
status('* Preparing ...')
### ---------- Instruction Encoding Classes ---------- ###
class HardcodedExtend(NamedTuple):
ext: str
rsp: str
sym: str
reg: list[str]
def __str__(self) -> str:
return '%s == %s ? %s : %s' % (' | '.join(self.reg), self.rsp, self.sym, self.ext)
class Account:
name: str
desc: str
mult: int
divs: int
altr: bool
defv: str | HardcodedExtend
valr: tuple[int, int] | None
def __init__(self,
name: str,
desc: str,
mult: int,
idiv: int,
altr: bool,
defv: str | HardcodedExtend,
valr: tuple[int, int] | None,
):
self.name = name
self.desc = desc
self.mult = mult
self.divs = idiv
self.altr = altr
self.defv = defv
self.valr = valr
def __repr__(self) -> str:
return '%s %s%s%s%s%s%s' % (
self.name,
self.desc,
'' if not self.altr else ' (altr)',
'' if not self.defv else ' (default = %s)' % self.defv,
'' if not self.valr else ' (range = [%d, %d])' % self.valr,
'' if self.mult == 1 else ' (multiply = %d)' % self.mult,
'' if self.divs == 1 else ' (scale = %d)' % self.divs,
)
class Definition(Account):
refs: list[str]
bits: dict[str, set[str]]
def __init__(self,
name: str,
desc: str,
mult: int,
divs: int,
altr: bool,
defv: str | HardcodedExtend,
valr: tuple[int, int] | None,
refs: list[str],
bits: dict[str, set[str]],
):
super().__init__(name, desc, mult, divs, altr, defv, valr)
self.refs = refs
self.bits = bits
def __repr__(self) -> str:
return super().__repr__() + ' (=%s) [%s]' % (
':'.join(self.refs[::-1]),
' '.join('%s={%s}' % (k, ':'.join(sorted(v))) for k, v in self.bits.items()),
)
class Instruction:
bits: list[int | None]
refs: dict[str, tuple[int, int]]
def __init__(self, other: 'Instruction | None' = None):
if other is None:
self.refs = {}
self.bits = [None] * 32
else:
self.bits = other.bits[:]
self.refs = dict(other.refs)
def __repr__(self) -> str:
char = 0
mlen = 0
refs = []
bits = ['x' if v is None else str(v) for v in self.bits]
for v in self.refs:
mlen = max(mlen, len(v))
bits.extend(' ' * mlen)
bits.extend(' ')
for p, n in self.refs.values():
char += 1
bits[p:p + n] = [
'\x1b[3%dm%s\x1b[0m' % (char % 5 + 1, 'x' if v is None else v)
for v in self.bits[p:p + n]
]
vals = list(self.refs.items())
vals.sort(key = lambda x: x[1], reverse = True)
for i, (v, (p, n)) in enumerate(vals):
line = list(v[::-1].rjust(mlen + 34))
line[p + n // 2] = '┘'
line[p + n // 2 + 1:33] = '─' * (32 - p - n // 2)
for i in range(len(refs)):
refs[i][p + n // 2] = '│'
else:
refs.append(line)
return '\n'.join([
''.join(bits[::-1]),
*(''.join(v[::-1]) for v in refs),
])
@staticmethod
def _intersects(a1: int, b1: int, a2: int, b2: int) -> bool:
return a1 <= a2 <= b1 <= b2 or a2 <= a1 <= b2 <= b1
def _remove_bits(self, hibit: int, width: int) -> Iterator[str | None]:
for k, (i, w) in self.refs.items():
if w == width and i == hibit - width + 1:
yield k
elif self._intersects(i, i + w - 1, hibit - width + 1, hibit):
yield None
def update(self, boxes: list[Element]):
for box in boxes:
bits = box.findall('c')
name = box.attrib.get('name')
hibit = int(box.attrib['hibit'])
width = int(box.attrib.get('width', 1))
if name is not None:
self.refs[name] = (hibit - width + 1, width)
for i, item in enumerate(bits):
if item.text in {'0', '(0)', 'z', 'Z'}:
assert self.bits[hibit - i] != 1, 'bit confiction: 0'
self.bits[hibit - i] = 0
elif item.text in {'1', '(1)'}:
assert self.bits[hibit - i] != 0, 'bit confiction: 1'
self.bits[hibit - i] = 1
else:
assert box.attrib.get('usename') == '1' or item.text in {None, '', 'x', 'N'}, \
'invalid cell value: ' + repr(item.text)
class EncodingTabEntry(NamedTuple):
name: str
desc: str
form: str
file: str
func: str
args: list[str]
bits: Instruction
link: str | None = None
def __repr__(self) -> str:
return '\n'.join([
'Encoding %s (%s) {' % (self.name, ', '.join(self.args)),
' ' + self.desc if self.link is None else ' %s (alias of %s)' % (self.desc, self.link),
' form = ' + self.form,
' file = ' + self.file,
' func = ' + self.func,
*(' ' + v for v in repr(self.bits).splitlines()),
'}',
])
def derive(self, name: str, desc: str, file: str) -> 'EncodingTabEntry':
return EncodingTabEntry(
name = name,
desc = desc,
form = self.form,
file = file,
func = self.func,
args = self.args[:],
bits = Instruction(self.bits),
link = self.name,
)
class InstructionTabEntry(NamedTuple):
name: str
desc: str
data: Element
args: list[str]
base: Instruction
def __repr__(self) -> str:
return '\n'.join([
'Instruction %s (%s) {' % (self.name, ', '.join(self.args)),
' ' + self.desc,
*(' ' + v for v in repr(self.base).splitlines()),
'}',
])
class DescriptionTabEntry(NamedTuple):
brief : str
notes : list[str]
authored : list[str]
TEXT_ITEMS = {
'arm-defined-word',
'asm-code',
'binarynumber',
'hexnumber',
'instruction',
'para',
'syntax',
'value',
'xref',
}
def parse_bit(bit: str) -> int | None:
match bit:
case '0': return 0
case '1': return 1
case 'x': return None
case _ : raise AssertionError('invalid bit value: ' + repr(bit))
def break_line(text: str, indent: int, prefix: str = '') -> Iterator[str]:
yield from textwrap.wrap(
text = text,
width = MAX_TEXT_WIDTH - indent,
initial_indent = ' ' * indent + prefix,
subsequent_indent = ' ' * (indent + len(prefix)),
)
def layout_line(node: Element, indent: int, prefix: str = '') -> Iterator[str]:
text = []
head = node.text
if head:
text.extend(head.split())
for elem in node:
if elem.tag in TEXT_ITEMS:
if elem.text:
text.extend(elem.text.split())
elif elem.tag == 'sub':
assert elem.text, 'invalid subscript'
text.append('_')
text.extend(elem.text.split())
elif elem.tag == 'sup':
assert elem.text, 'invalid superscript'
text.append('^')
text.extend(elem.text.split())
elif elem.tag == 'list':
yield from break_line(' '.join(text), indent, prefix)
yield ''
yield from layout_element(elem, indent)
text.clear()
elif elem.tag == 'image':
yield from break_line(' '.join(text), indent, prefix)
yield ' ' * indent + '[image:%s]' % os.path.join(os.path.dirname(DOC_FILE), elem.attrib['file'])
yield ' ' * indent + elem.attrib['label']
text.clear()
else:
raise RuntimeError('not a renderable element: ' + repr(elem.tag))
if elem.tail:
text.extend(elem.tail.split())
if text:
yield from break_line(' '.join(text), indent, prefix)
def layout_element(node: Element, indent: int = 0) -> Iterator[str]:
match node.tag:
case 'para':
yield from layout_line(node, indent)
yield ''
case 'list':
tail = False
kind = node.attrib['type']
if kind != 'unordered':
raise RuntimeError('unsupported list type: ' + repr(kind))
for item in node.findall('listitem'):
content = item.find('content')
assert content is not None, 'missing list item content'
for line in layout_line(content, indent + 4, '* '):
tail = bool(line.strip())
yield line
if tail:
yield ''
case 'note':
tail = False
size = len(node)
if size:
yield ' ' * indent + 'NOTE: '
for elem in node:
for line in layout_element(elem, 4):
tail = bool(line.strip())
yield line
if tail:
yield ''
case 'table':
tgroup = node.find('tgroup')
assert tgroup is not None, 'invalid table'
cols, rows = int(tgroup.attrib['cols']), []
thead, tbody = tgroup.find('thead'), tgroup.find('tbody')
assert thead is not None and tbody is not None, 'invalid table element'
rr = thead.findall('row')
assert len(rr) == 1, 'invalid table rows'
hdr = rr[0].findall('entry')
rows.append([x.text or '' for x in hdr])
assert len(hdr) == cols, 'invalid table header'
for row in tbody.findall('row'):
ents = row.findall('entry')
rows.append([x.text or '' for x in ents])
assert len(ents) == cols, 'invalid table body'
maxw = list(max(map(len, v)) for v in zip(*rows))
rows = [[(c.ljust if i else c.center)(w, ' ') for c, w in zip(r, maxw)] for i, r in enumerate(rows)]
rows.append([])
rows.insert(0, [])
rows.insert(len(rr) + 1, [])
for row in rows:
if row:
yield ' ' * indent + ' | %s |' % ' | '.join(row)
else:
yield ' ' * indent + ' +-%s-+' % '-+-'.join('-' * w for w in maxw)
else:
yield ''
case tag:
raise RuntimeError('unrecognized tag ' + repr(tag))
def layout_content(node: Element) -> Iterator[str]:
if node.text:
yield from break_line(' '.join(node.text.split()), 0)
for elem in node:
yield from layout_element(elem)
cc = CodeGen()
cc.line('// Code generated by "mkasm_aarch64.py", DO NOT EDIT.')
cc.line()
cc.line('package aarch64')
cc.line()
iidtab = dict[str, str]()
enctab = dict[str, EncodingTabEntry]()
destab = dict[str, DescriptionTabEntry]()
instab = dict[str, InstructionTabEntry]()
isadocs = ElementTree.parse(os.path.join(os.path.dirname(__file__), DOC_FILE)).getroot()
parent_tab = { c: p for p in isadocs.iter() for c in p }
for isect in isadocs.findall('.//instructionsection'):
iid = isect.attrib['id']
desc = isect.find('desc')
assert desc is not None, 'missing description for ' + repr(iid)
status('* Document:', iid)
brief = desc.find('brief')
notes = desc.find('encodingnotes')
detail = desc.find('authored') or desc.find('description')
assert brief is not None, 'missing brief for ' + repr(iid)
destab[iid] = DescriptionTabEntry(
brief = ' '.join(layout_content(brief)),
notes = list(layout_content(notes)) if notes else [],
authored = list(layout_content(detail)) if detail else [],
)
for enc in isect.findall('.//encoding'):
key = enc.attrib['name']
val = iidtab.get(key)
if val and val != iid:
raise RuntimeError('encoding IID confliction: %s=%s:%s' % (key, val, iid))
else:
iidtab[key] = iid
for iclass in sorted(isadocs.findall('.//encodingindex/iclass_sect'), key = lambda x: x.attrib['id']):
name = iclass.attrib['id']
desc = iclass.attrib['title']
itab = iclass.find('instructiontable')
# TODO: support SVE and SME instructions sometime in the future
if name.startswith('sve') or name.startswith('mortlach'):
continue
assert itab is not None, 'missing instruction table for ' + name
assert itab.attrib['iclass'] == name, 'wrong instruction table iclass for ' + name
status('* Instruction Class:', name)
bits = Instruction()
bits.update(iclass.findall('regdiagram/box'))
vals = bits.bits[:]
cond = set[tuple[str, str, str]]()
argv = sorted(bits.refs.items(), key = lambda x: x[1], reverse = True)
args = [v for v, _ in argv]
for dc in iclass.findall('decode_constraints/decode_constraint'):
cond.add((dc.attrib['name'], dc.attrib['op'], dc.attrib['val']))
for p, n in bits.refs.values():
vals[p:p + n] = [0] * n
instab[name] = InstructionTabEntry(
name = name,
desc = desc,
data = itab,
args = args,
base = bits,
)
cc.line('// %s: %s' % (name, desc))
cc.line('func %s(%s uint32) uint32 {' % (name, ', '.join(args)))
cc.indent()
for key, op, val in sorted(cond):
assert op == '!=', 'decode constraint is not implemented: %s %s %s' % (key, op, val)
cc.line('if %s == 0b%s {' % (key, val))
cc.indent()
cc.line('panic("%s: decode constraint is not satisfied: %s %s %s")' % (name, key, op, val))
cc.dedent()
cc.line('}')
assert None not in vals, 'unset bit in %s: %r' % (name, vals)
cc.line('ret := uint32(0x%08x)' % int(''.join(map(str, vals))[::-1], 2))
for th, (p, n) in argv:
if p == 0:
cc.line('ret |= %s & %s' % (th, hex((1 << n) - 1)))
else:
cc.line('ret |= (%s & %s) << %d' % (th, hex((1 << n) - 1), p))
cc.line('return ret;')
cc.dedent()
cc.line('}')
cc.line()
with open('arch/aarch64/encodings.go', 'w') as fp:
fp.write('\n'.join(cc.buf))
for name, entry in sorted(instab.items(), key = lambda v: v[0]):
keys = []
itab = entry.data
for th in itab.findall('thead/tr[@id="heading2"]/th[@class="bitfields"]'):
assert th.text, 'missing field name for ' + name
keys.append(th.text)
for th in itab.findall('tbody/tr[@class="instructiontable"]'):
if th.attrib.get('undef') != '1':
encname = th.attrib['encname']
iformfile = th.attrib['iformfile']
iformname = th.find('td[@class="iformname"]')
bitfields = th.findall('td[@class="bitfield"]')
assert iformfile, 'missing iform files for ' + name
assert iformname is not None, 'missing iform names for ' + name
assert len(bitfields) == len(keys), 'mismatched bitfields for %s.%s' % (name, encname)
desc = iformname.text
form = iformname.attrib['iformid']
assert desc and form, 'missing form or description for %s.%s' % (name, encname)
bits = []
instr = Instruction(entry.base)
for field in bitfields:
if not field.text or field.text.startswith('!='):
bits.append(None)
else:
bits.append(list(map(parse_bit, field.text[::-1])))
for key, req in zip(keys, bits):
if req is not None:
p, n = instr.refs[key]
assert len(req) == n, 'mismatched bits for %s.%s.%s' % (name, encname, key)
instr.bits[p:p + n] = req
enc = EncodingTabEntry(
name = encname,
desc = desc,
form = form,
file = iformfile,
func = name,
args = entry.args,
bits = instr,
)
assert encname not in enctab, 'duplicated encoding name %s.%s' % (name, encname)
status('* Encoding Table Entry: %s.%s' % (name, encname))
enctab[encname] = enc
for node in sorted(isadocs.findall('.//instructionsection[@type="alias"]'), key = lambda x: x.attrib['id']):
to = node.find('aliasto')
hdr = node.find('heading')
assert to is not None, 'invalid alias section'
assert hdr is not None and hdr.text, 'invalid alias section'
iclass = ''
refiform = to.attrib['refiform']
iformfile = parent_tab[node].attrib['file']
for vv in node.findall('docvars/docvar'):
if vv.attrib['key'] == 'instr-class':
iclass = vv.attrib['value']
break
# TODO: support SVE and SME instructions sometime in the future
if iclass.startswith('sve') or iclass.startswith('mortlach'):
continue
for cls in node.findall('classes/iclass'):
encs = cls.findall('encoding')
bits = cls.findall('regdiagram/box')
for enc in encs:
parent = None
encname = enc.attrib['name']
asmtmpl = enc.findall('equivalent_to/asmtemplate/a')
for equ in asmtmpl:
href = equ.attrib.get('href', '')
vals = href.split('#')
if len(vals) == 2 and vals[0] == refiform:
parent = enctab.get(vals[1])
break
if parent is not None:
form = parent.derive(encname, hdr.text, iformfile)
form.bits.update(bits)
enctab[encname] = form
### ---------- Instruction Assembly Template ---------- ###
class Mop(StrEnum):
LSL = 'lsl'
LSR = 'lsr'
ASR = 'asr'
ROR = 'ror'
MSL = 'msl'
UXTB = 'uxtb'
UXTH = 'uxth'
UXTW = 'uxtw'
UXTX = 'uxtx'
SXTB = 'sxtb'
SXTH = 'sxth'
SXTW = 'sxtw'
SXTX = 'sxtx'
class Sym(StrEnum):
CSYNC = 'CSYNC'
DSYNC = 'DSYNC'
RCTX = 'RCTX'
X16 = 'X16'
PRFOP = 'sa_prfop'
RPRFOP = 'sa_rprfop'
OPTION = 'sa_option'
OPTION_NXS = 'sa_option_1'
AT_OPTION = 'sa_at_op'
BRB_OPTION = 'sa_brb_op'
DC_OPTION = 'sa_dc_op'
IC_OPTION = 'sa_ic_op'
SME_OPTION = 'sa_sme_option'
TLBI_OPTION = 'sa_tlbi_op'
TLBIP_OPTION = 'sa_tlbip_op'
PSTATE_FIELD = 'sa_pstatefield'
SYSREG = 'sa_systemreg'
TARGETS = 'sa_targets'
class Tag(str):
@cached_property
def name(self) -> str:
return self + ''
def __str__(self) -> str:
return '=' + self
def __repr__(self) -> str:
return 'Tag(%s)' % super().__repr__()
class Imm(str):
@cached_property
def name(self) -> str:
return self + ''
def __str__(self) -> str:
return '#' + self
def __repr__(self) -> str:
return 'Imm(%s)' % super().__repr__()
class Lit:
ty : type
val : object
def __init__(self, v: object):
if type(v) not in {int, float}:
raise TypeError('invalid literal valu: ' + repr(v))
else:
self.ty, self.val = type(v), v
def __str__(self) -> str:
return '#%s' % self.val
def __repr__(self) -> str:
return 'Lit(%s: %s)' % (self.val, self.ty)
class Reg(NamedTuple):
name: str
incr: bool = False
altr: str | None = None
size: str | None = None
mode: str | Tag | None = None
vidx: Imm | Lit | None = None
def __str__(self) -> str:
if self.size is not None:
assert not self.incr
assert self.altr is None
assert self.mode is None
assert self.vidx is None
return '%s[%s]' % (self.size, self.name)
elif self.mode is not None and self.vidx is not None:
assert not self.incr
assert self.altr is None
return '%s.%s[%s]' % (self.name, self.mode, self.vidx)
elif self.mode is not None:
assert not self.incr
assert self.altr is None
return '%s.%s' % (self.name, self.mode)
elif self.altr is not None:
assert not self.incr
assert self.vidx is None
return '(%s|%s)' % (self.name, self.altr)
elif self.incr:
return self.name + '!'
else:
return self.name
class Vec(NamedTuple):
mode: str | Tag
regs: list[str]
vidx: Imm | Lit | None = None
def __str__(self) -> str:
return '{ %s }.%s%s' % (
', '.join(self.regs),
self.mode,
'' if self.vidx is None else '[%s]' % self.vidx
)
class Mod(NamedTuple):
mod: str | Mop
imm: tuple[Imm | Lit, bool] | None = None
def name(self) -> str:
if isinstance(self.mod, str):
return self.mod
else:
return self.mod.name
def __str__(self) -> str:
if self.imm is None:
return self.name()
elif not self.imm[1]:
return '%s %s' % (self.name(), self.imm[0])
else:
return '%s {%s}' % (self.name(), self.imm[0])
class Mem(NamedTuple):
base : Reg
offs : tuple[Imm | Reg | Lit, bool] | None = None
index : Literal['pre', 'post', 'post-reg'] | None = None
extend : tuple[Mod, bool] | None = None
def __str__(self) -> str:
ret = []
ret.append('[')
ret.append(self.base)
if self.offs and self.index not in {'post', 'post-reg'}:
v, o = self.offs
ret.append('%s, %s%s' % ('{' if o else '', str(v), '}' if o else ''))
if self.extend:
v, o = self.extend
ret.append('%s, %s%s' % ('{' if o else '', str(v), '}' if o else ''))
match self.index:
case 'pre':
ret.append(']!')
case 'post' | 'post-reg':
assert self.offs, 'missing index for post index'
v, o = self.offs
ret.append(']%s+%s%s' % ('{' if o else '', str(v), '}' if o else ''))
case v:
ret.append(']')
assert v is None
return ''.join(
str(v)
for v in ret
)
class Seq(NamedTuple):
req: list[Reg | Vec | Mem | Mod | Imm | Lit | Sym]
opt: list[Reg | Vec | Mem | Mod | Imm | Lit | Sym]
def __str__(self) -> str:
ret = []
pfx = '{'
if self.req:
pfx = '{, '
ret.extend('%s%s' % (', ' if i else '', str(v)) for i, v in enumerate(self.req))
if self.opt:
ret.append(pfx)
ret.extend('%s%s' % (', ' if i else '', str(v)) for i, v in enumerate(self.opt))
ret.append('}')
if not ret:
return ''
else:
return ''.join(ret)
class Instr(NamedTuple):
mnemonic: str
operands: Seq
modifier: str | None
def __str__(self) -> str:
return ''.join([
self.mnemonic,
'{%s}' % self.modifier if self.modifier else '',
' ' if self.operands.req or self.operands.opt else '',
str(self.operands)
])
class Token(NamedTuple):
name: str
text: str
def __repr__(self) -> str:
return '\x1b[31m{%s}\x1b[0m' % self.name
@classmethod
def parse(cls, item: Element) -> 'Token':
return cls(
text = item.text or '',
name = item.attrib['link'],
)
class AsmTemplate:
pos: int
buf: list[str | Token]
modops = {
v.name
for v in Mop
}
symtab = {
Sym.CSYNC: (
'CSYNC option',
['CSYNC'],
),
Sym.DSYNC: (
'DSYNC option',
['DSYNC'],
),
Sym.RCTX: (
'RCTX option',
['RCTX'],
),
Sym.X16: (
'register X16',
['X16'],
),
Sym.PRFOP: (
'prefetch option',
['sa_prfop', '|', '#', 'sa_imm5']
),
Sym.RPRFOP: (
'range prefetch option',
['sa_rprfop', '|', '#', 'sa_imm6'],
),
Sym.OPTION: (
'barrier option',
['sa_option', '|', '#', 'sa_imm'],
),
Sym.OPTION_NXS: (
'barrier option nXS',
['sa_option_1', 'nXS'],
),
Sym.AT_OPTION: (
'address translation options',
['sa_at_op'],
),
Sym.BRB_OPTION: (
'branch record buffer options',
['sa_brb_op'],
),
Sym.DC_OPTION: (
'data cache options',
['sa_dc_op'],
),
Sym.IC_OPTION: (
'instruction cache options',
['sa_ic_op'],
),
Sym.SME_OPTION: (
'streaming SVE and SME options',
['sa_option'],
),
Sym.TLBI_OPTION: (
'TLB invalidate options',
['sa_tlbi_op'],
),
Sym.TLBIP_OPTION: (
'TLB invalidate pair options',
['sa_tlbip_op'],
),
Sym.PSTATE_FIELD: (
'MSR PState fields',
['sa_pstatefield'],
),
Sym.SYSREG: (
'system register',
['sa_systemreg', '|', 'S', 'sa_op0', '_', 'sa_op1', '_', 'sa_cn', '_', 'sa_cm', '_', 'sa_op2'],
),
Sym.TARGETS: (
'branch targets option',
['sa_targets'],
),
}
for v in Sym:
assert v in symtab, 'undefined symbol: ' + str(v)
amounts = {
'sa_amount',
'sa_amount_1',
'sa_amount_2',
'sa_amount_3',
'sa_amount_4',
'sa_shift',
'sa_shift_1',
'sa_shift_2',
'sa_shift_3',
}
modifiers = {
'sa_shift',
'sa_extend',
'sa_extend_1',
}
registers = {
'sa_d',
'sa_m',
'sa_n',
'sa_t',
}
immediates = {
'sa_imm',
'sa_imm_1',
'sa_imm_2',
'sa_imm_3',
}
predefined = {
tok[0]
for _, tok in symtab.values()
}
def __init__(self, tok: list[str | Token]):
self.pos = 0
self.buf = tok
@property
def eof(self) -> bool:
return self.pos >= len(self.buf)
@property
def tok(self) -> str | Token:
if self.eof:
raise SyntaxError('unexpected EOF')
else:
return self.buf[self.pos]
@staticmethod
def _isint(v: str) -> bool:
try:
int(v)
except ValueError:
return False
else:
return True
def next(self) -> str | Token:
ret = self.tok
self.pos += 1
return ret
def must(self, tok: str):
if self.next() != tok:
raise SyntaxError('"%s" expected' % tok)
def skip(self, tok: str) -> bool:
if self.eof or self.buf[self.pos] != tok:
return False
else:
self.pos += 1
return True
def dsym(self, name: str) -> Sym:
tok = []