This repository has been archived by the owner on Jun 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
octogon.py
1464 lines (1214 loc) · 48.6 KB
/
octogon.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 argparse
import inspect
import json
import re
import string
import sys
from pycparser import c_parser, c_ast
cparser = c_parser.CParser()
REGISTER_SIZES = {
"R": 32,
"RR": 64,
"C": 32,
"CC": 64,
"G": 32,
"GG": 64,
"S": 32,
"SS": 64,
"P": 8,
"M": 32,
"N": 32,
"r": 32,
}
REGISTER_NAMES = {
"R": ["R{}".format(i) for i in range(32)],
"RR": ["R{}_{}".format(i + 1, i) if i % 2 == 0 else "_" for i in range(0, 32)],
"C": ["C{}".format(i) for i in range(32)],
"CC": ["C{}_{}".format(i + 1, i) if i % 2 == 0 else "_" for i in range(0, 32)],
"G": ["G{}".format(i) for i in range(32)],
"GG": ["G{}_{}".format(i + 1, i) if i % 2 == 0 else "_" for i in range(0, 32)],
"S": ["S{}".format(i) for i in range(32)],
"SS": ["S{}_{}".format(i + 1, i) if i % 2 == 0 else "_" for i in range(0, 32)],
"P": ["P{}".format(i) for i in range(4)],
"M": ["$(M{})".format(i) for i in range(2)],
"r": ["R{}".format(i) for i in list(range(0, 8)) + list(range(16, 24))],
}
REGISTER_ALIASES = {
"R": ["SP", "FP", "LR"],
"RR": ["LR_FP"],
"C": ["SA0", "LC0", "SA1", "LC1", "P3_0", "M0", "M1",
"USR", "PC", "UGP", "GP", "CS0", "CS1",
"UPCYCLELO", "UPCYCLEHI", "FRAMELIMIT", "FRAMEKEY",
"PKTCOUNTLO", "PKTCOUNTHI", "UTIMERLO", "UTIMERHI"],
"CC": ["UPCYCLE", "PKTCOUNT", "UTIMER"],
"G": ["GISDBMBXIN", "GISDBMBXOUT", "GPCYCLELO", "GPCYCLEHI",
"GPMUCNT0", "GPMUCNT1", "GPMUCNT2", "GPMUCNT3"],
"S": ["SGP0", "SGP1", "STID", "ELR", "BADVA0", "BADVA1", "SSR",
"CCR", "HTID", "BADVA", "IMASK", "EVB", "MODECTL", "SYSCFG",
"IPEND", "VID", "IAD", "IEL", "IAHL", "CFGBASE", "DIAG",
"REV", "PCYCLELO", "PCYCLEHI", "ISDBST", "ISDBCFG0",
"ISDBCFG1", "BRKPTPC0", "BRKPTCFG0", "BRKPTPC1", "BRKPTCFG1",
"ISDBMBXIN", "ISDBMBXOUT", "ISDBEN", "ISDBGPR", "PMUCNT0",
"PMUCNT1", "PMUCNT2", "PMUCNT3", "PMUEVTCFG", "PMUCFG"],
"SS": ["SGP"],
}
REGISTER_FIELDS = {
"USR": [
("PFA", 1),
("FPINEE", 1),
("FPUNFE", 1),
("FPOVFE", 1),
("FPDBZE", 1),
("FPINVE", 1),
("FPRND", 2),
("HFI", 2),
("HFD", 2),
("PCMME", 1),
("PCGME", 1),
("PCUME", 1),
("LPCFG", 2),
("FPINPF", 1),
("FPUNFF", 1),
("FPOVFF", 1),
("FPDBZF", 1),
("FPINVF", 1),
("OVF", 1),
],
"SYSCFG": [
("TLBLOCK", 1),
("K0LOCK", 1),
]
}
class Mnemonic:
OPERATORS = [
("+=", "acc"),
("-=", "nac"),
("&=", "aac"),
("|=", "oac"),
("^=", "xac"),
("++", "inc"),
("--", "dec"),
("==", "eq"),
("!=", "ne"),
(">=", "sup"),
("<=", "inf"),
("!", "not"),
("~", "neg"),
("*", "cnj"),
("<<", "sft"),
(">>", "rsf"),
]
CHARACTERS = " ().,;:[]#+-="
@staticmethod
def normalize(syntax):
# Normalize registers
syntax = re.sub(r"([RNPMCSG])[uxevtsdy]{2}", r"_\1\1_", syntax)
syntax = re.sub(r"([RNPMCSG])[uxevtsdy]\.L", r"_\1l_", syntax)
syntax = re.sub(r"([RNPMCSG])[uxevtsdy]\.H", r"_\1h_", syntax)
syntax = re.sub(r"([RNPMCSG])[uxevtsdy]", r"_\1_", syntax)
# Normalize immediates
def upper_repl(match):
return "_{}_".format(match.group(1).upper())
syntax = re.sub(r"#([uSsmrU])[123456789]:(0|1|2|3|31)", upper_repl, syntax)
syntax = re.sub(r"#([uSsmrU])[123456789]", upper_repl, syntax)
syntax = re.sub(r"-(\d+)", r"m\1", syntax)
# Normalize operators
for pattern, replace in Mnemonic.OPERATORS:
syntax = syntax.replace(pattern, replace)
# Normalize characters
for char in Mnemonic.CHARACTERS:
syntax = syntax.replace(char, "_")
# Prepend the Q6 suffix
syntax = "Q6_{}".format(syntax)
# Remove extra underscores
while "__" in syntax:
syntax = syntax.replace("__", "_")
syntax = syntax.strip("_")
return syntax
def __init__(self, syntax):
self.syntax = syntax
self.mnemonic = Mnemonic.normalize(syntax)
# Sanity check
charset = string.ascii_letters + string.digits + "_"
assert all([c in charset for c in self.mnemonic])
def __str__(self):
return self.mnemonic
class Register:
def __init__(self, token, ranges):
self.token = token
self.ranges = ranges
class Immediate:
def __init__(self, token, length, shift, ranges):
self.token = token
self.length = length
self.shift = shift
self.ranges = ranges
class Encoding:
def __init__(self, syntax, encoding):
self.encoding = encoding[::-1]
# Sanity check
assert len(encoding) == 32
registers, immediates = self.parse_syntax(syntax)
# Sanity check
self.characters = [l for l in set(encoding) if l not in "-01PN"]
assert len(self.characters) == len(registers) + len(immediates)
self.fixed_bits = []
self.find_fixed_bits()
self.registers = []
self.match_registers(registers)
self.immediates = []
self.match_immediates(immediates)
self.positions = []
self.order_operands(syntax)
@staticmethod
def calc_ranges(indexes):
ranges = []
for index in indexes:
if not ranges:
ranges.append((index, index))
else:
last_range = ranges[-1]
if last_range[1] == index - 1:
ranges[-1] = last_range[0], index
else:
ranges.append((index, index))
return ranges
def parse_syntax(self, syntax):
# Extract registers from syntax
registers = []
for match in re.finditer(r"[A-Z][a-z][a-z]?", syntax):
register = match.group(0)
if register not in registers:
registers.append(register)
# Extract immediates from syntax
immediates = []
for match in re.finditer(r"#[a-zA-Z][0-9]+(:[0-9]+)?", syntax):
immediate = match.group(0)
if immediate not in immediates:
immediates.append(immediate)
return registers, immediates
def find_fixed_bits(self):
fix_index = [i for i, char in enumerate(self.encoding) if char in "01"]
fix_ranges = Encoding.calc_ranges(fix_index)
self.fixed_bits = [(fix_beg, fix_end, self.encoding[fix_beg:fix_end + 1])
for fix_beg, fix_end in fix_ranges]
def match_registers(self, registers):
# Match registers from syntax with encoding
for register in registers:
reg_type = register[0]
reg_char = register[1]
# Sanity check
assert reg_type in "RCGPMNS"
assert reg_char in self.characters
reg_index = [i for i, char in enumerate(self.encoding) if char == reg_char]
reg_ranges = Encoding.calc_ranges(reg_index)
# Sanity check
assert len(reg_ranges) == 1
reg_beg, reg_end = reg_ranges[0]
reg_size = reg_end - reg_beg + 1
register = Register(register, reg_ranges)
self.registers.append(register)
def match_immediates(self, immediates):
# Match immediates from syntax with encoding
for immediate in immediates:
imm_type = immediate[1]
if imm_type.lower() == imm_type:
imm_char = "i"
else:
imm_char = "I"
# Sanity check
assert imm_type in "sSuUrR"
assert imm_char in self.characters
imm_index = [i for i, char in enumerate(self.encoding) if char == imm_char]
imm_ranges = Encoding.calc_ranges(imm_index)
# Sanity check
assert len(imm_ranges) > 0
imm_size = 0
for imm_beg, imm_end in imm_ranges:
imm_size += imm_end - imm_beg + 1
# Extract shift is present
if ":" in immediate:
imm_length, imm_shift = immediate[2:].split(":")
else:
imm_length, imm_shift = immediate[2:], "0"
imm_length, imm_shift = int(imm_length), int(imm_shift)
# Sanity check
assert imm_size == imm_length
token = immediate.replace("#", "").split(":")[0]
immediate = Immediate(token, imm_length, imm_shift, imm_ranges)
self.immediates.append(immediate)
def order_operands(self, syntax):
for register in self.registers:
position = syntax.index(register.token)
self.positions.append((position, register.token))
for immediate in self.immediates:
position = syntax.index(immediate.token)
self.positions.append((position, immediate.token))
self.positions = [token for start, token in sorted(self.positions)]
class Type:
pass
class Void(Type):
def __eq__(self, other):
return isinstance(other, Void)
def __repr__(self):
return "Void()"
class Integer(Type):
@staticmethod
def compare_length(this, other):
return this == 0 or other == 0 or this == other
@staticmethod
def compare_signed(this, other):
return this is None or other is None or this == other
def __init__(self, length, signed):
self.length = length
self.signed = signed
def __eq__(self, other):
return isinstance(other, Integer) \
and self.length == other.length \
and self.signed == other.signed
def __repr__(self):
length = "??" if self.length == 0 else str(self.length)
signed = "??" if self.signed is None else str(self.signed)
return "Integer({}, {})".format(length, signed)
class Pointer(Type):
def __init__(self, space, pointed):
self.space = space
self.pointed = pointed
def __eq__(self, other):
return isinstance(other, Pointer) \
and self.space == other.space \
and self.pointed == other.pointed
def __repr__(self):
return "Pointer({}, {!r})".format(self.space, self.pointed)
class Scope:
def __init__(self, parent=None):
self.parent = parent
self.lines = []
self.mapping = {}
self.variables = {}
def add_mapping(self, old_name, new_name):
if old_name in self.mapping:
assert self.mapping[old_name] == new_name
return False
self.mapping[old_name] = new_name
return True
def get_mapping(self, name):
if name in self.mapping:
name = self.mapping[name]
return self.get_mapping(name)
if self.parent:
return self.parent.get_mapping(name)
return name
def add_variable(self, name, type):
if name in self.variables:
assert self.variables[name] == type
return False
self.variables[name] = type
return True
def get_variable(self, name):
if name in self.variables:
return self.variables[name]
if self.parent:
return self.parent.get_variable(name)
return None
def del_variable(self, name):
if name in self.variables:
self.variables.pop(name)
return True
if self.parent:
return self.parent.del_variable(name)
return False
def decl_variable(self, name, type, expr=None):
if not self.add_variable(name, type):
return
if isinstance(type, Integer):
if type.length > 0:
length = type.length
else:
type.length = length = 32
elif isinstance(type, Pointer):
length = 32
else:
assert False
assert length % 8 == 0
init = ""
if expr is not None:
init = " = {}".format(expr.print(self))
self.lines.append("local {}:{}{};".format(name, length // 8, init))
def print(self, node):
line = node.print(self)
if not line:
return
if not line.endswith(";"):
line = line + ";"
if isinstance(node.type, Void):
self.lines.append(line)
#else:
# print("Ignoring statement \"{}\"".format(line), file=sys.stderr)
def show(self, ident=0, buf=sys.stdout):
lead = " " * (ident * 4)
print(lead + "Scope #{}:".format(ident), file=buf)
print(lead + " Lines:", file=buf)
for line in self.lines:
print(lead + " - {}".format(line), file=buf)
print(lead + " Mapping:", file=buf)
for old_name, new_name in self.mapping.items():
print(lead + " - {} -> {}".format(old_name, new_name), file=buf)
print(lead + " Variables:", file=buf)
for name, type in self.variables.items():
print(lead + " - {} -> {!r}".format(name, type), file=buf)
if self.parent:
self.parent.show(ident + 1, buf=buf)
class NodeException(Exception):
def __init__(self, node, frame, msg):
super().__init__(msg)
self.node = node
self.frame = frame
class Node:
@staticmethod
def labelify(node):
charset = string.ascii_letters + string.digits + "_"
label = [c if c in charset else "_" for c in str(node)]
return re.sub(r"_+", r"_", "".join(label)).strip("_")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if "type" in self.__slots__:
slots = list(self.__slots__)
slots[slots.index("type")] = "orig_type"
self.__slots__ = tuple(slots)
self.orig_type = self.type
self.type = None
# Ensure eval sets type
old_eval = self.eval
def new_eval(scope):
try:
node = old_eval(scope)
except Exception as e:
if isinstance(e, NodeException):
raise e
frame = e.__traceback__.tb_next.tb_frame
raise NodeException(self, frame, str(e))
self.check(node is not None)
self.check(node.type is not None)
return node
self.eval = new_eval
def check(self, cond, msg=None):
if not cond:
frame = inspect.currentframe().f_back
raise NodeException(self, frame, msg)
def eval(self, scope):
raise self.check(False, "eval() not implemented")
def print(self, scope):
raise self.check(False, "print() not implemented")
def __repr__(self):
attrs = ["{!r}".format(self.type)]
for attr in self.__slots__[:-2]:
attrs.append("{}={!r}".format(attr, getattr(self, attr)))
name = self.__class__.__name__
return "{}({})".format(name, ", ".join(attrs))
def is_ident(self):
return isinstance(self, ID)
def get_name(self):
self.check(self.is_ident())
return self.name
def is_const(self):
return isinstance(self, Constant)
def get_value(self):
self.check(self.is_const())
return int(self.value, 0)
def returns_value(self):
self.check(self.type is not None)
return not isinstance(self.type, Void)
def is_assignable(self):
return False
def resize(self, scope, length):
self.check(isinstance(self.type, Integer))
if self.type.length == 0:
self.type.length = length
if self.type.length == length:
return self
if self.type.length < length:
self.check(self.returns_value())
self.check(length % 8 == 0)
name = ID("sxt" if self.type.signed else "zxt")
old_length = Constant("int", str(self.type.length))
new_length = Constant("int", str(length))
args = ExprList([old_length, new_length, self])
node = FuncCall(name, args)
node.eval(scope)
return node
else:
self.check(self.is_assignable())
self.check(length % 8 == 0)
node = UnaryOp(":{}".format(length // 8), self)
node.eval(scope)
return node
class ArrayDecl(Node, c_ast.ArrayDecl):
pass
class ArrayRef(Node, c_ast.ArrayRef):
def eval(self, scope):
self.name = self.name.eval(scope)
self.check(self.name.is_assignable())
self.subscript = self.subscript.eval(scope)
self.check(self.subscript.returns_value())
if isinstance(self.name.type, Pointer):
self.check(self.subscript.is_const() or \
(self.subscript.type.length == 32 \
and self.subscript.type.signed is False))
self.type = self.name.type.pointed
return self
if self.name.is_ident():
self.check(self.subscript.is_const())
index = self.subscript.get_value()
self.check(self.name.type.length > index)
self.type = Integer(1, False)
return self
self.check(False)
def print(self, scope):
if isinstance(self.name.type, Pointer):
array = self.name.print(scope)
index = self.subscript.print(scope)
space = self.name.type.space
length = self.type.length // 8
expr = "({} + {} * {})".format(array, length, index)
return "*[{}]:{} {}".format(space, length, expr)
if self.name.is_ident() and self.name.type.length > 0:
array = self.name.print(scope)
index = self.subscript.print(scope)
return "{}[{}, 1]".format(array, index)
self.check(False)
def is_assignable(self):
return True
class Assignment(Node, c_ast.Assignment):
def eval(self, scope):
if self.op == "=":
self.lvalue = self.lvalue.eval(scope)
self.check(self.lvalue.is_assignable())
self.rvalue = self.rvalue.eval(scope)
self.check(self.rvalue.returns_value())
if self.lvalue.type.length == 0:
self.lvalue = self.lvalue.resize(scope, self.rvalue.type.length)
else:
self.rvalue = self.rvalue.resize(scope, self.lvalue.type.length)
self.type = Void()
return self
elif self.op in ["+=", "-=", "*=", "/=", "&=", "|=", "^="]:
rvalue = BinaryOp(self.op[0], self.lvalue, self.rvalue)
node = Assignment("=", self.lvalue, rvalue)
return node.eval(scope)
else:
self.check(False)
def print(self, scope):
scope.lines.append("{} = {};".format(
self.lvalue.print(scope), self.rvalue.print(scope)))
return ""
class BinaryOp(Node, c_ast.BinaryOp):
ARITHMETIC = ["+", "-", "*", "/", "<<", ">>", "&", "|", "^"]
COMPARISON = ["==", "!=", "<", ">", "<=", ">=", "s<", "s>", "s<=", "s>="]
def eval(self, scope):
self.check(self.op in BinaryOp.ARITHMETIC + BinaryOp.COMPARISON)
self.left = self.left.eval(scope)
self.check(self.left.returns_value())
left_type = self.left.type
self.right = self.right.eval(scope)
self.check(self.right.returns_value())
right_type = self.right.type
if self.op in [">>", "<<"]:
self.type = left_type
return self
if left_type.length < right_type.length:
self.left = self.left.resize(scope, right_type.length)
if right_type.length < left_type.length:
self.right = self.right.resize(scope, left_type.length)
if self.op in BinaryOp.COMPARISON:
if self.op in ["<", ">", "<=", ">="]:
if left_type.signed == False or right_type.signed == False:
self.check(Integer.compare_signed(left_type.signed, right_type.signed))
elif left_type.signed == True or right_type.signed == True:
self.check(Integer.compare_signed(left_type.signed, right_type.signed))
self.op = "s{}".format(self.op)
elif left_type.signed is None and right_type.signed is None:
#print("Assuming comparison is signed for {}".format(self.print(scope)), file=sys.stderr)
self.op = "s{}".format(self.op)
else:
self.check(False)
self.type = Integer(1, False)
else:
self.type = left_type
return self
def print(self, scope):
return "({} {} {})".format(self.left.print(scope),
self.op,
self.right.print(scope))
class Break(Node, c_ast.Break):
pass
class Case(Node, c_ast.Case):
pass
class Cast(Node, c_ast.Cast):
pass
class Compound(Node, c_ast.Compound):
def eval(self, scope):
self.block_items = (self.block_items or [])
if len(self.block_items) == 0:
self.type = Void()
return self
block_items = []
for child in self.block_items:
child = child.eval(scope)
block_items.append(child)
self.block_items = block_items
self.type = self.block_items[-1].type
return self
def print(self, scope):
if len(self.block_items) == 0:
return ""
for child in self.block_items[:-1]:
scope.print(child)
return self.block_items[-1].print(scope)
def is_assignable(self):
if len(self.block_items) == 0:
return super().is_assignable()
return self.block_items[-1].is_assignable()
class CompoundLiteral(Node, c_ast.CompoundLiteral):
pass
class Constant(Node, c_ast.Constant):
def eval(self, scope):
self.check(self.orig_type == 'int')
self.type = Integer(0, None)
return self
def print(self, scope):
return self.value
class Continue(Node, c_ast.Continue):
pass
class Decl(Node, c_ast.Decl):
pass
class DeclList(Node, c_ast.DeclList):
pass
class Default(Node, c_ast.Default):
pass
class DoWhile(Node, c_ast.DoWhile):
pass
class EllipsisParam(Node, c_ast.EllipsisParam):
pass
class EmptyStatement(Node, c_ast.EmptyStatement):
pass
class Enum(Node, c_ast.Enum):
pass
class Enumerator(Node, c_ast.Enumerator):
pass
class EnumeratorList(Node, c_ast.EnumeratorList):
pass
class ExprList(Node, c_ast.ExprList):
def eval(self, scope):
exprs = []
for child in self.exprs:
child = child.eval(scope)
self.check(child.returns_value())
exprs.append(child)
self.exprs = exprs
self.type = Void()
return self
def print(self, scope):
exprs = []
for child in self.exprs:
exprs.append(child.print(scope))
return ", ".join(exprs)
class FileAST(Node, c_ast.FileAST):
pass
class For(Node, c_ast.For):
def eval(self, scope):
# self.init = self.init.eval(scope)
self.check(isinstance(self.init, Assignment))
self.check(self.init.lvalue.is_ident())
self.loop_var = self.init.lvalue
self.check(self.init.rvalue.is_const())
self.init_val = self.init.rvalue
# self.cond = self.cond.eval(scope)
self.check(isinstance(self.cond, BinaryOp))
self.check(self.cond.left.is_ident())
self.check(self.cond.left.get_name() == self.loop_var.get_name())
self.check(self.cond.right.is_const())
self.cond_val = self.cond.right
# self.next = self.next.eval(scope)
self.check(isinstance(self.next, UnaryOp))
self.check(self.next.op == "p++")
self.check(self.next.expr.is_ident())
self.check(self.next.expr.get_name() == self.loop_var.get_name())
self.step_val = Constant("int", "1").eval(scope)
# Add the loop variable
scope.add_variable(self.loop_var.get_name(), Integer(32, False))
self.stmt_scope = Scope(scope)
self.stmt = self.stmt.eval(self.stmt_scope)
self.check(not self.stmt.returns_value())
# Remove the loop variable
scope.del_variable(self.loop_var.get_name())
self.type = Void()
return self
def print(self, scope):
loop_var = self.loop_var.print(scope)
init_val = self.init_val.print(scope)
cond_val = self.cond_val.print(scope)
step_val = self.step_val.print(scope)
label = "for_{}".format(loop_var)
self.stmt_scope.print(self.stmt)
scope.lines.append("local {}:4 = {};".format(loop_var, init_val))
scope.lines.append("<{}>".format(label))
for line in self.stmt_scope.lines:
scope.lines.append(line)
scope.lines.append("{} = {} + {};".format(loop_var, loop_var, step_val))
scope.lines.append("if ({} < {}) goto <{}>;".format(loop_var, cond_val, label))
return ""
class FuncCall(Node, c_ast.FuncCall):
def eval(self, scope):
self.name = self.name.eval(scope)
if self.name.get_name() == "apply_extension":
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 1)
self.check(self.args.exprs[0].is_assignable())
return self.args.exprs[0]
elif self.name.get_name() in ["sat", "usat"]:
# TODO: Handle value saturation
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 2)
return self.args.exprs[1]
elif self.name.get_name() in ["sxt", "zxt"]:
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 3)
self.check(self.args.exprs[0].is_const())
old_length = self.args.exprs[0].get_value()
self.check(self.args.exprs[1].is_const())
new_length = self.args.exprs[1].get_value()
self.check(old_length < new_length)
signed = self.name.get_name() == "sxt"
expr = self.args.exprs[2]
self.check(Integer.compare_signed(expr.type.signed, signed))
self.name.name = self.name.name.replace("xt", "ext")
self.args.exprs = [expr.resize(scope, old_length)]
self.type = Integer(new_length, signed)
return self
elif self.name.get_name() == "newSuffix":
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 1)
self.check(self.args.exprs[0].is_assignable())
# FIXME: Workaround for new-values
arg = self.args.exprs[0]
token = arg.print(scope)
if re.match(r"N[s-v]_\d+\d+", token):
arg_name = "arg_{}".format(Node.labelify(token))
scope.decl_variable(arg_name, arg.type, arg)
self.args.exprs[0] = ID(arg_name).eval(scope)
self.type = self.args.exprs[0].type
return self
elif self.name.get_name() == "nextPacket":
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 0)
self.type = Integer(32, False)
return self
elif self.name.get_name() == "constExtend":
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 0)
self.type = Integer(0, None)
return self
elif self.name.get_name() == "circAdd":
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 3)
# FIXME: Workaround for immediates
arg = self.args.exprs[1]
token = arg.print(scope)
if re.match(r"[sSuUrR]\d+", token):
arg_name = "arg_{}".format(Node.labelify(token))
scope.decl_variable(arg_name, arg.type, arg)
self.args.exprs[1] = ID(arg_name).eval(scope)
self.type = self.args.exprs[0].type
return self
elif self.name.get_name() == "bitsRev":
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 1)
self.check(self.args.exprs[0].returns_value())
self.type = self.args.exprs[0].type
return self
elif self.name.get_name() == "frameUnscramble":
self.args = self.args.eval(scope)
self.check(len(self.args.exprs) == 1)
self.check(self.args.exprs[0].returns_value())
self.check(self.args.exprs[0].type.length == 64)
self.check(self.args.exprs[0].type.signed == False)
self.type = self.args.exprs[0].type
return self
else:
self.check(False)
def print(self, scope):
return "{}({})".format(self.name.print(scope),
self.args.print(scope))
class FuncDecl(Node, c_ast.FuncDecl):
pass
class FuncDef(Node, c_ast.FuncDef):
pass
class Goto(Node, c_ast.Goto):
pass
class ID(Node, c_ast.ID):
IGNORED_FUNCTIONS = ["PREDUSE_TIMING", "NOP"]
BUILTIN_FUNCTIONS = ["apply_extension", "sat", "usat", "sxt", "zxt"]
PCODEOP_FUNCTIONS = ["newSuffix", "nextPacket", "constExtend",
"circAdd", "bitsRev", "frameUnscramble"]
SUBPIECE_KEYWORDS = ["b", "ub", "h", "uh", "w", "uw", "new"]
def eval(self, scope):
if self.name in ID.IGNORED_FUNCTIONS:
return Compound([]).eval(scope)
if self.name in ID.BUILTIN_FUNCTIONS \
or self.name in ID.PCODEOP_FUNCTIONS \
or self.name in ID.SUBPIECE_KEYWORDS:
self.type = Void()
return self
self.name = scope.get_mapping(self.name)
self.type = scope.get_variable(self.name)
if self.type is None:
if self.name in ["tmp", "EA"]:
self.type = Integer(32, False)
scope.decl_variable(self.name, self.type)
return self
if self.name in ["MuV", "tmpV"]:
return ID(self.name[:-1]).eval(scope)
if self.name == "I":
name = scope.get_mapping("Mu")
self.type = Integer(32, False)
line = "local I:4 = ((({} >> 28) & 0xf) << 7) | (({} >> 17) & 0x7f);"
scope.lines.append(line.format(name, name))
scope.add_variable("I", self.type)
return self
if self.name == "NPC":
node = FuncCall(ID("nextPacket"), ExprList([]))
return node.eval(scope)
if self.name == "Constant_extended":
node = FuncCall(ID("constExtend"), ExprList([]))
return node.eval(scope)
if self.name == "circ_add":
return ID("circAdd").eval(scope)
if self.name == "brev":
return ID("bitsRev").eval(scope)
if self.name == "frame_unscramble":
return ID("frameUnscramble").eval(scope)
# Check if it is a register name
for reg_type, tokens in REGISTER_NAMES.items():
if self.name in tokens:
length = REGISTER_SIZES[reg_type]
self.type = Integer(length, False)
scope.add_variable(self.name, self.type)
return self
# Check if it is a register alias
for reg_type, tokens in REGISTER_ALIASES.items():
if self.name in tokens:
length = REGISTER_SIZES[reg_type]
old_name = self.name
self.name = "$({})".format(self.name)
self.type = Integer(length, False)
scope.add_mapping(old_name, self.name)
scope.add_variable(self.name, self.type)
return self
# Check if it is a register field
for reg_name, fields in REGISTER_FIELDS.items():
for field, length in fields:
if field == self.name:
old_name = self.name
self.name = "$({})".format(self.name)
self.type = Integer(length, False)
scope.add_mapping(old_name, self.name)
scope.add_variable(self.name, self.type)
return self
self.check(False, "Unknown identifier")
return self
def print(self, scope):
return self.name
def is_assignable(self):
return self.returns_value()
class IdentifierType(Node, c_ast.IdentifierType):
pass
class If(Node, c_ast.If):