3 from collections
import defaultdict
, OrderedDict
4 from contextlib
import contextmanager
6 from ..tools
import bits_for
, flatten
7 from ..hdl
import ast
, rec
, ir
, mem
, xfrm
19 def _make_name(self
, name
, local
):
22 name
= "${}".format(self
._index
)
23 elif not local
and name
[0] not in "\\$":
24 name
= "\\{}".format(name
)
25 while name
in self
._names
:
27 name
= "{}${}".format(name
, self
._index
)
32 class _BufferedBuilder
:
35 self
._buffer
= io
.StringIO()
38 return self
._buffer
.getvalue()
40 def _append(self
, fmt
, *args
, **kwargs
):
41 self
._buffer
.write(fmt
.format(*args
, **kwargs
))
44 class _ProxiedBuilder
:
45 def _append(self
, *args
, **kwargs
):
46 self
.rtlil
._append
(*args
, **kwargs
)
50 _escape_map
= str.maketrans({
58 def _attribute(self
, name
, value
, *, indent
=0):
59 if isinstance(value
, str):
60 self
._append
("{}attribute \\{} \"{}\"\n",
61 " " * indent
, name
, value
.translate(self
._escape
_map
))
63 self
._append
("{}attribute \\{} {}\n",
64 " " * indent
, name
, int(value
))
66 def _attributes(self
, attrs
, *, src
=None, **kwargs
):
67 for name
, value
in attrs
.items():
68 self
._attribute
(name
, value
, **kwargs
)
70 self
._attribute
("src", src
, **kwargs
)
73 class _Builder(_Namer
, _BufferedBuilder
):
74 def module(self
, name
=None, attrs
={}):
75 name
= self
._make
_name
(name
, local
=False)
76 return _ModuleBuilder(self
, name
, attrs
)
79 class _ModuleBuilder(_Namer
, _BufferedBuilder
, _AttrBuilder
):
80 def __init__(self
, rtlil
, name
, attrs
):
84 self
.attrs
= {"generator": "nMigen"}
85 self
.attrs
.update(attrs
)
88 self
._attributes
(self
.attrs
)
89 self
._append
("module {}\n", self
.name
)
92 def __exit__(self
, *args
):
94 self
.rtlil
._buffer
.write(str(self
))
96 def wire(self
, width
, port_id
=None, port_kind
=None, name
=None, attrs
={}, src
=""):
97 self
._attributes
(attrs
, src
=src
, indent
=1)
98 name
= self
._make
_name
(name
, local
=False)
100 self
._append
(" wire width {} {}\n", width
, name
)
102 assert port_kind
in ("input", "output", "inout")
103 self
._append
(" wire width {} {} {} {}\n", width
, port_kind
, port_id
, name
)
106 def connect(self
, lhs
, rhs
):
107 self
._append
(" connect {} {}\n", lhs
, rhs
)
109 def memory(self
, width
, size
, name
=None, attrs
={}, src
=""):
110 self
._attributes
(attrs
, src
=src
, indent
=1)
111 name
= self
._make
_name
(name
, local
=False)
112 self
._append
(" memory width {} size {} {}\n", width
, size
, name
)
115 def cell(self
, kind
, name
=None, params
={}, ports
={}, attrs
={}, src
=""):
116 self
._attributes
(attrs
, src
=src
, indent
=1)
117 name
= self
._make
_name
(name
, local
=False)
118 self
._append
(" cell {} {}\n", kind
, name
)
119 for param
, value
in params
.items():
120 if isinstance(value
, str):
121 self
._append
(" parameter \\{} \"{}\"\n",
122 param
, value
.translate(self
._escape
_map
))
123 elif isinstance(value
, int):
124 self
._append
(" parameter \\{} {:d}\n",
126 elif isinstance(value
, ast
.Const
):
127 self
._append
(" parameter \\{} {}'{:b}\n",
128 param
, len(value
), value
.value
)
130 assert False, "Bad parameter {!r}".format(value
)
131 for port
, wire
in ports
.items():
132 self
._append
(" connect {} {}\n", port
, wire
)
133 self
._append
(" end\n")
136 def process(self
, name
=None, attrs
={}, src
=""):
137 name
= self
._make
_name
(name
, local
=True)
138 return _ProcessBuilder(self
, name
, attrs
, src
)
141 class _ProcessBuilder(_BufferedBuilder
, _AttrBuilder
):
142 def __init__(self
, rtlil
, name
, attrs
, src
):
150 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=1)
151 self
._append
(" process {}\n", self
.name
)
154 def __exit__(self
, *args
):
155 self
._append
(" end\n")
156 self
.rtlil
._buffer
.write(str(self
))
159 return _CaseBuilder(self
, indent
=2)
161 def sync(self
, kind
, cond
=None):
162 return _SyncBuilder(self
, kind
, cond
)
165 class _CaseBuilder(_ProxiedBuilder
):
166 def __init__(self
, rtlil
, indent
):
173 def __exit__(self
, *args
):
176 def assign(self
, lhs
, rhs
):
177 self
._append
("{}assign {} {}\n", " " * self
.indent
, lhs
, rhs
)
179 def switch(self
, cond
, attrs
={}, src
=""):
180 return _SwitchBuilder(self
.rtlil
, cond
, attrs
, src
, self
.indent
)
183 class _SwitchBuilder(_ProxiedBuilder
, _AttrBuilder
):
184 def __init__(self
, rtlil
, cond
, attrs
, src
, indent
):
192 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=self
.indent
)
193 self
._append
("{}switch {}\n", " " * self
.indent
, self
.cond
)
196 def __exit__(self
, *args
):
197 self
._append
("{}end\n", " " * self
.indent
)
199 def case(self
, *values
, attrs
={}, src
=""):
200 self
._attributes
(attrs
, src
=src
, indent
=self
.indent
+ 1)
202 self
._append
("{}case\n", " " * (self
.indent
+ 1))
204 self
._append
("{}case {}\n", " " * (self
.indent
+ 1),
205 ", ".join("{}'{}".format(len(value
), value
) for value
in values
))
206 return _CaseBuilder(self
.rtlil
, self
.indent
+ 2)
209 class _SyncBuilder(_ProxiedBuilder
):
210 def __init__(self
, rtlil
, kind
, cond
):
216 if self
.cond
is None:
217 self
._append
(" sync {}\n", self
.kind
)
219 self
._append
(" sync {} {}\n", self
.kind
, self
.cond
)
222 def __exit__(self
, *args
):
225 def update(self
, lhs
, rhs
):
226 self
._append
(" update {} {}\n", lhs
, rhs
)
233 return "{}:{}".format(file, line
)
237 return "|".join(sorted(filter(lambda x
: x
, map(src
, src_locs
))))
240 class LegalizeValue(Exception):
241 def __init__(self
, value
, branches
, src_loc
):
243 self
.branches
= list(branches
)
244 self
.src_loc
= src_loc
247 class _ValueCompilerState
:
248 def __init__(self
, rtlil
):
250 self
.wires
= ast
.SignalDict()
251 self
.driven
= ast
.SignalDict()
252 self
.ports
= ast
.SignalDict()
253 self
.anys
= ast
.ValueDict()
255 self
.expansions
= ast
.ValueDict()
257 def add_driven(self
, signal
, sync
):
258 self
.driven
[signal
] = sync
260 def add_port(self
, signal
, kind
):
261 assert kind
in ("i", "o", "io")
268 self
.ports
[signal
] = (len(self
.ports
), kind
)
270 def resolve(self
, signal
, prefix
=None):
271 if signal
in self
.wires
:
272 return self
.wires
[signal
]
274 if signal
in self
.ports
:
275 port_id
, port_kind
= self
.ports
[signal
]
277 port_id
= port_kind
= None
278 if prefix
is not None:
279 wire_name
= "{}_{}".format(prefix
, signal
.name
)
281 wire_name
= signal
.name
283 wire_curr
= self
.rtlil
.wire(width
=signal
.nbits
, name
=wire_name
,
284 port_id
=port_id
, port_kind
=port_kind
,
286 src
=src(signal
.src_loc
))
287 if signal
in self
.driven
and self
.driven
[signal
]:
288 wire_next
= self
.rtlil
.wire(width
=signal
.nbits
, name
=wire_curr
+ "$next",
289 src
=src(signal
.src_loc
))
292 self
.wires
[signal
] = (wire_curr
, wire_next
)
294 return wire_curr
, wire_next
296 def resolve_curr(self
, signal
, prefix
=None):
297 wire_curr
, wire_next
= self
.resolve(signal
, prefix
)
300 def expand(self
, value
):
301 if not self
.expansions
:
303 return self
.expansions
.get(value
, value
)
306 def expand_to(self
, value
, expansion
):
308 assert value
not in self
.expansions
309 self
.expansions
[value
] = expansion
312 del self
.expansions
[value
]
315 class _ValueCompiler(xfrm
.ValueVisitor
):
316 def __init__(self
, state
):
319 def on_unknown(self
, value
):
323 super().on_unknown(value
)
325 def on_ClockSignal(self
, value
):
326 raise NotImplementedError # :nocov:
328 def on_ResetSignal(self
, value
):
329 raise NotImplementedError # :nocov:
331 def on_Sample(self
, value
):
332 raise NotImplementedError # :nocov:
334 def on_Record(self
, value
):
335 return self(ast
.Cat(value
.fields
.values()))
337 def on_Cat(self
, value
):
338 return "{{ {} }}".format(" ".join(reversed([self(o
) for o
in value
.parts
])))
340 def _prepare_value_for_Slice(self
, value
):
341 raise NotImplementedError # :nocov:
343 def on_Slice(self
, value
):
344 if value
.start
== 0 and value
.end
== len(value
.value
):
345 return self(value
.value
)
347 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
)
348 if value
.start
== value
.end
:
350 elif value
.start
+ 1 == value
.end
:
351 return "{} [{}]".format(sigspec
, value
.start
)
353 return "{} [{}:{}]".format(sigspec
, value
.end
- 1, value
.start
)
355 def on_ArrayProxy(self
, value
):
356 index
= self
.s
.expand(value
.index
)
357 if isinstance(index
, ast
.Const
):
358 if index
.value
< len(value
.elems
):
359 elem
= value
.elems
[index
.value
]
361 elem
= value
.elems
[-1]
362 return self
.match_shape(elem
, *value
.shape())
364 raise LegalizeValue(value
.index
, range(len(value
.elems
)), value
.src_loc
)
367 class _RHSValueCompiler(_ValueCompiler
):
371 (1, "b"): "$reduce_bool",
392 def on_value(self
, value
):
393 return super().on_value(self
.s
.expand(value
))
395 def on_Const(self
, value
):
396 if isinstance(value
.value
, str):
397 return "{}'{}".format(value
.nbits
, value
.value
)
399 value_twos_compl
= value
.value
& ((1 << value
.nbits
) - 1)
400 return "{}'{:0{}b}".format(value
.nbits
, value_twos_compl
, value
.nbits
)
402 def on_AnyConst(self
, value
):
403 if value
in self
.s
.anys
:
404 return self
.s
.anys
[value
]
406 res_bits
, res_sign
= value
.shape()
407 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
408 self
.s
.rtlil
.cell("$anyconst", ports
={
412 }, src
=src(value
.src_loc
))
413 self
.s
.anys
[value
] = res
416 def on_AnySeq(self
, value
):
417 if value
in self
.s
.anys
:
418 return self
.s
.anys
[value
]
420 res_bits
, res_sign
= value
.shape()
421 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
422 self
.s
.rtlil
.cell("$anyseq", ports
={
426 }, src
=src(value
.src_loc
))
427 self
.s
.anys
[value
] = res
430 def on_Signal(self
, value
):
431 wire_curr
, wire_next
= self
.s
.resolve(value
)
434 def on_Operator_unary(self
, value
):
435 arg
, = value
.operands
436 arg_bits
, arg_sign
= arg
.shape()
437 res_bits
, res_sign
= value
.shape()
438 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
439 self
.s
.rtlil
.cell(self
.operator_map
[(1, value
.op
)], ports
={
443 "A_SIGNED": arg_sign
,
446 }, src
=src(value
.src_loc
))
449 def match_shape(self
, value
, new_bits
, new_sign
):
450 if isinstance(value
, ast
.Const
):
451 return self(ast
.Const(value
.value
, (new_bits
, new_sign
)))
453 value_bits
, value_sign
= value
.shape()
454 if new_bits
<= value_bits
:
455 return self(ast
.Slice(value
, 0, new_bits
))
457 res
= self
.s
.rtlil
.wire(width
=new_bits
, src
=src(value
.src_loc
))
458 self
.s
.rtlil
.cell("$pos", ports
={
462 "A_SIGNED": value_sign
,
463 "A_WIDTH": value_bits
,
465 }, src
=src(value
.src_loc
))
468 def on_Operator_binary(self
, value
):
469 lhs
, rhs
= value
.operands
470 lhs_bits
, lhs_sign
= lhs
.shape()
471 rhs_bits
, rhs_sign
= rhs
.shape()
472 if lhs_sign
== rhs_sign
:
476 lhs_sign
= rhs_sign
= True
477 lhs_bits
= rhs_bits
= max(lhs_bits
, rhs_bits
)
478 lhs_wire
= self
.match_shape(lhs
, lhs_bits
, lhs_sign
)
479 rhs_wire
= self
.match_shape(rhs
, rhs_bits
, rhs_sign
)
480 res_bits
, res_sign
= value
.shape()
481 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
482 self
.s
.rtlil
.cell(self
.operator_map
[(2, value
.op
)], ports
={
487 "A_SIGNED": lhs_sign
,
489 "B_SIGNED": rhs_sign
,
492 }, src
=src(value
.src_loc
))
495 def on_Operator_mux(self
, value
):
496 sel
, val1
, val0
= value
.operands
497 val1_bits
, val1_sign
= val1
.shape()
498 val0_bits
, val0_sign
= val0
.shape()
499 res_bits
, res_sign
= value
.shape()
500 val1_bits
= val0_bits
= res_bits
= max(val1_bits
, val0_bits
, res_bits
)
501 val1_wire
= self
.match_shape(val1
, val1_bits
, val1_sign
)
502 val0_wire
= self
.match_shape(val0
, val0_bits
, val0_sign
)
503 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
504 self
.s
.rtlil
.cell("$mux", ports
={
511 }, src
=src(value
.src_loc
))
514 def on_Operator(self
, value
):
515 if len(value
.operands
) == 1:
516 return self
.on_Operator_unary(value
)
517 elif len(value
.operands
) == 2:
518 return self
.on_Operator_binary(value
)
519 elif len(value
.operands
) == 3:
520 assert value
.op
== "m"
521 return self
.on_Operator_mux(value
)
523 raise TypeError # :nocov:
525 def _prepare_value_for_Slice(self
, value
):
526 if isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
)):
527 sigspec
= self(value
)
529 sigspec
= self
.s
.rtlil
.wire(len(value
), src
=src(value
.src_loc
))
530 self
.s
.rtlil
.connect(sigspec
, self(value
))
533 def on_Part(self
, value
):
534 lhs
, rhs
= value
.value
, value
.offset
535 if value
.stride
!= 1:
537 lhs_bits
, lhs_sign
= lhs
.shape()
538 rhs_bits
, rhs_sign
= rhs
.shape()
539 res_bits
, res_sign
= value
.shape()
540 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
541 # Note: Verilog's x[o+:w] construct produces a $shiftx cell, not a $shift cell.
542 # However, Migen's semantics defines the out-of-range bits to be zero, so it is correct
543 # to use a $shift cell here instead, even though it produces less idiomatic Verilog.
544 self
.s
.rtlil
.cell("$shift", ports
={
549 "A_SIGNED": lhs_sign
,
551 "B_SIGNED": rhs_sign
,
554 }, src
=src(value
.src_loc
))
557 def on_Repl(self
, value
):
558 return "{{ {} }}".format(" ".join(self(value
.value
) for _
in range(value
.count
)))
561 class _LHSValueCompiler(_ValueCompiler
):
562 def on_Const(self
, value
):
563 raise TypeError # :nocov:
565 def on_AnyConst(self
, value
):
566 raise TypeError # :nocov:
568 def on_AnySeq(self
, value
):
569 raise TypeError # :nocov:
571 def on_Operator(self
, value
):
572 raise TypeError # :nocov:
574 def match_shape(self
, value
, new_bits
, new_sign
):
575 assert value
.shape() == (new_bits
, new_sign
)
578 def on_Signal(self
, value
):
579 if value
not in self
.s
.driven
:
580 raise ValueError("No LHS wire for non-driven signal {}".format(repr(value
)))
581 wire_curr
, wire_next
= self
.s
.resolve(value
)
582 return wire_next
or wire_curr
584 def _prepare_value_for_Slice(self
, value
):
585 assert isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
, rec
.Record
))
588 def on_Part(self
, value
):
589 offset
= self
.s
.expand(value
.offset
)
590 if isinstance(offset
, ast
.Const
):
591 return self(ast
.Slice(value
.value
, offset
.value
, offset
.value
+ value
.width
))
593 raise LegalizeValue(value
.offset
, range((1 << len(value
.offset
))), value
.src_loc
)
595 def on_Repl(self
, value
):
596 raise TypeError # :nocov:
599 class _StatementCompiler(xfrm
.StatementVisitor
):
600 def __init__(self
, state
, rhs_compiler
, lhs_compiler
):
602 self
.rhs_compiler
= rhs_compiler
603 self
.lhs_compiler
= lhs_compiler
606 self
._test
_cache
= {}
607 self
._has
_rhs
= False
610 def case(self
, switch
, values
, attrs
={}, src
=""):
612 old_case
= self
._case
613 with switch
.case(*values
, attrs
=attrs
, src
=src
) as self
._case
:
616 self
._case
= old_case
618 def _check_rhs(self
, value
):
619 if self
._has
_rhs
or next(iter(value
._rhs
_signals
()), None) is not None:
622 def on_Assign(self
, stmt
):
623 self
._check
_rhs
(stmt
.rhs
)
625 lhs_bits
, lhs_sign
= stmt
.lhs
.shape()
626 rhs_bits
, rhs_sign
= stmt
.rhs
.shape()
627 if lhs_bits
== rhs_bits
:
628 rhs_sigspec
= self
.rhs_compiler(stmt
.rhs
)
630 # In RTLIL, LHS and RHS of assignment must have exactly same width.
631 rhs_sigspec
= self
.rhs_compiler
.match_shape(
632 stmt
.rhs
, lhs_bits
, lhs_sign
)
633 self
._case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
635 def on_Assert(self
, stmt
):
636 self(stmt
._check
.eq(stmt
.test
))
639 en_wire
= self
.rhs_compiler(stmt
._en
)
640 check_wire
= self
.rhs_compiler(stmt
._check
)
641 self
.state
.rtlil
.cell("$assert", ports
={
644 }, src
=src(stmt
.src_loc
))
646 def on_Assume(self
, stmt
):
647 self(stmt
._check
.eq(stmt
.test
))
650 en_wire
= self
.rhs_compiler(stmt
._en
)
651 check_wire
= self
.rhs_compiler(stmt
._check
)
652 self
.state
.rtlil
.cell("$assume", ports
={
655 }, src
=src(stmt
.src_loc
))
657 def on_Switch(self
, stmt
):
658 self
._check
_rhs
(stmt
.test
)
660 if stmt
not in self
._test
_cache
:
661 self
._test
_cache
[stmt
] = self
.rhs_compiler(stmt
.test
)
662 test_sigspec
= self
._test
_cache
[stmt
]
664 with self
._case
.switch(test_sigspec
, src
=src(stmt
.src_loc
)) as switch
:
665 for values
, stmts
in stmt
.cases
.items():
667 if values
in stmt
.case_src_locs
:
668 case_attrs
["src"] = src(stmt
.case_src_locs
[values
])
669 if isinstance(stmt
.test
, ast
.Signal
) and stmt
.test
.decoder
:
673 decoded_values
.append("<multiple>")
675 decoded_values
.append(stmt
.test
.decoder(int(value
, 2)))
676 case_attrs
["nmigen.decoding"] = "|".join(decoded_values
)
677 with self
.case(switch
, values
, attrs
=case_attrs
):
678 self
.on_statements(stmts
)
680 def on_statement(self
, stmt
):
682 super().on_statement(stmt
)
683 except LegalizeValue
as legalize
:
684 with self
._case
.switch(self
.rhs_compiler(legalize
.value
),
685 src
=src(legalize
.src_loc
)) as switch
:
686 bits
, sign
= legalize
.value
.shape()
687 tests
= ["{:0{}b}".format(v
, bits
) for v
in legalize
.branches
]
688 tests
[-1] = "-" * bits
689 for branch
, test
in zip(legalize
.branches
, tests
):
690 with self
.case(switch
, (test
,)):
691 branch_value
= ast
.Const(branch
, (bits
, sign
))
692 with self
.state
.expand_to(legalize
.value
, branch_value
):
693 super().on_statement(stmt
)
695 def on_statements(self
, stmts
):
697 self
.on_statement(stmt
)
700 def convert_fragment(builder
, fragment
, hierarchy
):
701 if isinstance(fragment
, ir
.Instance
):
702 port_map
= OrderedDict()
703 for port_name
, (value
, dir) in fragment
.named_ports
.items():
704 port_map
["\\{}".format(port_name
)] = value
706 if fragment
.type[0] == "$":
707 return fragment
.type, port_map
709 return "\\{}".format(fragment
.type), port_map
711 module_name
= hierarchy
[-1] or "anonymous"
712 module_attrs
= OrderedDict()
713 if len(hierarchy
) == 1:
714 module_attrs
["top"] = 1
715 module_attrs
["nmigen.hierarchy"] = ".".join(name
or "anonymous" for name
in hierarchy
)
717 with builder
.module(module_name
, attrs
=module_attrs
) as module
:
718 compiler_state
= _ValueCompilerState(module
)
719 rhs_compiler
= _RHSValueCompiler(compiler_state
)
720 lhs_compiler
= _LHSValueCompiler(compiler_state
)
721 stmt_compiler
= _StatementCompiler(compiler_state
, rhs_compiler
, lhs_compiler
)
723 verilog_trigger
= None
724 verilog_trigger_sync_emitted
= False
726 # Register all signals driven in the current fragment. This must be done first, as it
727 # affects further codegen; e.g. whether \sig$next signals will be generated and used.
728 for domain
, signal
in fragment
.iter_drivers():
729 compiler_state
.add_driven(signal
, sync
=domain
is not None)
731 # Transform all signals used as ports in the current fragment eagerly and outside of
732 # any hierarchy, to make sure they get sensible (non-prefixed) names.
733 for signal
in fragment
.ports
:
734 compiler_state
.add_port(signal
, fragment
.ports
[signal
])
735 compiler_state
.resolve_curr(signal
)
737 # Transform all clocks clocks and resets eagerly and outside of any hierarchy, to make
738 # sure they get sensible (non-prefixed) names. This does not affect semantics.
739 for domain
, _
in fragment
.iter_sync():
740 cd
= fragment
.domains
[domain
]
741 compiler_state
.resolve_curr(cd
.clk
)
742 if cd
.rst
is not None:
743 compiler_state
.resolve_curr(cd
.rst
)
745 # Transform all subfragments to their respective cells. Transforming signals connected
746 # to their ports into wires eagerly makes sure they get sensible (prefixed with submodule
748 memories
= OrderedDict()
749 for subfragment
, sub_name
in fragment
.subfragments
:
750 if not subfragment
.ports
:
753 sub_params
= OrderedDict()
754 if hasattr(subfragment
, "parameters"):
755 for param_name
, param_value
in subfragment
.parameters
.items():
756 if isinstance(param_value
, mem
.Memory
):
758 if memory
not in memories
:
759 memories
[memory
] = module
.memory(width
=memory
.width
, size
=memory
.depth
,
761 addr_bits
= bits_for(memory
.depth
)
763 data_mask
= (1 << memory
.width
) - 1
764 for addr
in range(memory
.depth
):
765 if addr
< len(memory
.init
):
766 data
= memory
.init
[addr
] & data_mask
769 data_parts
.append("{:0{}b}".format(data
, memory
.width
))
770 module
.cell("$meminit", ports
={
771 "\\ADDR": rhs_compiler(ast
.Const(0, addr_bits
)),
772 "\\DATA": "{}'".format(memory
.width
* memory
.depth
) +
773 "".join(reversed(data_parts
)),
775 "MEMID": memories
[memory
],
777 "WIDTH": memory
.width
,
778 "WORDS": memory
.depth
,
782 param_value
= memories
[memory
]
784 sub_params
[param_name
] = param_value
786 sub_type
, sub_port_map
= \
787 convert_fragment(builder
, subfragment
, hierarchy
=hierarchy
+ (sub_name
,))
789 sub_ports
= OrderedDict()
790 for port
, value
in sub_port_map
.items():
791 if not isinstance(subfragment
, ir
.Instance
):
792 for signal
in value
._rhs
_signals
():
793 compiler_state
.resolve_curr(signal
, prefix
=sub_name
)
794 sub_ports
[port
] = rhs_compiler(value
)
796 module
.cell(sub_type
, name
=sub_name
, ports
=sub_ports
, params
=sub_params
,
797 attrs
=subfragment
.attrs
)
799 # If we emit all of our combinatorial logic into a single RTLIL process, Verilog
800 # simulators will break horribly, because Yosys write_verilog transforms RTLIL processes
801 # into always @* blocks with blocking assignment, and that does not create delta cycles.
803 # Therefore, we translate the fragment as many times as there are independent groups
804 # of signals (a group is a transitive closure of signals that appear together on LHS),
805 # splitting them into many RTLIL (and thus Verilog) processes.
806 lhs_grouper
= xfrm
.LHSGroupAnalyzer()
807 lhs_grouper
.on_statements(fragment
.statements
)
809 for group
, group_signals
in lhs_grouper
.groups().items():
810 lhs_group_filter
= xfrm
.LHSGroupFilter(group_signals
)
811 group_stmts
= lhs_group_filter(fragment
.statements
)
813 with module
.process(name
="$group_{}".format(group
)) as process
:
814 with process
.case() as case
:
815 # For every signal in comb domain, assign \sig$next to the reset value.
816 # For every signal in sync domains, assign \sig$next to the current
818 for domain
, signal
in fragment
.iter_drivers():
819 if signal
not in group_signals
:
822 prev_value
= ast
.Const(signal
.reset
, signal
.nbits
)
825 case
.assign(lhs_compiler(signal
), rhs_compiler(prev_value
))
827 # Convert statements into decision trees.
828 stmt_compiler
._case
= case
829 stmt_compiler
._has
_rhs
= False
830 stmt_compiler(group_stmts
)
832 # Verilog `always @*` blocks will not run if `*` does not match anything, i.e.
833 # if the implicit sensitivity list is empty. We check this while translating,
834 # by looking for any signals on RHS. If there aren't any, we add some logic
835 # whose only purpose is to trigger Verilog simulators when it converts
836 # through RTLIL and to Verilog, by populating the sensitivity list.
837 if not stmt_compiler
._has
_rhs
:
838 if verilog_trigger
is None:
840 module
.wire(1, name
="$verilog_initial_trigger")
841 case
.assign(verilog_trigger
, verilog_trigger
)
843 # For every signal in the sync domain, assign \sig's initial value (which will
844 # end up as the \init reg attribute) to the reset value.
845 with process
.sync("init") as sync
:
846 for domain
, signal
in fragment
.iter_sync():
847 if signal
not in group_signals
:
849 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
850 sync
.update(wire_curr
, rhs_compiler(ast
.Const(signal
.reset
, signal
.nbits
)))
852 # The Verilog simulator trigger needs to change at time 0, so if we haven't
853 # yet done that in some process, do it.
854 if verilog_trigger
and not verilog_trigger_sync_emitted
:
855 sync
.update(verilog_trigger
, "1'0")
856 verilog_trigger_sync_emitted
= True
858 # For every signal in every sync domain, assign \sig to \sig$next. The sensitivity
859 # list, however, differs between domains: for domains with sync reset, it is
860 # `posedge clk`, for sync domains with async reset it is `posedge clk or
862 for domain
, signals
in fragment
.drivers
.items():
866 signals
= signals
& group_signals
870 cd
= fragment
.domains
[domain
]
873 triggers
.append(("posedge", compiler_state
.resolve_curr(cd
.clk
)))
875 triggers
.append(("posedge", compiler_state
.resolve_curr(cd
.rst
)))
877 for trigger
in triggers
:
878 with process
.sync(*trigger
) as sync
:
879 for signal
in signals
:
880 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
881 sync
.update(wire_curr
, wire_next
)
883 # Any signals that are used but neither driven nor connected to an input port always
884 # assume their reset values. We need to assign the reset value explicitly, since only
885 # driven sync signals are handled by the logic above.
887 # Because this assignment is done at a late stage, a single Signal object can get assigned
888 # many times, once in each module it is used. This is a deliberate decision; the possible
889 # alternatives are to add ports for undriven signals (which requires choosing one module
890 # to drive it to reset value arbitrarily) or to replace them with their reset value (which
891 # removes valuable source location information).
892 driven
= ast
.SignalSet()
893 for domain
, signals
in fragment
.iter_drivers():
894 driven
.update(flatten(signal
._lhs
_signals
() for signal
in signals
))
895 driven
.update(fragment
.iter_ports(dir="i"))
896 driven
.update(fragment
.iter_ports(dir="io"))
897 for subfragment
, sub_name
in fragment
.subfragments
:
898 driven
.update(subfragment
.iter_ports(dir="o"))
899 driven
.update(subfragment
.iter_ports(dir="io"))
901 for wire
in compiler_state
.wires
:
904 wire_curr
, _
= compiler_state
.wires
[wire
]
905 module
.connect(wire_curr
, rhs_compiler(ast
.Const(wire
.reset
, wire
.nbits
)))
907 # Finally, collect the names we've given to our ports in RTLIL, and correlate these with
908 # the signals represented by these ports. If we are a submodule, this will be necessary
909 # to create a cell for us in the parent module.
910 port_map
= OrderedDict()
911 for signal
in fragment
.ports
:
912 port_map
[compiler_state
.resolve_curr(signal
)] = signal
914 return module
.name
, port_map
917 def convert(fragment
, name
="top", platform
=None, **kwargs
):
918 fragment
= ir
.Fragment
.get(fragment
, platform
).prepare(**kwargs
)
920 convert_fragment(builder
, fragment
, hierarchy
=(name
,))