forked from riscv/sail-riscv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config2sail.py
1036 lines (963 loc) · 40.2 KB
/
config2sail.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 re
from ruamel.yaml import YAML
from ruamel.yaml.constructor import DuplicateKeyError
import logging
import getopt
import sys
# function for yaml loading
def load_yaml(foo):
yaml = YAML(typ='rt')
yaml.default_flow_style = False
yaml.allow_unicode = True
yaml.compact(seq_seq=False, seq_map=False)
yaml.indent = 4
yaml.block_seq_indent = 2
try:
with open(foo, 'r') as file:
return yaml.load(file)
except DuplicateKeyError as msg:
logger = logging.getLogger(__name__)
error = '\n'.join(str(msg).split('\n')[2:-7])
logger.error(error)
raise SystemExit
# common sail code for warl field handling
warl_type_and_func = '''
enum WARL_range_mode = {
WARL_Unchanged,
WARL_Nextup,
WARL_Nextdown,
WARL_Nearup,
WARL_Neardown,
WARL_Largest,
WARL_Smallest,
WARL_Addr
}
union WARL_range_entry = {
WARL_range_value: nat,
WARL_range_interval: (nat, nat)
}
struct WARL_range_type = {
mask: nat,
delta: nat,
values: list(WARL_range_entry)
}
struct WARL_bitmask = {
mask: nat, /* XXX consider using bits('n) */
default_val: nat
}
union WARL_either = {
WARL_range_list: list(WARL_range_type),
WARL_bitmask: WARL_bitmask
}
val is_value_in_range: (nat, list(WARL_range_entry)) -> bool
function is_value_in_range (value, warl_range) = match(warl_range) {
[||] => false,
v :: vs => match (v) {
WARL_range_value(v) => value == v | is_value_in_range(value, vs),
WARL_range_interval(l, u) => ((l <= value) & (value <= u)) |
is_value_in_range(value, vs)
}
}
val is_value_in_rangelist:
forall 'n, 'n > 0 . (bits('n), list(WARL_range_type)) -> bool effect {escape}
function is_value_in_rangelist (value, list) = match(list) {
[||] => true,
v :: vs => is_value_in_range(unsigned(value & to_bits('n, v.mask)),
v.values) &
is_value_in_rangelist(value, vs)
}
val WARL_range_max: (list(WARL_range_entry)) -> nat effect {escape}
function WARL_range_max (warl_range) = match(warl_range) {
[||] => throw Error_not_implemented("Empty WARL range"),
v :: [||] =>
match (v) {
WARL_range_value(v) => v,
WARL_range_interval(l, u) => u
},
v :: vs =>
let tail_max: nat = WARL_range_max(vs) in
match (v) {
WARL_range_value(v) => if v > tail_max then v else tail_max,
WARL_range_interval(l, u) => if u > tail_max then u else tail_max
}
}
val WARL_range_min: (list(WARL_range_entry)) -> nat effect {escape}
function WARL_range_min (warl_range) = match(warl_range) {
[||] => throw Error_not_implemented("Empty WARL range"),
v :: [||] =>
match (v) {
WARL_range_value(v) => v,
WARL_range_interval(l, u) => l
},
v :: vs =>
let tail_min: nat = WARL_range_min(vs) in
match (v) {
WARL_range_value(v) => if v < tail_min then v else tail_min,
WARL_range_interval(l, u) => if u < tail_min then u else tail_min
}
}
val WARL_range_nextup: (nat, list(WARL_range_entry)) -> nat effect {escape}
function WARL_range_nextup (value, warl_range) = match(warl_range) {
[||] => throw Error_not_implemented("Empty WARL range"),
v :: [||] =>
match (v) {
WARL_range_value(v) => v,
WARL_range_interval(l, u) => {
if value >= l & value <= u then value
else if value > u then u
else l
}
},
v :: vs =>
let tail_nextup: nat = WARL_range_nextup(value, vs) in
match (v) {
WARL_range_value(v) => {
if v >= value & v < tail_nextup then v
else if v >= value & tail_nextup < value then v
else if v <= value & v > tail_nextup then v
else tail_nextup
},
WARL_range_interval(l, u) => {
if value >= l & value <= u then value
else if value > u & u > tail_nextup then u
else if value < l & l < tail_nextup then l
else tail_nextup
}
}
}
val WARL_range_nextdown: (nat, list(WARL_range_entry)) -> nat effect {escape}
function WARL_range_nextdown (value, warl_range) = match(warl_range) {
[||] => throw Error_not_implemented("Empty WARL range"),
v :: [||] =>
match (v) {
WARL_range_value(v) => v,
WARL_range_interval(l, u) => {
if value >= l & value <= u then value
else if value > u then u
else l
}
},
v :: vs =>
let tail_nextdown: nat = WARL_range_nextdown(value, vs) in
match (v) {
WARL_range_value(v) => {
if v <= value & v > tail_nextdown then v
else if v <= value & tail_nextdown > value then v
else if v >= value & v < tail_nextdown then v
else tail_nextdown
},
WARL_range_interval(l, u) => {
if value >= l & value <= u then value
else if value > u & u > tail_nextdown then u
else if value < l & l < tail_nextdown then l
else tail_nextdown
}
}
}
val WARL_range_nearup: (nat, list(WARL_range_entry)) -> nat effect {escape}
function WARL_range_nearup (value, warl_range) = {
nextup = WARL_range_nextup(value, warl_range);
nextdown = WARL_range_nextup(value, warl_range);
if nextup <= value then nextup
else if nextdown >= value then nextdown
else if (nextup - value) <= (value - nextdown) then nextup
else nextdown
}
val WARL_range_neardown: (nat, list(WARL_range_entry)) -> nat effect {escape}
function WARL_range_neardown (value, warl_range) = {
nextup = WARL_range_nextup(value, warl_range);
nextdown = WARL_range_nextup(value, warl_range);
if nextup <= value then nextup
else if nextdown >= value then nextdown
else if (nextup - value) < (value - nextdown) then nextup
else nextdown
}
val legalize_warl_range: forall 'n, 'n > 0 .
(bits('n), bits('n), WARL_range_type, WARL_range_mode) -> bits('n)
effect {escape}
function legalize_warl_range(current_val, written_val, legal_range, mode) = {
match(mode) {
WARL_Unchanged => current_val & to_bits('n, legal_range.mask),
WARL_Largest => to_bits('n, WARL_range_max(legal_range.values)),
WARL_Smallest => to_bits('n, WARL_range_min(legal_range.values)),
WARL_Nextup => to_bits('n, WARL_range_nextup(unsigned(current_val),
legal_range.values)),
WARL_Nextdown => to_bits('n, WARL_range_nextdown(unsigned(current_val),
legal_range.values)),
WARL_Nearup => to_bits('n, WARL_range_nearup(unsigned(current_val),
legal_range.values)),
WARL_Neardown => to_bits('n, WARL_range_neardown(unsigned(current_val),
legal_range.values)),
WARL_Addr => written_val ^ shiftl(to_bits('n, 1), 'n - 1)
}
}
val legalize_warl_rangelist: forall 'n, 'n > 0 .
(bits('n), bits('n), list(WARL_range_type), WARL_range_mode, bits('n)) ->
bits('n) effect {escape}
function legalize_warl_rangelist(current_val, written_val,
legal_range_list, mode, msmask) = {
match(mode) {
WARL_Unchanged => current_val,
WARL_Nearup => {
nextup: bits('n) = legalize_warl_rangelist(current_val, written_val,
legal_range_list,
WARL_Nextup, msmask);
nextdown: bits('n) = legalize_warl_rangelist(current_val, written_val,
legal_range_list,
WARL_Nextdown, msmask);
cur: bits('n) = written_val & not_vec(msmask);
if (nextup == nextdown) then nextup
else if ((unsigned(nextup) - unsigned(cur)) <=
(unsigned(cur) - unsigned(nextdown))) then nextup
else nextdown
},
WARL_Neardown => {
nextup: bits('n) = legalize_warl_rangelist(current_val, written_val,
legal_range_list,
WARL_Nextup, msmask);
nextdown: bits('n) = legalize_warl_rangelist(current_val, written_val,
legal_range_list,
WARL_Nextdown, msmask);
cur: bits('n) = written_val & not_vec(msmask);
if (nextup == nextdown) then nextup
else if ((unsigned(nextup) - unsigned(cur)) <
(unsigned(cur) - unsigned(nextdown))) then nextup
else nextdown
},
WARL_Addr => written_val ^ shiftl(to_bits('n, 1), 'n - 1),
_ => {
match(legal_range_list) {
[||] => to_bits('n, 0),
v :: vs => {
cur = written_val & to_bits('n, v.mask);
msfields: bits('n) = legalize_warl_range(current_val, cur , v, mode);
match(mode) {
WARL_Largest => msfields | legalize_warl_rangelist(current_val,
written_val, vs, mode,
msmask | to_bits('n, v.mask)),
WARL_Smallest => msfields | legalize_warl_rangelist(current_val,
written_val, vs, mode,
msmask | to_bits('n, v.mask)),
WARL_Nextup => {
if (unsigned(msfields) > unsigned(cur)) then
msfields | legalize_warl_rangelist(current_val, written_val,
vs, WARL_Smallest, msmask | to_bits('n, v.mask))
else if (unsigned(msfields) < unsigned(cur)) then
msfields | legalize_warl_rangelist(current_val, written_val,
vs, WARL_Largest, msmask | to_bits('n, v.mask))
else {
lsfields: bits('n) = legalize_warl_rangelist(current_val,
written_val, vs, mode,
msmask | to_bits('n, v.mask));
value: bits('n) = msfields | lsfields;
if (unsigned(value) > unsigned(written_val & not_vec(msmask)))
then value
else {
msfields = legalize_warl_range(current_val,
to_bits('n, unsigned(cur) + v.delta) , v, mode);
if (unsigned(msfields) >= unsigned(cur)) then
msfields | legalize_warl_rangelist(current_val, written_val,
vs, WARL_Smallest, msmask | to_bits('n, v.mask))
else value
}
}
},
WARL_Nextdown => {
cur = written_val & to_bits('n, v.mask);
msfields: bits('n) = legalize_warl_range(current_val, cur ,
v, mode);
if (unsigned(msfields) > unsigned(cur)) then
msfields | legalize_warl_rangelist(current_val, written_val,
vs, WARL_Smallest, msmask | to_bits('n, v.mask))
else if (unsigned(msfields) < unsigned(cur)) then
msfields | legalize_warl_rangelist(current_val, written_val,
vs, WARL_Largest, msmask | to_bits('n, v.mask))
else {
lsfields: bits('n) = legalize_warl_rangelist(current_val,
written_val, vs, mode,
msmask | to_bits('n, v.mask));
value: bits('n) = msfields | lsfields;
if (unsigned(value) < unsigned(written_val & (not_vec(msmask))))
then value
else {
msfields = legalize_warl_range(current_val,
to_bits('n, unsigned(cur) - v.delta) , v, mode);
if (unsigned(msfields) <= unsigned(cur)) then
msfields | legalize_warl_rangelist(current_val, written_val,
vs, WARL_Largest, msmask | to_bits('n, v.mask))
else value
}
}
}
}
}
}
}
}
}
val legalize_warl_bitmask: forall 'n, 'n > 0 & 'n <= 64 .
(bits('n), WARL_bitmask) -> bits('n)
function legalize_warl_bitmask (value, mask) =
(value & to_bits('n, mask.mask)) | to_bits('n, mask.default_val)
val legalize_warl_either: forall 'n, 'n > 0 & 'n <= 64 .
(bits('n), bits('n), WARL_either, WARL_range_mode) -> bits('n) effect {escape}
function legalize_warl_either(current_val, written_val, warl_either, mode) =
match (warl_either) {
WARL_range_list(r) => legalize_warl_rangelist(current_val, written_val, r,
mode, to_bits('n, 0)),
WARL_bitmask(b) => legalize_warl_bitmask(written_val, b)
}
'''
def getMask(x):
return x[0]
# function for parsing legal values of specific field in range or value list
# generate sail code for value list of field
def parse_values(value_str, field_mask, lsb, not_in):
parse_str = ''
if ":" in value_str: # value str is a range
[base, bound] = value_str.split(':')
if 'x' in base: # Hexadecimal value
base = int(base, 16)
base = int(base) << lsb
if 'x' in bound:
bound = int(bound, 16)
bound = int(bound) << lsb
# check th
if base > field_mask | bound > field_mask:
print(reg + ' [base: bound] is illegal\n')
raise SystemExit
if not_in:
if base != 0:
parse_str += \
'WARL_range_interval(unsigned(0x%x), unsigned(0x%x)), ' \
% (0, base - (1 << lsb))
if bound != field_mask:
parse_str += \
'WARL_range_interval(unsigned(0x%x), unsigned(0x%x)), ' \
% (bound + (1 << lsb), field_mask)
else:
parse_str += \
'WARL_range_interval(unsigned(0x%x), unsigned(0x%x)), ' \
% (base, bound)
else: # value_str is value list
l_vals = value_str.split(',')
values = []
last = 0
for i in l_vals:
if 'x' in i:
i = int(i, 16)
i = int(i) << lsb
if i > field_mask:
print(reg + ' legal list is illegal\n')
raise SystemExit
values.append(i)
values.sort()
# for illegal value list, select the legal range between illegal values
for i in values:
if not_in:
if i != last:
parse_str += 'WARL_range_interval(unsigned(0x%x), \
unsigned(0x%x)), ' % (last << lsb, i - (1 << lsb))
last = i + (1 << lsb)
else:
parse_str += 'WARL_range_value(unsigned(0x%x)), ' % i
# add the final legal range for 'not in'
if not_in:
if last <= field_mask:
parse_str += 'WARL_range_interval(' + \
'unsigned(0x%x), unsigned(0x%x)), ' % (last, field_mask)
return parse_str[:-2]
# function for parsing the legal ranges for legal str
def parse_field_range(legal_str):
warl_range_temp = '''
struct {{
mask = {0},
delta = {1},
values = [|{2}|]
}}: WARL_range_type'''
warl_bitmask_temp = '''
struct {{
mask = {0},
default_val = {1}
}}: WARL_bitmask'''
exp = re.compile(r'\[(?P<csr_ind>.*?)\]\s*(?P<csr_op>.*?)\s*' +
r'\[(?P<csr_vals>.*?)\]')
csr_search = exp.findall(legal_str)
range_field = ''
range_list = []
for part in csr_search:
(csr_ind, csr_op, csr_vals) = part
msb = csr_ind.split(':')[0].strip()
lsb = csr_ind.split(':')[-1].strip()
bitmask = True if 'bitmask' in csr_op else False
field_mask = (1 << (int(msb) + 1)) - (1 << int(lsb))
parse_str = ''
if not bitmask: # range or value list
parse_str = parse_values(csr_vals, field_mask, int(lsb),
'not' in csr_op)
range_list.append([field_mask, warl_range_temp.format(
'unsigned(0x%x)' % field_mask,
'unsigned(0x%x)' % (1 << int(lsb)), parse_str)])
else: # bitmask
[mask, fixed] = csr_vals.split(',')
if 'x' in mask:
mask = 'unsigned(' + mask.strip() + ')'
if 'x' in fixed:
fixed = 'unsigned(' + fixed.strip() + ')'
if range_field == '' and range_list == []:
range_field = warl_bitmask_temp.format(str(mask), str(fixed))
range_field += ', '
break
else:
print('cannot mix bitmask and range\n')
if 'bitmask' not in legal_str:
range_list.sort(key=getMask, reverse=True)
for d in range_list:
range_field += d[1] + ', '
return range_field[: -2]
# function for generating sail code for field without dependencies
def legalize_without_dependencies(reg, field, field_yaml):
global func_str
legalize_field = '''
function legalize_{0}_{1}(o: {2}, v: {2}) -> {2} = {{
m: {2} = v;
{3} m
}}
'''
wr_value_temp = '''let wr_value_rangelist: list(WARL_range_type) =
[|{0}|];\n'''
warl_range_temp = '''let warl_range_list: list(WARL_range_type) =
[|{0}|];\n'''
legalize_field_strs = ''
warl = field_yaml['type']['warl']
if len(warl['legal']) > 1:
print('warl without dependence can only have one legal entry')
raise SystemExit
range_list = parse_field_range(warl['legal'][0])
# generate sail code for legalize functions for csr field
if 'bitmask' not in warl['legal'][0]: # wr_illegal string without bitmask
legalize_field_strs += warl_range_temp.format(range_list) + '\n'
legalize_field_strs += ' if (~ (is_value_in_rangelist(v,' + \
'warl_range_list))) then {\n'
for i in range(len(warl['wr_illegal'])):
op = re.findall(r'\s*wr_val\s*in\s*\[(.*?)\]',
warl['wr_illegal'][i])
if op != []:
parse_str = parse_values(op[0], 0xffffffffffffffff, 1, False)
wr_value_temp.format(parse_str)
legalize_field_strs += \
' if is_value_in_range(v, wr_value_rangelist) then '
op2 = re.split(r'\->', warl['wr_illegal'][i])
mode = op2[1]
else:
mode = warl['wr_illegal'][i]
if '0x' in mode:
legalize_field_strs += ' m = ' + mode + ';'
else:
legalize_field_strs += \
' m = legalize_warl_either(o , m,' + \
' WARL_range_list(warl_range_list), WARL_' + \
mode.title() + ');'
legalize_field_strs += '\n };\n'
else: # WARL_Unchanged is selected for bitmask legal string
legalize_field_strs += \
'm = legalize_warl_either(o , m, WARL_bitmask(' + range_list + \
'), WARL_Unchanged);\n'
func_str += legalize_field.format(
reg.lower(), field.upper(), 'bits(' +
str(int(field_yaml['msb']) - int(field_yaml['lsb']) + 1) + ')',
legalize_field_strs)
# function for searching the dependency_field
def search_dependency_field(csr, field, depend_fields):
leaf_dependencies = []
# collect all the legal dependency fields
for d in depend_fields:
leaf_dependencies.append(d.split('::')[-1])
# check whether current field is legal dependancy field
if field not in leaf_dependencies:
print('cannot find dpendency field ' + field + ' in ' +
str(leaf_dependencies) + '\n')
raise SystemExit
field_val = depend_fields[leaf_dependencies.index(field)]
# get the value (code) of dependency field
if '::' in field_val:
csr_name = field_val.split('::')[0].strip()
field_name = field_val.split('::')[-1].strip()
return csr_name + '.' + field_name.upper() + '()'
else:
return field_val + '->bits()'
# function for parsing the dependency string
def parse_dependency(csr, dep_str, depend_fields):
cond_str = ''
exp = re.compile(r'(?P<csr>.*?)\[(?P<csr_ind>.*?)\]\s*(?P<csr_op>.*?)' +
r'\s*\[(?P<csr_vals>.*?)\]')
csr_search = exp.findall(dep_str)
for part in csr_search:
(field, csr_ind, csr_op, csr_vals) = part
field = search_dependency_field(csr, field.strip(), depend_fields)
val = 'unsigned(' + field + '[' + csr_ind.split(':')[0] + ' .. ' + \
csr_ind.split(':')[-1] + '])'
bitmask = True if 'bitmask' in csr_op else False
range_str = ''
if not bitmask: # if its not a bitmask
if ":" in csr_vals: # range is specified
[base, bound] = csr_vals.split(':')
if 'x' in base:
base = int(base.strip(), 16)
base = int(base)
if 'x' in bound:
bound = int(bound.strip(), 16)
bound = int(bound)
range_str += 'WARL_range_interval(' + \
'unsigned(0x%x), unsigned(0x%x)),' % (base, bound)
else:
l_vals = csr_vals.split(',')
for i in l_vals:
if 'x' in i:
i = int(i, 16)
i = int(i)
range_str += 'WARL_range_value(unsigned(0x%x)),' % i
cond_str += 'is_value_in_range(' + val + ',[|' + \
range_str[:-1] + '|]) & \n'
else:
print('cannot support bitmask in dpendency list\n')
raise SystemExit
return cond_str[:-4]
# function for generating sail code for field with dependencies
def legalize_with_dependencies(reg, field, field_yaml):
global func_str
legalize_field = '''
function legalize_{0}_{1}(o: {2}, v: {2}) -> {2} = {{
m: {2} = v;
{3}
m
}}
'''
warl_range_temp = \
''' let warl_range_list: list(WARL_range_type) = [|{0}|];'''
legalize_field_strs = 'illegal: bool = false;\n' + \
' let warl_range_list: list(WARL_range_type) = [||];\n'
warl = field_yaml['type']['warl']
# parsing the legal string
for legal_str in warl['legal']:
if '->' in legal_str:
dep_str = legal_str.split('->')[0]
csr_str = legal_str.split('->')[1]
dep_str = parse_dependency(reg, dep_str,
warl['dependency_fields'])
legalize_field_strs += ' if ' + dep_str + ' then {\n '
else:
csr_str = legal_str
legalize_field_strs += ' {\n '
range_list = parse_field_range(csr_str)
if 'bitmask' not in csr_str:
legalize_field_strs += warl_range_temp.format(range_list) + '\n'
legalize_field_strs += \
' if (~(is_value_in_rangelist(v, warl_range_list))) ' + \
'then illegal = true;\n };\n\n'
else:
legalize_field_strs += ' m = legalize_warl_either(o , m, ' + \
'WARL_bitmask(' + range_list + '), WARL_Unchanged);\n };\n\n'
# parsing the wr_illegal string
for illegal_str in warl['wr_illegal']:
if '->' in illegal_str:
dep_str = illegal_str.split('->')[0]
mode = illegal_str.split('->')[1].strip()
op = re.findall(r'\s*wr_val\s*in\s*\[(.*?)\]', dep_str)
dep_str = parse_dependency(reg, dep_str,
warl['dependency_fields'])
if dep_str != '':
dep_str = ' & ' + dep_str
if op != []:
wr_value_temp = \
''' let wr_value_rangelist: list(WARL_range_type) = [|{0}|];
'''
parse_str = parse_values(op[0], 0xffffffffffffffff, 1, False)
wr_value_temp.format(parse_str)
legalize_field_strs += ' if illegal == true' + dep_str + \
' & is_value_in_range(v, wr_value_rangelist) then '
else:
legalize_field_strs += ' if illegal == true' + dep_str + \
' then \n'
else:
legalize_field_strs += ' if illegal == true then \n'
mode = illegal_str.strip()
if '0x' in mode:
legalize_field_strs += ' m = ' + mode + ';'
else:
legalize_field_strs += \
' m = legalize_warl_either(o , m, WARL_range_list' + \
'(warl_range_list), WARL_' + mode.title() + ');\n'
func_str += legalize_field.format(
reg.lower(), field.upper(), 'bits(' +
str(int(field_yaml['msb']) - int(field_yaml['lsb']) + 1) + ')',
legalize_field_strs)
# function for parsing warl field
def parse_warl_field(reg, field, field_yaml):
warl = field_yaml['type']['warl']
dependencies = warl['dependency_fields']
if dependencies == []: # field without dependencies
legalize_without_dependencies(reg, field, field_yaml)
else: # field with dependencies
legalize_with_dependencies(reg, field, field_yaml)
# function for field parsing
def parse_field(reg, field_name, field_yaml, len, real_len):
global parsed_warl_fields
global parsed_regs
assign_str = ''
get_str = ''
if field_yaml['shadow'] is not None: # shadow field
if field_yaml['shadow_type'] == 'rw': # rw shadow field
shadow = field_yaml['shadow'].lower()
if '.' in shadow: # shadow field is a field
shadow_reg = shadow.split('.')[0]
shadow_field = shadow.split('.')[1]
if shadow_reg not in parsed_regs:
print("please make reg %s before %s: %s\n"
% (shadow_reg, reg, str(parsed_regs)))
raise SystemExit
if shadow in parsed_warl_fields:
assign_str += \
' %s = update_%s(%s,' \
% (shadow_reg, shadow_field.upper(), shadow_reg) + \
' legalize_%s_%s(%s.%s(), v[%d .. %d]));\n' \
% (shadow_reg, shadow_field.upper(),
shadow_reg, shadow_field.upper(),
int(field_yaml['msb']), int(field_yaml['lsb']))
else:
assign_str += ' %s = update_%s(%s, v[%d .. %d]);\n' \
% (shadow_reg, shadow_field.upper(), shadow_reg,
int(field_yaml['msb']), int(field_yaml['lsb']))
shadow = shadow_reg + '.' + shadow_field.upper() + '()'
else: # shadow field is a total reg
assign_str += ' %s = legalize_%s(%s, EXTZ(v[%d .. %d]));\n' \
% (shadow, shadow, shadow, int(field_yaml['msb']),
int(field_yaml['lsb']))
if field_name == 'total': # total reg as a field
if len != real_len: # field doesn't begin from bit 0
assign_str += ' let m = %s @ 0b' % (shadow, len - 1,
len - real_len) + \
('0' * (len - real_len)) + ';\n'
get_str = ' let m = %s @ 0b' % (shadow, len - 1,
len - real_len) + \
('0' * (len - real_len)) + ';\n'
else: # field begins from bit 0
get_str += ' let m = %s;\n' % shadow
else: # for normal field
get_str += ' let m = update_' + field_name.upper() + \
'(m, %s);\n' % shadow
assign_str += get_str
else: # read only shadow field
if field_name == 'total':
assign_str += ' let m = o;\n'
else:
assign_str += ' let m = update_' + field_name.upper() + \
'(m, o.' + field_name.upper() + '());\n'
elif 'ro_constant' in field_yaml['type']: # ro_constant field
ro_constant = field_yaml['type']['ro_constant']
if 'x' in str(ro_constant):
ro_constant = 'unsigned(' + ro_constant + ')'
if field_name == 'total':
if len != real_len:
assign_str = ' let m = to_bits(%d, %s) @ 0b' \
% (real_len, str(ro_constant)) + \
('0' * (len - real_len)) + ';\n'
else:
assign_str = ' let m: bits(%d) = EXTZ(0x%x);\n' \
% (len, ro_constant)
else:
assign_str = ' let m = update_' + field_name.upper() + \
'(m , to_bits(%d, %s));\n' % (len, str(ro_constant))
elif 'ro_variable' in field_yaml['type']: # ro_variable field
if field_name == 'total':
assign_str = ' let m = o;\n'
else:
assign_str = ' let m = update_' + field_name.upper() + \
'(m, o.' + field_name.upper() + '());\n'
elif 'warl' in field_yaml['type']: # warl field
parse_warl_field(reg, field_name, field_yaml)
if field_name == 'total': # total reg as a field
parsed_warl_fields.append(reg.lower())
if len != real_len:
assign_str += ' let m = legalize_' + reg.lower() + '_' + \
field_name.upper() + '(o[%d .. %d] , v[%d .. %d]) @ 0b' \
% (len - 1, len - real_len, len - 1, len - real_len) + \
('0' * (len - real_len)) + ';\n'
else:
assign_str += ' let m = legalize_' + reg.lower() + '_' + \
field_name.upper() + '(o[%d .. %d] , v[%d .. %d]);\n' \
% (len - 1, len - real_len, len - 1, len - real_len)
else: # normal field
parsed_warl_fields.append(reg.lower() + '.' + field_name.lower())
assign_str = ' let m = update_' + field_name.upper() + \
'(m, legalize_' + reg.lower() + '_' + field_name.upper() + \
'(o.' + field_name.upper() + '()' + ', m.' + \
field_name.upper() + '()));\n'
else: # other type field
if field_name == 'total':
if len != real_len:
assign_str = ' let m = v[%d .. %d] @ 0b' \
% (len - 1, len - real_len) + ('0' * (len - real_len)) + \
';\n'
else:
assign_str = ' let m = v[%d .. %d];\n' % (len - 1, 0)
return (get_str, assign_str)
# function for total csr reg parsing
def parse_reg(reg, xlen, isa_yaml):
global func_str
global regs_str
global reset_str
global write_str
global read_str
reg_subfield_struct = '''
bitfield {0}: xlenbits = {{
{1}
}}
register {2}: {0}
'''
reg_without_subfield_struct = '''
type {0} = bits({1})
register {2}: {0}
'''
legalize_func = '''
function legalize_{0}(o: {1}, v: xlenbits) -> {1} = {{
let m = Mk_{1}(v);
{2} m
}}
'''
legalize_func_without_subfield = '''
function legalize_{0}(o: {1}, v: xlenbits) -> {1} = {{
{2} m
}}
'''
get_func = '''
function get_{0}(o: {1}) -> {1} = {{
let m = o;
{2} m
}}
'''
fields_str = ''
assign_field_strs = ''
get_shadow_fields = ''
if isa_yaml[reg]['rv' + xlen]['fields'] != []: # parse reg with subfield
for field in reversed(isa_yaml[reg]['rv' + xlen]):
if field in isa_yaml[reg]['rv' + xlen]['fields']:
if isa_yaml[reg]['rv' + xlen][field]['implemented']:
# compute length of field
len = int(isa_yaml[reg]['rv' + xlen][field]['msb']) - \
int(isa_yaml[reg]['rv' + xlen][field]['lsb']) + 1
# parse field
(get_str, assign_str) = parse_field(
reg, field, isa_yaml[reg]['rv' + xlen][field], len,
len)
if get_str != '': # shadow field
fields_str += '/* shadow field of %s*/\n' \
% isa_yaml[reg]['rv' + xlen][field]['shadow']
# generate field range string according field length
if isa_yaml[reg]['rv' + xlen][field]['msb'] != \
isa_yaml[reg]['rv' + xlen][field]['lsb']:
fields_str += field.upper() + ': ' + \
str(isa_yaml[reg]['rv' + xlen][field]['msb']) + \
' .. ' + \
str(isa_yaml[reg]['rv' + xlen][field]['lsb']) + \
',\n'
else:
fields_str += field.upper() + ': ' + \
str(isa_yaml[reg]['rv' + xlen][field]['msb']) + \
',\n'
assign_field_strs += assign_str
get_shadow_fields += get_str
# generate sail code for reg structure
regs_str += reg_subfield_struct.format(reg.title(), fields_str[:-2],
reg.lower())
# generate sail code for csr reset function
reset_str += ' %s->bits() = EXTZ(0x%x);\n' \
% (reg, isa_yaml[reg]['reset-val'])
# generate sail code for csr legalize function
func_str += legalize_func.format(reg.lower(), reg.title(),
assign_field_strs)
if get_shadow_fields != '': # shadow field
# generate sail code for csr legalize function
func_str += get_func.format(reg.lower(), reg.title(),
get_shadow_fields)
# generate sail code for csr read function
read_str += \
' 0x%03x => { let m = get_%s(%s); Some(m.bits()) },\n' \
% (isa_yaml[reg]["address"], reg, reg)
else: # normal field
# generate sail code for csr read function
read_str += ' 0x%03x => Some(%s.bits()),\n' \
% (isa_yaml[reg]['address'], reg)
# generate sail code for csr write function
write_str += \
' 0x%03x => { %s = legalize_%s(%s, value); Some(%s' \
% (isa_yaml[reg]["address"], reg, reg, reg, reg) + \
'.bits()) },\n'
else: # parse reg without subfield
# compute the real length of csr without subfield
real_len = int(isa_yaml[reg]['rv' + xlen]['msb']) - \
int(isa_yaml[reg]['rv' + xlen]['lsb']) + 1
# compute the length (from bit 0) of csr without subfield
len = int(isa_yaml[reg]['rv' + xlen]['msb']) + 1
regs_str += reg_without_subfield_struct.format(reg.title(), len, reg)
# extend the length to mutiple of four
if (int(isa_yaml[reg]['rv' + xlen]['msb']) % 4 != 0):
reset_str += ' %s = to_bits(%d, unsigned(0x%x));\n' \
% (reg, len, isa_yaml[reg]['reset-val'])
else:
reset_str += \
' %s = EXTZ(0x%x);\n' % (reg, isa_yaml[reg]['reset-val'])
# parse field
(get_str, assign_str) = parse_field(
reg, 'total', isa_yaml[reg]['rv' + xlen], len, real_len)
assign_field_strs += assign_str
get_shadow_fields += get_str
# generate sail code for csr legalize/read/write function
func_str += legalize_func_without_subfield.format(
reg.lower(), 'bits(%d)' % len, assign_field_strs)
if get_shadow_fields != '':
func_str += get_func.format(reg.lower(), 'bits(%d)' % len,
get_shadow_fields)
if len != int(xlen):
read_str += ' 0x%03x => Some(EXTZ(get_%s(%s))),\n' \
% (isa_yaml[reg]['address'], reg, reg)
else:
read_str += ' 0x%03x => Some(get_%s(%s)),\n' \
% (isa_yaml[reg]['address'], reg, reg)
else:
if len != int(xlen):
read_str += ' 0x%03x => Some(EXTZ(%s)),\n' \
% (isa_yaml[reg]['address'], reg)
else:
read_str += ' 0x%03x => Some(%s),\n' \
% (isa_yaml[reg]['address'], reg)
if len != int(xlen):
write_str += ' 0x%03x => { %s = legalize_%s(%s, value);' \
% (isa_yaml[reg]["address"], reg, reg, reg) + \
' Some(EXTZ(%s)) },\n' % reg
else:
write_str += ' 0x%03x => { %s = legalize_%s(%s, value);' \
% (isa_yaml[reg]["address"], reg, reg, reg) + \
' Some(%s) },\n' % reg
return
arch = ''
generate_dir = 'generated_definitions/riscv-config'
try:
opts, args = getopt.getopt(sys.argv[1:], "a:i:p:",
["arch= ", "isa_yaml=", "platform_yaml="])
for k, v in opts:
if k in ("-a", "--arch"):
arch = v
elif k in ("-i", "--isa-yaml"):
isa_yaml = v
elif k in ("-p", "--platform-yaml"):
platform_yaml = v
except getopt.GetoptError:
print('[getopt.GetoptError]')
sys.exit()
if arch not in ['32', '64']:
print('please specify the arch: 32 or 64!')
sys.exit()
else:
isa_yaml = load_yaml(isa_yaml)['hart0']
plat_yaml = load_yaml(platform_yaml)
xlen = str(max(isa_yaml['supported_xlen']))
parsed_warl_fields = []
parsed_regs = []
regs_str = '' # sail code for csr structue
func_str = warl_type_and_func # sail code for csr legalize function
reset_str = '' # sail code for reset function of csrs
read_str = '' # sail code for read function of csrs
write_str = '' # sail code for write function of csrs
define_str = '' # sail code for defined function of csrs
map_str = '' # sail code for map function of csrs and their names
reset_func = '''
function reset_regs() -> unit = {{
{0}
}}
'''
read_func = '''
function read_csr(csr: csreg) -> option(xlenbits) = {{
let res: option(xlenbits) =
match (csr) {{
{0}
_ => None()
}};
res
}}
'''
write_func = '''
function write_csr(csr: csreg, value: xlenbits) -> option(xlenbits) = {{
let res: option(xlenbits) =
match (csr) {{
{0}
_ => None()
}};
res
}}
'''
define_func = '''
function is_csr_defined (csr: csreg, p: Privilege) -> bool = match (csr) {{
{0}
_ => false
}}
'''
csr_map = '''
val csr_name_map: csreg <-> string
scattered mapping csr_name_map
{0}
/* trigger/debug */
mapping clause csr_name_map = 0x7a0 <-> "tselect"
mapping clause csr_name_map = 0x7a1 <-> "tdata1"
mapping clause csr_name_map = 0x7a2 <-> "tdata2"
mapping clause csr_name_map = 0x7a3 <-> "tdata3"
val csr_name: csreg -> string
overload to_str = {{csr_name}}
mapping clause csr_name_map = reg <-> hex_bits_12(reg)
end csr_name_map
/* XXX due to an apparent Sail bug the definition of this function must appear
after the last csr_name_map clause and not by the val spec as it was
previously. */
function csr_name(csr) = csr_name_map(csr)
'''
# isa_yaml -> {regs}
# reg -> {fields}
# field -> {shadow, warl, ro_constant, ...}
# warl_field -> {with dependency, without dependency}
for reg in isa_yaml:
if reg not in ['custom_exceptions', 'custom_interrupts', 'ISA',
'supported_xlen', 'pmp_granularity',