-
Notifications
You must be signed in to change notification settings - Fork 41
/
applegpu.py
5995 lines (4744 loc) · 157 KB
/
applegpu.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
import fma
import os
from srgb import SRGB_TABLE
MAX_OPCODE_LEN = 12
ABS_FLAG = 'abs'
NEGATE_FLAG = 'neg'
SIGN_EXTEND_FLAG = 'sx'
CACHE_FLAG = 'cache'
DISCARD_FLAG = 'discard'
OPERAND_FLAGS = [
ABS_FLAG,
NEGATE_FLAG,
SIGN_EXTEND_FLAG,
CACHE_FLAG,
DISCARD_FLAG,
]
CACHE_HINT = '$'
SR_NAMES = {
0: 'threadgroup_position_in_grid.x',
1: 'threadgroup_position_in_grid.y',
2: 'threadgroup_position_in_grid.z',
4: 'threads_per_threadgroup.x',
5: 'threads_per_threadgroup.y',
6: 'threads_per_threadgroup.z',
8: 'dispatch_threads_per_threadgroup.x',
9: 'dispatch_threads_per_threadgroup.y',
10: 'dispatch_threads_per_threadgroup.z',
20: 'core_index',
21: 'vm_slot',
48: 'thread_position_in_threadgroup.x',
49: 'thread_position_in_threadgroup.y',
50: 'thread_position_in_threadgroup.z',
51: 'thread_index_in_threadgroup',
52: 'thread_index_in_simdgroup',
53: 'simdgroup_index_in_threadgroup',
56: 'active_thread_index_in_quadgroup',
58: 'active_thread_index_in_simdgroup',
# sample coverage mask in fragment shaders?
# MSAA lowering uses this
60: 'internal_coverage_mask',
# [sample_mask] input in Metal
124: 'input_coverage_mask',
# In fragment shaders. Invert for front facing
62: 'backfacing',
63: 'is_active_thread', # compare to zero for simd/quad_is_helper_thread
# 80, 81 also used for calculating fragcoord.xy
80: 'thread_position_in_grid.x',
81: 'thread_position_in_grid.y',
82: 'thread_position_in_grid.z',
124: 'input_sample_mask',
144: 'opfifo_cmd',
146: 'opfifo_data_l',
147: 'opfifo_data_h',
}
def opcode_to_number(opcode):
n = 0
for i, c in enumerate(opcode[:MAX_OPCODE_LEN]):
n |= c << (8 * i)
return n
def sign_extend(v, bits):
v &= (1 << bits) - 1
if v & (1 << (bits-1)):
v |= (-1 << bits)
return v
class Operand:
pass
def _add_flags(base, flags):
parts = [base]
for i in flags:
if 'APPLEGPU_CRYPTIC' in os.environ and i == 'cache':
parts[0] = CACHE_HINT + parts[0]
else:
parts.append(i)
return '.'.join(parts)
class RegisterTuple(Operand):
def __init__(self, registers, flags=None):
self.registers = list(registers)
if flags is None:
self.flags = []
else:
self.flags = list(flags)
def __str__(self):
return _add_flags('_'.join(map(str, self.registers)), self.flags)
def __repr__(self):
return 'RegisterTuple(%r)' % self.registers
def __repr__(self):
return 'RegisterTuple(%r)' % self.registers
def __getitem__(self, i):
return self.registers[i]
def get_with_flags(self, i):
r = self[i]
return r.__class__(r.n, flags=self.flags)
def __len__(self):
return len(self.registers)
def get_bit_size(self):
raise NotImplementedError('get_bit_size')
def set_thread(self, corestate, thread, result):
raise NotImplementedError('set_thread')
def get_thread(self, corestate, thread):
raise NotImplementedError('get_thread')
class Immediate(Operand):
# TODO: how should we handle bit_size?
def __init__(self, value, bit_size=16, flags=None):
self.value = value
self._bit_size = bit_size
if flags is None:
self.flags = []
else:
self.flags = list(flags)
def get_bit_size(self):
return self._bit_size
def get_thread(self, corestate, thread):
return self.value
def __str__(self):
return '.'.join([str(self.value)] + self.flags)
def __repr__(self):
if self.flags:
return 'Immediate(%r, flags=%r)' % (self.value, self.flags)
return 'Immediate(%r)' % self.value
class RelativeOffset(Immediate):
def __str__(self):
base = getattr(self, 'base', None)
if base is not None:
v = '0x%X' % (base + self.value,)
elif self.value >= 0:
v = 'pc+%d' % (self.value,)
else:
v = 'pc-%d' % (-self.value,)
return '.'.join([v] + self.flags)
def __repr__(self):
if self.flags:
return 'RelativeOffset(%r, flags=%r)' % (self.value, self.flags)
return 'RelativeOffset(%r)' % self.value
class Register(Operand):
def __init__(self, n, flags=None):
self.n = n
if flags is None:
self.flags = []
else:
self.flags = list(flags)
def _str(self, names):
return _add_flags(names[self.n], self.flags)
def _repr(self, clsname):
if self.flags:
return '%s(%d, flags=%r)' % (clsname, self.n, self.flags)
return '%s(%d)' % (clsname, self.n)
class BaseReg(Register):
pass
class Reg16(BaseReg):
def __str__(self):
return self._str(reg16_names)
def __repr__(self):
return self._repr('Reg16')
def get_bit_size(self):
return 16
def set_thread(self, corestate, thread, result):
corestate.set_reg16(self.n, thread, result)
def get_thread(self, corestate, thread):
return corestate.get_reg16(self.n, thread)
class Reg32(BaseReg):
def __str__(self):
return self._str(reg32_names)
def __repr__(self):
return self._repr('Reg32')
def get_bit_size(self):
return 32
def set_thread(self, corestate, thread, result):
corestate.set_reg32(self.n, thread, result)
def get_thread(self, corestate, thread):
return corestate.get_reg32(self.n, thread)
class Reg64(BaseReg):
def __str__(self):
return self._str(reg64_names)
def __repr__(self):
return self._repr('Reg64')
def get_bit_size(self):
return 64
def set_thread(self, corestate, thread, result):
corestate.set_reg64(self.n, thread, result)
def get_thread(self, corestate, thread):
return corestate.get_reg64(self.n, thread)
class BaseUReg(Register):
pass
class UReg16(BaseUReg):
def __str__(self):
return self._str(ureg16_names)
def __repr__(self):
return self._repr('UReg16')
def get_thread(self, corestate, thread):
return corestate.uniforms.get_reg16(self.n)
def get_bit_size(self):
return 16
class UReg32(BaseUReg):
def __str__(self):
return self._str(ureg32_names)
def __repr__(self):
return self._repr('UReg32')
def get_thread(self, corestate, thread):
return corestate.uniforms.get_reg32(self.n)
def get_bit_size(self):
return 32
class UReg64(BaseUReg):
def __str__(self):
return self._str(ureg64_names)
def __repr__(self):
return self._repr('UReg64')
def get_thread(self, corestate, thread):
return corestate.uniforms.get_reg64(self.n)
def get_bit_size(self):
return 64
class SReg32(Register):
def __str__(self):
name = 'sr%d' % (self.n)
if self.n in SR_NAMES:
name += ' (' + SR_NAMES[self.n] + ')'
return name
def __repr__(self):
return self._repr('SReg32')
def get_bit_size(self):
return 32
class TextureState(Register):
def __str__(self):
return 'ts%d' % (self.n)
def __repr__(self):
return self._repr('TextureState')
def get_bit_size(self):
return 32 # ?
class SamplerState(Register):
def __str__(self):
return 'ss%d' % (self.n)
def __repr__(self):
return self._repr('SamplerState')
def get_bit_size(self):
return 32 # ?
class CF(Register):
def __str__(self):
return 'cf%d' % (self.n)
def __repr__(self):
return self._repr('CF')
def get_bit_size(self):
return 32 # ?
ureg16_names = []
ureg32_names = []
ureg64_names = []
for _i in range(256):
ureg16_names.append('u%dl' % _i)
ureg16_names.append('u%dh' % _i)
ureg32_names.append('u%d' % _i)
ureg64_names.append('u%d_u%d' % (_i, _i + 1))
reg16_names = []
reg32_names = []
reg64_names = []
reg96_names = []
reg128_names = []
for _i in range(128):
reg16_names.append('r%dl' % _i)
reg16_names.append('r%dh' % _i)
reg32_names.append('r%d' % _i)
# TODO: limit? can cross r31-r32 boundary?
reg64_names.append('r%d_r%d' % (_i, _i + 1))
reg96_names.append('r%d_r%d_r%d' % (_i, _i + 1, _i + 2))
reg128_names.append('r%d_r%d_r%d_r%d' % (_i, _i + 1, _i + 2, _i + 3))
# TODO: is this the right number?
ts_names = []
ss_names = []
cf_names = []
for _i in range(256):
ts_names.append('ts%d' % _i)
ss_names.append('ss%d' % _i)
cf_names.append('cf%d' % _i)
registers_by_name = {}
for _namelist, _c in [
(reg16_names, Reg16),
(reg32_names, Reg32),
(reg64_names, Reg64),
(ureg16_names, UReg16),
(ureg32_names, UReg32),
(ureg64_names, UReg64),
(ts_names, TextureState),
(ss_names, SamplerState),
(cf_names, CF),
]:
for _i, _name in enumerate(_namelist):
registers_by_name[_name] = (_c, _i)
def try_parse_register(s):
flags = []
if s.startswith(CACHE_HINT):
s = s[1:]
flags.append(CACHE_FLAG)
parts = s.split('.')
if parts[0] not in registers_by_name:
return None
for i in parts[1:]:
if i not in OPERAND_FLAGS:
return None
flags.append(i)
c, n = registers_by_name[parts[0]]
return c(n, flags=flags)
def try_parse_register_tuple(s):
flags = []
if s.startswith(CACHE_HINT):
s = s[1:]
flags.append(CACHE_FLAG)
parts = s.split('.')
regs = [try_parse_register(i) for i in parts[0].split('_')]
if not all(isinstance(r, Reg32) for r in regs) and not all(isinstance(r, Reg16) for r in regs):
return None
if any(i.flags for i in regs):
return None
if not all(regs[i].n + 1 == regs[i+1].n for i in range(len(regs)-1)):
return None
for i in parts[1:]:
if i not in OPERAND_FLAGS:
return None
flags.append(i)
return RegisterTuple(regs, flags=flags)
SIMD_WIDTH = 32
class AsmInstruction:
def __init__(self, mnem, operands=None):
self.mnem = mnem
self.operands = list(operands)
def __str__(self):
operands = ', '.join(filter(None, (str(i) for i in self.operands)))
return self.mnem.ljust(16) + ' ' + operands
def __repr__(self):
return 'AsmInstruction(%r, %r)' % (self.mnem, self.operands)
class AddressSpace:
def __init__(self):
self.mappings = []
def map(self, address, size):
# TODO: check for overlap
self.mappings.append((address, [0] * size))
def set_byte(self, address, value):
for start, values in self.mappings:
if start < address and address - start < len(values):
values[address - start] = value
return
assert False, 'bad address %x' % address
def get_byte(self, address):
for start, values in self.mappings:
if start < address and address - start < len(values):
return values[address - start]
assert False, 'bad address %x' % address
def get_u16(self, address):
return self.get_byte(address) | (self.get_byte(address + 1) << 8)
def get_u32(self, address):
return self.get_u16(address) | (self.get_u16(address + 2) << 16)
class Uniforms:
def __init__(self):
self.reg16s = [0] * 256
def get_reg16(self, regid):
return self.reg16s[regid]
def set_reg32(self, regid, value):
self.reg16s[regid * 2] = value & 0xFFFF
self.reg16s[regid * 2 + 1] = (value >> 16) & 0xFFFF
def get_reg32(self, regid):
return self.reg16s[regid * 2] | (self.reg16s[regid * 2 + 1] << 16)
def get_reg64(self, regid):
return self.get_reg32(regid) | (self.get_reg32(regid + 1) << 32)
def set_reg64(self, regid, value):
self.set_reg32(regid, value & 0xFFFFFFFF)
self.set_reg32(regid + 1, (value >> 32) & 0xFFFFFFFF)
class CoreState:
def __init__(self, num_registers=8, uniforms=None, device_memory=None):
self.reg16s = [[0] * SIMD_WIDTH for i in range(num_registers * 2)]
self.pc = 0
self.exec = [True] * SIMD_WIDTH
if uniforms is None:
uniforms = Uniforms()
self.uniforms = uniforms
self.device_memory = device_memory
def get_reg16(self, regid, thread):
return self.reg16s[regid][thread]
def set_reg16(self, regid, thread, value):
self.reg16s[regid][thread] = value & 0xFFFF
def get_reg32(self, regid, thread):
return self.reg16s[regid * 2][thread] | (self.reg16s[regid * 2 + 1][thread] << 16)
def set_reg32(self, regid, thread, value):
self.reg16s[regid * 2][thread] = value & 0xFFFF
self.reg16s[regid * 2 + 1][thread] = (value >> 16) & 0xFFFF
def get_reg64(self, regid, thread):
return self.get_reg32(regid, thread) | (self.get_reg32(regid + 1, thread) << 32)
def set_reg64(self, regid, thread, value):
self.set_reg32(regid, thread, value & 0xFFFFFFFF)
self.set_reg32(regid + 1, thread, (value >> 32) & 0xFFFFFFFF)
class InstructionDesc:
documentation_skip = False
def __init__(self, name, size=2, length_bit_pos=15):
self.name = name
self.mask = 0
self.bits = 0
self.fields = []
self.ordered_operands = []
self.operands = {}
self.constants = []
self.merged_fields = []
self.fields_mask = 0
assert isinstance(size, (int, tuple))
self.sizes = (size, size) if isinstance(size, int) else size
self.length_bit_pos = length_bit_pos
def matches(self, instr):
instr = self.mask_instr(instr)
return (instr & self.mask) == self.bits
def add_raw_field(self, start, size, name):
# collision check
mask = ((1 << size) - 1) << start
assert (self.mask & mask) == 0, name
assert (self.fields_mask & mask) == 0
for _, _, existing_name in self.fields:
assert existing_name != name, name
self.fields_mask |= mask
self.fields.append((start, size, name))
def add_merged_field(self, name, subfields):
pairs = []
shift = 0
for start, size, subname in subfields:
self.add_raw_field(start, size, subname)
pairs.append((subname, shift))
shift += size
self.merged_fields.append((name, pairs))
def add_field(self, start, size, name):
self.add_merged_field(name, [(start, size, name)])
def add_suboperand(self, operand):
# a "suboperand" is an operand which does not appear in the operand list,
# but is used by other operands. currently unused.
for start, size, name in operand.fields:
self.add_field(start, size, name)
for name, subfields in operand.merged_fields:
self.add_merged_field(name, subfields)
self.operands[operand.name] = operand
def add_operand(self, operand):
self.add_suboperand(operand)
self.ordered_operands.append(operand)
def add_constant(self, start, size, value):
mask = (1 << size) - 1
assert (value & ~mask) == 0
assert (self.mask & (mask << start)) == 0
self.mask |= mask << start
self.bits |= value << start
self.constants.append((start, size, value))
def decode_raw_fields(self, instr):
instr = self.mask_instr(instr)
assert self.matches(instr)
fields = []
for start, size, name in self.fields:
fields.append((name, (instr >> start) & ((1 << size) - 1)))
return fields
def decode_remainder(self, instr):
instr = self.mask_instr(instr)
assert self.matches(instr)
instr &= ~self.mask
for start, size, name in self.fields:
instr &= ~(((1 << size) - 1) << start)
if self.sizes[0] != self.sizes[1]:
instr &= ~(1 << self.length_bit_pos)
return instr
def patch_raw_fields(self, encoded, fields):
lookup = {name: (start, size) for start, size, name in self.fields}
for name, value in fields.items():
start, size = lookup[name]
mask = (1 << size) - 1
assert (value & ~mask) == 0
encoded = (encoded & ~(mask << start)) | (value << start)
if self.sizes[0] != self.sizes[1]:
encoded &= ~(1 << self.length_bit_pos)
if (encoded & (0xFFFF << (self.sizes[0] * 8))) != 0:
# use long encoding
encoded |= (1 << self.length_bit_pos)
assert self.matches(encoded)
encoded = self.mask_instr(encoded)
return encoded
def encode_raw_fields(self, fields):
assert sorted(lookup.keys()) == sorted(name for start, size, name in self.fields)
return self.patch_raw_fields(self.bits, fields)
def patch_fields(self, encoded, fields):
mf_lookup = dict(self.merged_fields)
size_lookup = {name: size for start, size, name in self.fields}
raw_fields = {}
for name, value in fields.items():
for subname, shift in mf_lookup[name]:
mask = (1 << size_lookup[subname]) - 1
raw_fields[subname] = (value >> shift) & mask
return self.patch_raw_fields(encoded, raw_fields)
def encode_fields(self, fields):
if sorted(fields.keys()) != sorted(name for name, subfields in self.merged_fields):
print(sorted(fields.keys()))
print(sorted(name for name, subfields in self.merged_fields))
assert False
return self.patch_fields(self.bits, fields)
def to_bytes(self, instr):
return bytes((instr >> (i*8)) & 0xFF for i in range(self.decode_size(instr)))
def decode_fields(self, instr):
raw = dict(self.decode_raw_fields(instr))
fields = []
for name, subfields in self.merged_fields:
value = 0
for subname, shift in subfields:
value |= raw[subname] << shift
fields.append((name, value))
return fields
def decode_operands(self, instr):
instr = self.mask_instr(instr)
fields = dict(self.decode_fields(instr))
return self.fields_to_operands(fields)
def fields_to_operands(self, fields):
ordered_operands = []
for o in self.ordered_operands:
ordered_operands.append(o.decode(fields))
return ordered_operands
def decode_size(self, instr):
return self.sizes[(instr >> self.length_bit_pos) & 1]
def mask_instr(self, instr):
return instr & ((1 << (self.decode_size(instr) * 8)) - 1)
def decode_mnem(self, instr):
instr = self.mask_instr(instr)
assert self.matches(instr)
return self.fields_to_mnem(dict(self.decode_fields(instr)))
def fields_to_mnem_base(self, fields):
return self.name
def fields_to_mnem_suffix(self, fields):
return ''
def fields_to_mnem(self, fields):
return self.fields_to_mnem_base(fields) + self.fields_to_mnem_suffix(fields)
def map_to_alias(self, mnem, operands):
return mnem, operands
def disassemble(self, n, pc=None):
mnem = self.decode_mnem(n)
operands = self.decode_operands(n)
mnem, operands = self.map_to_alias(mnem, operands)
for operand in operands:
if isinstance(operand, RelativeOffset):
operand.base = pc
return AsmInstruction(mnem, operands)
def fields_for_mnem(self, mnem, operand_strings):
if self.name == mnem:
return {}
def rewrite_operands_strings(self, mnem, opstrs):
return opstrs
documentation_operands = []
def document_operand(cls):
documentation_operands.append(cls)
return cls
class OperandDesc:
def __init__(self, name=None):
self.name = name
self.fields = []
self.merged_fields = []
def add_field(self, start, size, name):
self.fields.append((start, size, name))
def add_merged_field(self, name, subfields):
self.merged_fields.append((name, subfields))
def decode(self, fields):
return '<TODO>'
def get_bit_size(self, fields):
r = self.decode(fields)
return r.get_bit_size()
def add_dest_hint_modifier(reg, bits):
if bits & 1:
reg.flags.append(CACHE_FLAG)
return reg
def add_hint_modifier(reg, bits):
if bits == 0b10:
reg.flags.append(CACHE_FLAG)
return reg
elif bits == 0b11:
reg.flags.append(DISCARD_FLAG)
return reg
else:
assert bits == 0b01
return reg
def decode_float_immediate(n):
sign = -1.0 if n & 0x80 else 1.0
e = (n & 0x70) >> 4
f = n & 0xF
if e == 0:
return sign * f / 64.0
else:
return sign * float(0x10 | f) * (2.0 ** (e - 7))
# okay, this is very lazy
float_immediate_lookup = {str(decode_float_immediate(i)): i for i in range(0x100)}
def add_float_modifier(r, modifier):
if modifier & 1:
r.flags.append(ABS_FLAG)
if modifier & 2:
r.flags.append(NEGATE_FLAG)
return r
class AbstractDstOperandDesc(OperandDesc):
def set_thread(self, fields, corestate, thread, result):
r = self.decode(fields)
r.set_thread(corestate, thread, result)
class AbstractSrcOperandDesc(OperandDesc):
def evaluate_thread(self, fields, corestate, thread):
r = self.decode(fields)
return r.get_thread(corestate, thread)
class ImplicitR0LDesc(AbstractDstOperandDesc):
def __init__(self, name):
super().__init__(name)
self.add_field(7, 1, self.name + 't')
def decode(self, fields):
flags = fields[self.name + 't']
r = Reg16(0)
return add_dest_hint_modifier(r, flags)
def encode_string(self, fields, opstr):
reg = try_parse_register(opstr)
if reg and isinstance(reg, Reg16) and reg.n == 0:
flags = 0
if CACHE_FLAG in reg.flags:
flags |= 1
fields[self.name + 't'] = flags
return
raise Exception('invalid ImplicitR0LDesc %r' % (opstr,))
@document_operand
class ALUDstDesc(AbstractDstOperandDesc):
def __init__(self, name, bit_off_ex):
super().__init__(name)
self.add_merged_field(self.name, [
(9, 6, self.name),
(bit_off_ex, 2, self.name + 'x')
])
self.add_field(7, 2, self.name + 't')
def _allow64(self):
return False
def _allow32(self):
return True
def _paired(self):
return False
def decode(self, fields):
flags = fields[self.name + 't']
value = fields[self.name]
if flags & 2 and self._allow32():
if (value & 1) and self._allow64():
assert not self._paired()
r = Reg64(value >> 1)
else:
if self._paired():
r = RegisterTuple(Reg32((value >> 1) + i) for i in range(2))
else:
r = Reg32(value >> 1)
else:
if self._paired():
r = RegisterTuple(Reg16(value + i) for i in range(2))
else:
r = Reg16(value)
return add_dest_hint_modifier(r, flags)
def encode(self, fields, operand):
if self._paired() and isinstance(operand, RegisterTuple):
# TODO: validate
operand = operand.get_with_flags(0)
flags = 0
value = 0
if isinstance(operand, BaseReg):
if isinstance(operand, Reg16):
value = operand.n
elif isinstance(operand, Reg32):
if not self._allow32():
print('WARNING: encoding invalid 32-bit register')
value = operand.n << 1
flags |= 2
else:
assert isinstance(operand, Reg64)
if not self._allow64():
print('WARNING: encoding invalid 64-bit register')
value = (operand.n << 1) | 1
flags |= 2
if CACHE_FLAG in operand.flags:
flags |= 1
else:
raise Exception('invalid ALUDstDesc %r' % (operand,))
fields[self.name + 't'] = flags
fields[self.name] = value
pseudocode = '''
{name}(value, flags, max_size=32):
cache_flag = flags & 1
if flags & 2 and value & 1 and max_size >= 64:
return Reg64Reference(value >> 1, cache=cache_flag)
elif flags & 2 and max_size >= 32:
return Reg32Reference(value >> 1, cache=cache_flag)
else:
return Reg16Reference(value, cache=cache_flag)
'''
def encode_string(self, fields, opstr):
if self._paired():
regs = try_parse_register_tuple(opstr)
if regs and len(regs) == 2:
return self.encode(fields, regs)
raise Exception('invalid paired ALUDstDesc %r' % (opstr,))
reg = try_parse_register(opstr)
if reg:
return self.encode(fields, reg)
raise Exception('invalid ALUDstDesc %r' % (opstr,))
class PairedALUDstDesc(ALUDstDesc):
# converts r0 <-> r0_r1 and r0h <-> r0h_r1l
def _paired(self):
return True
@document_operand
class ALUDst64Desc(ALUDstDesc):
pseudocode = '''
{name}(value, flags):
return ALUDst(value, flags, max_size=64)
'''
def _allow64(self):
return True
class ALUDst16Desc(ALUDstDesc):
pseudocode = '''
{name}(value, flags):
return ALUDst(value, flags, max_size=16)
'''
def _allow32(self):
return False
@document_operand
class FloatDstDesc(ALUDstDesc):
def __init__(self, name, bit_off_ex):
super().__init__(name, bit_off_ex)
self.add_field(6, 1, 'S')
# so far this is the same, but conceptually i'd like the destination to
# be responsible for converting the result to the correct size, which is
# a very different operation for floats.
pseudocode = '''
{name}(value, flags, saturating, max_size=32):
destination = ALUDst(value, flags, max_size=max_size)
if destination.thread_bit_size == 32:
wrapper = RoundToFloat32Wrapper(destination, flush_to_zero=True)
else:
wrapper = RoundToFloat16Wrapper(destination, flush_to_zero=False)
if saturating:
wrapper = SaturateRealWrapper(wrapper)
return wrapper
'''
@document_operand
class FloatDst16Desc(FloatDstDesc):
def _allow32(self):
return False
pseudocode = '''
{name}(value, flags, saturating):
return FloatDst(value, flags, saturating, max_size=16)
'''
@document_operand
class ALUSrcDesc(AbstractSrcOperandDesc):
"Zero-extended 16 or 32 bit source field"
def __init__(self, name, bit_off, bit_off_ex):
super().__init__(name)
self.add_merged_field(self.name, [
(bit_off, 6, self.name),
(bit_off_ex, 2, self.name + 'x')
])
self.add_field(bit_off + 6, self._type_size(), self.name + 't')
def _type_size(self):
return 4
def _allow32(self):
return True
def _allow64(self):
return False
def _paired(self):
return False
def decode_impl(self, fields, allow64):
flags = fields[self.name + 't']
value = fields[self.name]
return bitop_decode(flags, value, allow64)
def decode_immediate(self, fields, value):
return Immediate(value)
def decode(self, fields):
flags = fields[self.name + 't']
value = fields[self.name]
if flags == 0:
return self.decode_immediate(fields, value)
elif (flags & 0b1100) == 0b0100:
value |= (flags & 1) << 8
if flags & 2:
return UReg32(value >> 1)
else:
return UReg16(value)
elif (flags & 0b11) != 0: # in (0b0001, 0b0010, 0b0011):
if self._allow64() and (flags & 0b1100) == 0b1100:
assert (value & 1) == 0
assert not self._paired()
r = Reg64(value >> 1)
elif self._allow32() and (flags & 0b1100) in (0b1000, 0b1100):
# assert (value & 1) == 0
if self._paired():
r = RegisterTuple(Reg32((value >> 1) + i) for i in range(2))
else:
r = Reg32(value >> 1)
elif (flags & 0b1100) in (0b0000, 0b1000, 0b1100):
if self._paired():
r = RegisterTuple(Reg16(value + i) for i in range(2))
else:
r = Reg16(value)
else:
return
return add_hint_modifier(r, flags & 0b11)
else:
print('TODO: ' + format(flags, '04b'))
def encode(self, fields, operand):
if self._paired():