-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhdlregs.py
1325 lines (1232 loc) · 51.1 KB
/
hdlregs.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/python
# Copyright (c) 2013, Guy Eschemann
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are those
# of the authors and should not be interpreted as representing official policies,
# either expressed or implied, of the FreeBSD Project.
import re
import sys
import json
import datetime
from string import Template
# ------------------------------------------------------------------------------
# Constants
#
HDLREGS_VERSION = "0.5"
INDENTATION_WIDTH = 4
RESERVED_VHDL_KEYWORDS = ("abs", "access", "after", "alias", "all", "and", "architecture", "array", "assert", "attribute", "begin", "block", "body", "buffer", "bus", "case", "component", "configuration", "constant", "disconnect", "downto", "else", "elsif", "end", "entity", "exit", "file", "for", "function", "generate", "generic", "group", "guarded", "if", "impure", "in", "inertial", "inout", "is", "label", "library", "linkage", "literal", "loop", "map", "mod", "nand", "new", "next", "nor", "not", "null", "of", "on", "open", "or", "others", "out", "package", "port", "postponed", "procedure", "process", "pure", "range", "record", "register", "reject", "rem", "report", "return", "rol", "ror", "select", "severity", "signal", "shared", "sla", "sll", "sra", "srl", "subtype", "then", "to", "transport", "type", "unaffected", "units", "until", "use", "variable", "wait", "when", "while", "with", "xnor", "xor")
RESERVED_C_KEYWORDS = ("auto", "else", "long", "switch", "break", "enum", "register", "typedef", "case", "extern", "return", "union", "char", "float", "short", "unsigned", "const", "for", "signed", "void", "continue", "goto", "sizeof", "volatile", "default", "if", "static", "while", "do", "int", "struct", "_Packed", "double")
# ------------------------------------------------------------------------------
# String templates for C, VHDL and HTML documents
#
HTML_DOC_TEMPLATE = Template("""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Registers in '$module_name' module</title>
<style type="text/css" media="screen,print">
body, html{
margin:0;
padding:0;
font-family:Verdana,Geneva,Arial,sans-serif;
font-size: small;
}
h1 {
margin:0;
}
/* registers table */
table.register {
border: thin solid #aaa;
border-collapse: collapse;
border-spacing:0;
}
table.register tr.Header{
background-color: #edf0f9;
height: 2em;
font-size: 125%;
}
table.register td.RegisterAddr {
width: 10em;
text-align: left;
font-weight: bold;
padding: 5px;
}
table.register td.RegisterName {
font-weight: bold;
padding: 5px;
}
table.register td.RegisterDescription {
border-bottom: thin solid #aaa;
padding: 5px;
padding-top: 0;
background-color: #edf0f9;
}
table.register td.BitFieldIndex {
padding-right: 1em;
padding-top: 3px;
width: 5em; text-align: right;
vertical-align: top;
border-top: thin solid #aaa;
}
table.register td.BitFieldName {
width: 25em;
text-align: left;
border-top: thin solid #aaa;
font-weight: bold;
}
table.register td.BitFieldMode {
width: 3em;
text-align: left;
border-top: thin solid #aaa;
}
table.register td.BitFieldReset {
text-align: left;
vertical-align: top;
border-top: thin solid #aaa;
}
/* overview table format */
table#overview{
width: 200px;
border: none;
}
table#overview tr {
height: 1.5em;
}
table#overview td {
padding-left: 1em;
}
.even{
background-color: #eee;
}
a.overview {
color: black;
text-decoration: none;
}
#footer p {
margin:0;
}
#sidebar ul {
margin:0;
padding:0;
list-style:none;
}
div#wrap {
width:750px;
margin:1em auto;
border: solid 2px #aaa;
padding: 5px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
-o-border-radius: 10px;
-ms-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 3px;
}
div#header {
padding:10px 10px;
/*border-width: 0 0 0.1em 0;*/
/*border-style: double;*/
border-color: #aaa;
}
div#footer {
clear:both; /*push footer down*/
padding:5px 10px;
text-align:center;
border-width: 0.1em 0 0 0;
border-style: double;
border-color: #aaa;
font-size: x-small;
}
div#sidebar {
width:200px; /* subtract padding from actual width*/
float:left;
padding:10px;
}
div#main {
width: 510px; /* subtract padding from actual width*/
float:right;
padding:10px;
}
</style>
</head>
<body>
<div id="wrap">
<div id="header">
<h1>Registers in '$module_name' module</h1>
</div>
<div id="sidebar">
<h2>Overview</h2>
$overview
</div>
<div id="main">
<h2>Detailed description</h2>
$registers
</div>
<div id="footer">
<p>Generated: $date_time by <a href="https://github.com/noasic/hdlregs">HDLRegs</a> version $hdlregs_version</p>
</div>
</div>
</body>
</html>""")
# ------------------------------------------------------------------------------
HTML_REGISTER_TEMPLATE = Template("""
<p>
<a id="$register_name"></a>
<table class="register">
<tr class="Header">
<td class="RegisterName" colspan="3">$register_name</td>
<td class="RegisterAddr">$register_addr_offset</td>
</tr>
<tr>
<td class="RegisterDescription" colspan="4">$register_description</td>
</tr>
$register_fields
</table>
</p>""") # html_register_template
# ------------------------------------------------------------------------------
HTML_REGISTER_FIELD_TEMPLATE = Template("""
<tr class="BitField">
<td class="BitFieldIndex" rowspan="2">[$field_range]</td>
<td class="BitFieldName">$field_name</td>
<td class="BitFieldMode">$field_access</td>
<td class="BitFieldReset">Reset: $field_reset</td>
</tr>
<tr>
<td class="BitFieldDescription">$field_description</td>
<td> </td>
<td class="BitFieldSelfClear">$field_selfClear</td>
</tr>
""") # html_register_field_template
# ------------------------------------------------------------------------------
c_header_template = Template("""
// Header for module '${json_module_name}'
// automatically generated by HDLRegs version $hdlregs_version on $date_time
#ifndef ${module_name}_H
#define ${module_name}_H
//
// Register address offsets
//
$address_offsets
$fields
#endif // ${module_name}_H
""")
# ------------------------------------------------------------------------------
vhdl_package_template = Template("""
-- VHDL package for module '${json_module_name}'
-- automatically generated by HDLRegs version $hdlregs_version on $date_time
library ieee;
use ieee.std_logic_1164.all;
package $package_name is
$declarations
end package $package_name;
""")
# ------------------------------------------------------------------------------
vhdl_component_template = Template("""
-- VHDL component for module '${json_module_name}'
-- automatically generated by HDLRegs version $hdlregs_version on $date_time
library ieee;
use ieee.std_logic_1164.all;
use work.$package_name.all;
entity $entity_name is
port(
clk : in std_logic; -- system clock
rst : in std_logic; -- synchronous, high-active
addr : in std_logic_vector(31 downto 0); -- read/write address
cs : in std_logic; -- chip select
rnw : in std_logic; -- read (1) or write (0)
datain : in std_logic_vector(31 downto 0); -- write data
dataout : out std_logic_vector(31 downto 0); -- read data
--
regs2user : out t_regs2user; -- register file -> user logic
user2regs : in t_user2regs -- user logic -> register file
);
end entity $entity_name;
architecture RTL of $entity_name is
$signal_declarations
begin
$register_write_proc
$register_read_proc
$concurrent_signal_assignments
end architecture RTL;
""")
# ------------------------------------------------------------------------------
# VHDL code blocks
#
class VhdlRecord:
#
def __init__(self, name, description, elements):
self.name = name
self.description = description
self.elements_ = elements
#
def add_element(self, element):
self.elements_.append(element)
#
def __str__(self):
raise NotImplementedError
#
def to_str(self, level):
str = '\n'
str += indent(level) + "-- %s\n" % self.description
str += indent(level) + "type %s is record\n" % self.name
level += 1
for e in self.elements_:
str += indent(level) + e + ";\n"
level -= 1
str += indent(level) + "end record;\n"
return str
#
def name(self):
return self.name
#
# Returns the number elements within the record
def num_elements(self):
return len(self.elements_)
class VhdlPackage:
#
def __init__(self, name):
self.name = name
self.declarations_ = []
#
def add_declaration(self, declaration):
self.declarations_.append(declaration)
#
def __str__(self):
str_declarations = ''
for d in self.declarations_:
str_declarations += d.to_str(1)
d = dict(package_name = self.name,
declarations = str_declarations,
json_module_name = module.name,
hdlregs_version = HDLREGS_VERSION,
date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
return vhdl_package_template.substitute(d)
class VhdlIfStatement:
#
def __init__(self, condition):
self._condition = condition
self.statements = []
#
def to_str(self, level):
str = indent(level) + 'if %s then\n' % self._condition
level += 1
for s in self.statements:
str += "%s" % s.to_str(level)
level -= 1
str += indent(level) + 'end if;\n'
return str
#
def __str__(self):
raise NotImplementedError
class VhdlClockedProcess:
#
def __init__(self, name, clock, reset):
self.name = name
self.clock = clock
self.reset = reset
self.reset_statements = []
self.statements = []
#
def to_str(self, level):
s = indent(level) + '%s : process(%s) is\n' % (self.name, self.clock)
s += indent(level) + 'begin\n'
level += 1
s += indent(level) + "if rising_edge(%s) then\n" % self.clock
level += 1
s += indent(level) + "if %s = '1' then\n" % self.reset
level += 1
for st in self.reset_statements:
s += "%s" % st.to_str(level)
level -= 1
s += indent(level) + "else\n"
level += 1
for st in self.statements:
s += st.to_str(level)
level -= 1
s += indent(level) + "end if;\n"
level -= 1
s += indent(level) + "end if;\n"
level -= 1
s += indent(level) + 'end process %s;\n' % self.name
return s
#
def __str__(self):
raise NotImplementedError
class VhdlAsyncProcess():
#
def __init__(self, name):
self.name = name
self.sensitivity = []
self.statements = []
#
def to_str(self, level):
if len(self.sensitivity) > 0:
sensitivity = "(%s)" % (','.join(self.sensitivity))
else:
sensitivity = ''
s = indent(level) + '%s : process %s is\n' % (self.name, sensitivity)
s += indent(level) + 'begin\n'
level += 1
for st in self.statements:
s += st.to_str(level)
level -= 1
s += indent(level) + 'end process %s;\n' % self.name
return s
#
def __str__(self):
raise NotImplementedError
class VhdlCodeBlock():
#
def __init__(self):
self.statements = []
#
def to_str(self, level):
s = '\n'
for st in self.statements:
s += st.to_str(level)
return s
#
def __str__(self):
raise NotImplementedError
class VhdlStatement():
#
def __init__(self, value):
self._value = value
#
def to_str(self, level):
return indent(level) + self._value
#
def __str__(self):
raise NotImplementedError
class VhdlDeclaration():
#
def __init__(self, value):
self._value = value
#
def to_str(self, level):
return indent(level) + self._value
#
def __str__(self):
raise NotImplementedError
# ------------------------------------------------------------------------------
# Code generators
#
#
# The mother of all code generators
#
class CodeGenerator():
#
# Returns a field's bit width identifier, e.g. 'WIDTH_CONTROL_RESET'
def bitWidth_identifier(self, field):
return 'WIDTH_' + field.parent_reg.name.upper() + '_' + field.name.upper()
#
# Returns a field's bit offset identifier, e.g. 'OFFSET_CONTROL_RESET'
def bitOffset_identifier(self, field):
return 'OFFSET_' + field.parent_reg.name.upper() + '_' + field.name.upper()
#
# Returns a field's bit mask identifier, e.g. 'MASK_CONTROL_RESET'
def bitMask_identifier(self, field):
return 'MASK_' + field.parent_reg.name.upper() + '_' + field.name.upper()
#
# Returns the name of the record type corresponding to this field
def vhdl_record_name(self, field):
return 't_' + field.parent_reg.name.lower() + '_' + field.name.lower()
#
# Returns the name of the VHDL package for a module
def vhdl_package_name(self, module):
return module.name.lower() + '_regs_pkg'
#
# Return a register's address identifier, e.g. 'ADDR_CONTROL'
def address_identifier(self, register):
return "ADDR_" + register.name.upper()
#
# Get a registers's data signal name
def vhdl_data_signal(self, register):
return 's_' + register.name.lower() + "_r"
#
# Get a registers's strobe signal name
def vhdl_strobe_signal(self, register):
return 's_' + register.name.lower() + "_strobe_r"
#
# Returns the name of the VHDL entity for a module
def vhdl_entity_name(self, module):
return module.name.lower() + '_regs'
#
# VHDL component generator
#
class VhdlComponentGenerator(CodeGenerator):
def __init__(self, module):
#
# Signal declarations
signal_declarations = VhdlCodeBlock()
for r in module.registers:
signal_declarations.statements.append(VhdlStatement('signal %s : std_logic_vector(31 downto 0) := x"%.8X";\n' % (self.vhdl_data_signal(r), r.reset())))
if r.is_bus_writable():
signal_declarations.statements.append(VhdlStatement("signal %s : std_logic := '0';\n" % (self.vhdl_strobe_signal(r))))
#
# Register-write process
register_write_proc = VhdlClockedProcess("register_write", "clk", "rst")
# resets
for r in module.registers:
register_write_proc.reset_statements.append(VhdlStatement('%s <= x"%.8X";\n' % (self.vhdl_data_signal(r), r.reset())))
# defaults
register_write_proc.statements.append(VhdlStatement("-- defaults:\n"))
for r in module.registers:
if r.is_bus_writable():
register_write_proc.statements.append(VhdlStatement("%s <= '0';\n" % self.vhdl_strobe_signal(r)))
# self-clearing fields
register_write_proc.statements.append(VhdlStatement("-- self-clearing fields:\n"))
for r in module.registers:
if r.is_bus_writable():
reg_data_signal = self.vhdl_data_signal(r)
for f in r.fields:
if f.selfClear:
index_high = "%s + %s - 1" % (self.bitOffset_identifier(f), self.bitWidth_identifier(f))
index_low = self.bitOffset_identifier(f)
register_write_proc.statements.append(VhdlStatement("%s(%s downto %s) <= (others => '0');\n" % (reg_data_signal, index_high, index_low)))
# bus-write
register_write_proc.statements.append(VhdlStatement("-- bus write:\n"))
bus_write_block = VhdlIfStatement("cs = '1' and rnw = '0'")
for r in module.registers:
reg_data_signal = self.vhdl_data_signal(r)
reg_strobe_signal = self.vhdl_strobe_signal(r)
if r.is_bus_writable():
register_write_block = VhdlIfStatement("addr = %s" % self.address_identifier(r))
for f in r.fields:
if f.is_bus_writable():
index_high = "%s + %s - 1" % (self.bitOffset_identifier(f), self.bitWidth_identifier(f))
index_low = self.bitOffset_identifier(f)
register_write_block.statements.append(VhdlStatement("%s(%s downto %s) <= datain(%s downto %s);\n" % (reg_data_signal, index_high, index_low, index_high, index_low)))
register_write_block.statements.append(VhdlStatement("%s <= '1';\n" % (reg_strobe_signal)))
bus_write_block.statements.append(register_write_block)
register_write_proc.statements.append(bus_write_block)
# user-logic write
register_write_proc.statements.append(VhdlStatement("-- user-logic write:\n"))
for r in module.registers:
for f in r.fields:
if f.is_user_writable():
field_write_block = VhdlIfStatement("user2regs.%s.%s.strobe = '1'" % (r.name, f.name))
field_write_block.statements.append(VhdlStatement("%s(%s + %s - 1 downto %s) <= user2regs.%s.%s.value;\n" % (self.vhdl_data_signal(r), self.bitOffset_identifier(f), self.bitWidth_identifier(f), self.bitOffset_identifier(f), r.name, f.name)))
register_write_proc.statements.append(field_write_block)
#
# Bus-read process
bus_read_proc = VhdlAsyncProcess("bus_read")
bus_read_proc.sensitivity.append('cs')
bus_read_proc.sensitivity.append('rnw')
bus_read_proc.sensitivity.append('addr')
bus_read_proc.statements.append(VhdlStatement("dataout <= (others => 'X'); -- default\n"))
cs_block = VhdlIfStatement("cs = '1' and rnw = '1'")
for r in module.registers:
if r.is_bus_readable():
bus_read_proc.sensitivity.append(self.vhdl_data_signal(r))
reg_read_block = VhdlIfStatement("addr = %s" % self.address_identifier(r))
for f in r.fields:
if f.is_bus_readable():
index_high = "%s + %s - 1" % (self.bitOffset_identifier(f), self.bitWidth_identifier(f))
index_low = self.bitOffset_identifier(f)
reg_read_block.statements.append(VhdlStatement("dataout(%s downto %s) <= %s(%s downto %s);\n" % (index_high, index_low, self.vhdl_data_signal(r), index_high, index_low)))
cs_block.statements.append(reg_read_block)
bus_read_proc.statements.append(cs_block)
#
# Concurrent signal assignments
concurrent_signal_assignments = VhdlCodeBlock()
for r in module.registers:
for f in r.fields:
if f.is_bus_writable():
concurrent_signal_assignments.statements.append(VhdlStatement("regs2user.%s.%s.value <= %s(%s + %s - 1 downto %s);\n" % (r.name, f.name, self.vhdl_data_signal(r), self.bitOffset_identifier(f), self.bitWidth_identifier(f), self.bitOffset_identifier(f))))
concurrent_signal_assignments.statements.append(VhdlStatement("regs2user.%s.%s.strobe <= %s;\n" % (r.name, f.name, self.vhdl_strobe_signal(r))))
d = dict(entity_name = self.vhdl_entity_name(module),
signal_declarations = signal_declarations.to_str(1),
package_name = self.vhdl_package_name(module),
register_write_proc = register_write_proc.to_str(1),
concurrent_signal_assignments = concurrent_signal_assignments.to_str(1),
register_read_proc = bus_read_proc.to_str(1),
json_module_name = module.name,
hdlregs_version = HDLREGS_VERSION,
date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
self._code = vhdl_component_template.substitute(d)
#
# Save the generated VHDL component to a file
def save(self, filename):
with open(filename, 'w') as f:
f.write(self._code)
#
# VHDL package generator
#
class VhdlPackageGenerator(CodeGenerator):
def __init__(self, module):
vhdl_package = VhdlPackage(self.vhdl_package_name(module))
# Interface record types
user2regs = VhdlRecord('t_user2regs', 'User-logic -> register file interface', [])
regs2user = VhdlRecord('t_regs2user', 'Register file -> user-logic interface', [])
# Register address offsets
for r in module.registers:
vhdl_package.add_declaration(VhdlDeclaration('constant %s : std_logic_vector(31 downto 0) := x"%.8X";\n' % (self.address_identifier(r), r.addressOffset)))
# Lowest address in register file
identifier = module.name.upper() + "_REGS_BASEADDR"
base_register_identifier = self.address_identifier(module.base_register())
vhdl_package.add_declaration(VhdlDeclaration('constant %s : std_logic_vector(31 downto 0) := %s; -- lowest register address\n' % (identifier, base_register_identifier)))
# Highest address in register file
identifier = module.name.upper() + "_REGS_HIGHADDR"
high_register_identifier = self.address_identifier(module.high_register())
vhdl_package.add_declaration(VhdlDeclaration('constant %s : std_logic_vector(31 downto 0) := %s; -- highest register address\n' % (identifier, high_register_identifier)))
# Field constants:
for r in module.registers:
for f in r.fields:
vhdl_package.add_declaration(self.to_vhdl_constants(f))
# Field record types
field_types = ''
for r in module.registers:
for f in r.fields:
description = "Field '%s' of register '%s' (%s)" % (f.name, r.name, f.access())
elements = []
elements.append("value : std_logic_vector(%s - 1 downto 0)" % (self.bitWidth_identifier(f)))
elements.append("strobe : std_logic")
record = VhdlRecord(self.vhdl_record_name(f), description, elements)
vhdl_package.add_declaration(record)
# Register record types (XXX_regs2user and/or XXX_user2regs)
for r in module.registers:
records = self.to_vhdl_records(r)
for record in records:
if record.name.endswith('user2regs'):
user2regs.add_element(r.name + ": " + record.name)
if record.name.endswith('regs2user'):
regs2user.add_element(r.name + ": " + record.name)
vhdl_package.add_declaration(record)
# Add dummy signals in case of empty records, as these are not allowed in VHDL
if 0 == user2regs.num_elements():
user2regs.add_element("dummy : std_logic")
if 0 == regs2user.num_elements():
regs2user.add_element("dummy : std_logic")
#
vhdl_package.add_declaration(user2regs)
vhdl_package.add_declaration(regs2user)
self._code = str(vhdl_package)
#
# Generate VHDL constants for a field
def to_vhdl_constants(self, field):
field_name = field.name.upper()
field_mask = (2 ** field.bitWidth - 1) << field.bitOffset
code_block = VhdlCodeBlock()
code_block.statements.append(VhdlStatement("-- Field '%s' of register '%s'\n" % (field.name, field.parent_reg.name)))
code_block.statements.append(VhdlDeclaration("constant %s : natural := %d;\n" % (self.bitOffset_identifier(field), field.bitOffset)))
code_block.statements.append(VhdlDeclaration("constant %s : natural := %d;\n" % (self.bitWidth_identifier(field), field.bitWidth)))
code_block.statements.append(VhdlDeclaration('constant %s : std_logic_vector(31 downto 0) := x"%.8X";\n' % (self.bitMask_identifier(field), field_mask)))
return code_block
#
# Generate VHDL record types for a register
def to_vhdl_records(self, register):
records = []
# user-writable fields:
name = "t_%s_user2regs" % (register.name)
description = "Register '%s'" % register.name
elements = []
for f in register.fields:
if f.access() == "read-only":
elements.append('%s : %s' % (f.name, self.vhdl_record_name(f)))
if len(elements) > 0:
records.append(VhdlRecord(name, description, elements))
# bus-writable fields:
name = "t_%s_regs2user" % (register.name)
description = "Register '%s'" % register.name
elements = []
for f in register.fields:
if f.access() == "read-write" or f.access() == "write-only":
elements.append('%s : %s' % (f.name, self.vhdl_record_name(f)))
if len(elements) > 0:
records.append(VhdlRecord(name, description, elements))
return records
#
def save(self, filename):
with open(filename, 'w') as f:
f.write(self._code)
#
# C header generator
#
class CHeaderGenerator(CodeGenerator):
def __init__(self, module):
# Register address offsets
address_offsets = ""
for r in module.registers:
address_offsets += '#define %s 0x%.8X\n' % (self.address_identifier(r), r.addressOffset)
# Field bit offsets
fields = ""
for r in module.registers:
register_name = r.name.upper()
fields += "//\n"
fields += "// Fields in register '%s'\n" % register_name
fields += "//\n"
for f in r.fields:
field_name = f.name.upper()
field_mask = (2 ** f.bitWidth - 1) << f.bitOffset
fields += "// Field '%s'\n" % f.name
fields += "#define %s %d\n" % (self.bitOffset_identifier(f), f.bitOffset)
fields += "#define %s %d\n" % (self.bitWidth_identifier(f), f.bitWidth)
fields += "#define %s 0x%.8X\n" % (self.bitMask_identifier(f), field_mask)
fields += "\n"
fields += "\n"
module_name = module.name.upper() + "_REGS"
d = dict(module_name = module_name,
address_offsets = address_offsets,
fields = fields,
json_module_name = module.name,
hdlregs_version = HDLREGS_VERSION,
date_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
self._code = c_header_template.substitute(d)
def save(self, filename):
with open(filename, 'w') as f:
f.write(self._code)
#
# HTML code generator
#
class HtmlGenerator():
def __init__(self, module):
# HTML overview list
html_overview = indent(4) + '<table id="overview">\n'
html_cell_class = 'even'
for r in module.registers:
html_overview += indent(5) + '<tr><td class="%s"><a class="overview" href="#%s">%s</d></td></tr>\n' % (html_cell_class, r.name, r.name)
# cycle cell colors:
if html_cell_class == 'even': html_cell_class = 'odd'
elif html_cell_class == 'odd': html_cell_class = 'even'
html_overview += indent(4) + '</table>\n'
# HTML detailed description
html_registers = ""
for r in module.registers:
html_registers += self.to_html(r)
d = dict(module_name=module.name,
date_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
hdlregs_version=HDLREGS_VERSION,
registers=html_registers,
overview=html_overview)
self._code = HTML_DOC_TEMPLATE.substitute(d)
def to_html(self, element):
# Register -> HTML
if isinstance(element, Register):
r = element
fields_sorted = sorted(r.fields, key=lambda field: field.bitOffset, reverse=True) # sort fields in order of descending bit offset
fields_html = ""
for f in fields_sorted:
fields_html += self.to_html(f)
str_addressOffset = "0x%.8X" % r.addressOffset
d = dict(register_name=r.name,
register_description=r.description,
register_addr_offset=str_addressOffset,
register_fields=fields_html)
return HTML_REGISTER_TEMPLATE.substitute(d)
# Field -> HTML
elif isinstance(element, Field):
if element.bitWidth == 1:
field_range = element.bitOffset
else:
field_range = "%d:%d" % (element.bitOffset + element.bitWidth - 1, element.bitOffset)
#
access = element.access()
if access == "read-write":
field_access = "RW"
elif access == "read-only":
field_access = "R"
elif access == "write-only":
field_access = "W"
#
if element.selfClear:
field_selfClear = "Self-clearing"
else:
field_selfClear = " "
#
d = dict(field_range=field_range,
field_name=element.name,
field_access=field_access,
field_reset=element.reset(),
field_description=element.description,
field_selfClear=field_selfClear)
return HTML_REGISTER_FIELD_TEMPLATE.substitute(d)
def save(self, filename):
with open(filename, 'w') as f:
f.write(self._code)
# ------------------------------------------------------------------------------
# Register file elements: Module, Register and Field classes
#
# A module definition
class Module():
SUPPORTED_WIDTHS = (32,) # supported bus widths
MANDATORY_ELEMENTS = ("name", "description", "width", "registers")
#
# Module constructor
def __init__(self, json_module):
# default values:
self.name = ""
for key in json_module.keys():
if key == "name":
self.name = json_module[key]
elif key == "description":
self.description = json_module[key]
elif key == "interface":
self.interface = json_module[key]
elif key == "width":
self.width = int(json_module[key])
elif key == "registers":
self.registers = [Register(json_reg, parent_module=self) for json_reg in json_module[key]]
# check for missing mandatory elements
for e in self.MANDATORY_ELEMENTS:
if not hasattr(self, e):
if(e == 'name'): self.name = '<unnamed>'
raise ModuleError(self, "missing '%s' element" % e)
# check for unsupported elements
for key in json_module.keys():
if key not in self.MANDATORY_ELEMENTS:
raise ModuleError(self, "unsupported element '%s'" % key)
# check for unsupported width
if self.width not in self.SUPPORTED_WIDTHS:
str_supported_widths = ["'%s'" % str(w) for w in SUPPORTED_WIDTHS]
str_supported_widths = ", ".join(str_supported_widths)
raise ModuleError(self, "unsupported width '%d' -- HDLRegs currently supports only the following register widths: %s" % (self.width, str_supported_widths))
# elaborate & check
self.elaborate()
self.check() #
# Check a module
def check(self):
pass
#
# Elaborate a module, i.e. compute values for all undefined parameters such
# as register addresses, bit field offsets etc.
def elaborate(self):
# Register address sanity checks:
addr_dict = {}
for reg in self.registers:
addr = reg.addressOffset
if addr == None:
continue
if addr_dict.has_key(addr):
addr_dict[addr].append(reg)
else:
addr_dict[addr] = [reg]
for key in addr_dict.keys():
# check that no two registers have the same address offset:
if len(addr_dict[key]) > 1:
conflicting_regs = [r.name for r in addr_dict[key]]
conflicting_regs = ", ".join(conflicting_regs)
raise(ModuleError(self, "registers [%s] have the same addressOffset" % conflicting_regs))
#
# Allocate register addresses
for r1 in self.registers:
if r1.addressOffset == None:
# Register has not been assigned an address offset -> compute the
# next available one
candidate_addressOffset = 0x0
while(True):
success = True
for r2 in self.registers:
if r2.addressOffset == candidate_addressOffset:
candidate_addressOffset += 4
success = False
break
if success:
break
# print "elaboration: allocated address 0x%.8X for register %s" % (candidate_addressOffset, r1.name)
r1.addressOffset = candidate_addressOffset
r1.elaborate()
#
# Returns the module's register with the lowest address
def base_register(self):
base_addr_reg = self.registers[0]
for r in self.registers[1:]:
if r.addressOffset < base_addr_reg.addressOffset:
base_addr_reg = r
return base_addr_reg
#
# Returns the module's register with the highest address
def high_register(self):
base_addr_reg = self.registers[0]
for r in self.registers[1:]:
if r.addressOffset > base_addr_reg.addressOffset:
base_addr_reg = r
return base_addr_reg
# A register definition
class Register:
MANDATORY_ELEMENTS = ("name", "description")
OPTIONAL_ELEMENTS = ("access", "addressOffset", "reset", "fields")
ACCESS = ("read-write", "read-only", "write-only") # supported access-types
#
# Register constructor
def __init__(self, json_reg, parent_module):
#
# default values:
self.parent_module_ = parent_module
self.name = ""
self.description = None
self.access = "read-write"
self.addressOffset = None
self._reset = 0
self.fields = []
#
# initialize fields from JSON
for key in json_reg.keys():
if key == "name":
self.name = json_reg[key]
elif key == "description":
self.description = json_reg[key]
elif key == "access":
self.access = json_reg[key]
elif key == "addressOffset":
self.addressOffset = int_from_json(json_reg[key])
elif key == "reset":
self._reset = int_from_json(json_reg[key])
elif key == "fields":
self.fields = [Field(json_field, self) for json_field in json_reg[key]]
#
# check for missing mandatory elements
for e in self.MANDATORY_ELEMENTS:
if not hasattr(self, e):
if(e == 'name'): self.name = '<unnamed>'
raise RegisterError(self, "missing '%s' element" % e)
#
# check for unsupported elements
for key in json_reg.keys():
if key not in self.MANDATORY_ELEMENTS + self.OPTIONAL_ELEMENTS:
raise RegisterError(self, "unsupported element '%s'" % key)
#
# elaborate & check
self.elaborate()
self.check()
#
# Returns only the register's bus-writable fields
def bus_writable_fields(self):
result = []
for f in self.fields:
if f.access() == "write-only" or f.access() == "read-write":
result += f
return f
#
# Returns True if the register is bus-writable, i.e. if it has at least one bus-writable field
def is_bus_writable(self):
for f in self.fields:
if f.access() == "write-only" or f.access() == "read-write":
return True
return False
#
# Returns True if the register is bus-readable, i.e. if it has at least one bus-readable field