2 from collections
import OrderedDict
3 from contextlib
import contextmanager
5 from .._utils
import bits_for
, flatten
6 from ..hdl
import ast
, ir
, mem
, xfrm
9 __all__
= ["convert", "convert_fragment"]
12 class ImplementationLimit(Exception):
16 _escape_map
= str.maketrans({
26 if isinstance(value
, str):
28 elif isinstance(value
, int):
30 elif isinstance(value
, ast
.Const
):
33 assert False, "Invalid constant {!r}".format(value
)
37 if isinstance(value
, str):
38 return "\"{}\"".format(value
.translate(_escape_map
))
39 elif isinstance(value
, int):
40 if value
in range(0, 2**31-1):
41 return "{:d}".format(value
)
43 # This code path is only used for Instances, where Verilog-like behavior is desirable.
44 # Verilog ensures that integers with unspecified width are 32 bits wide or more.
45 width
= max(32, bits_for(value
))
46 return _const(ast
.Const(value
, width
))
47 elif isinstance(value
, ast
.Const
):
48 value_twos_compl
= value
.value
& ((1 << value
.width
) - 1)
49 return "{}'{:0{}b}".format(value
.width
, value_twos_compl
, value
.width
)
51 assert False, "Invalid constant {!r}".format(value
)
62 name
= "U$${}".format(self
._anon
)
63 assert name
not in self
._names
67 def _make_name(self
, name
, local
):
70 name
= "${}".format(self
._index
)
71 elif not local
and name
[0] not in "\\$":
72 name
= "\\{}".format(name
)
73 while name
in self
._names
:
75 name
= "{}${}".format(name
, self
._index
)
80 class _BufferedBuilder
:
83 self
._buffer
= io
.StringIO()
86 return self
._buffer
.getvalue()
88 def _append(self
, fmt
, *args
, **kwargs
):
89 self
._buffer
.write(fmt
.format(*args
, **kwargs
))
92 class _ProxiedBuilder
:
93 def _append(self
, *args
, **kwargs
):
94 self
.rtlil
._append
(*args
, **kwargs
)
98 def _attribute(self
, name
, value
, *, indent
=0):
99 self
._append
("{}attribute \\{} {}\n",
100 " " * indent
, name
, _const(value
))
102 def _attributes(self
, attrs
, *, src
=None, **kwargs
):
103 for name
, value
in attrs
.items():
104 self
._attribute
(name
, value
, **kwargs
)
106 self
._attribute
("src", src
, **kwargs
)
109 class _Builder(_Namer
, _BufferedBuilder
):
110 def module(self
, name
=None, attrs
={}):
111 name
= self
._make
_name
(name
, local
=False)
112 return _ModuleBuilder(self
, name
, attrs
)
115 class _ModuleBuilder(_Namer
, _BufferedBuilder
, _AttrBuilder
):
116 def __init__(self
, rtlil
, name
, attrs
):
120 self
.attrs
= {"generator": "nMigen"}
121 self
.attrs
.update(attrs
)
124 self
._attributes
(self
.attrs
)
125 self
._append
("module {}\n", self
.name
)
128 def __exit__(self
, *args
):
129 self
._append
("end\n")
130 self
.rtlil
._buffer
.write(str(self
))
132 def wire(self
, width
, port_id
=None, port_kind
=None, name
=None, attrs
={}, src
=""):
133 # Very large wires are unlikely to work. Verilog 1364-2005 requires the limit on vectors
134 # to be at least 2**16 bits, and Yosys 0.9 cannot read RTLIL with wires larger than 2**32
135 # bits. In practice, wires larger than 2**16 bits, although accepted, cause performance
136 # problems without an immediately visible cause, so conservatively limit wire size.
138 raise ImplementationLimit("Wire created at {} is {} bits wide, which is unlikely to "
139 "synthesize correctly"
140 .format(src
or "unknown location", width
))
142 self
._attributes
(attrs
, src
=src
, indent
=1)
143 name
= self
._make
_name
(name
, local
=False)
145 self
._append
(" wire width {} {}\n", width
, name
)
147 assert port_kind
in ("input", "output", "inout")
148 self
._append
(" wire width {} {} {} {}\n", width
, port_kind
, port_id
, name
)
151 def connect(self
, lhs
, rhs
):
152 self
._append
(" connect {} {}\n", lhs
, rhs
)
154 def memory(self
, width
, size
, name
=None, attrs
={}, src
=""):
155 self
._attributes
(attrs
, src
=src
, indent
=1)
156 name
= self
._make
_name
(name
, local
=False)
157 self
._append
(" memory width {} size {} {}\n", width
, size
, name
)
160 def cell(self
, kind
, name
=None, params
={}, ports
={}, attrs
={}, src
=""):
161 self
._attributes
(attrs
, src
=src
, indent
=1)
162 name
= self
._make
_name
(name
, local
=False)
163 self
._append
(" cell {} {}\n", kind
, name
)
164 for param
, value
in params
.items():
165 if isinstance(value
, float):
166 self
._append
(" parameter real \\{} \"{!r}\"\n",
169 self
._append
(" parameter signed \\{} {}\n",
170 param
, _const(value
))
172 self
._append
(" parameter \\{} {}\n",
173 param
, _const(value
))
174 for port
, wire
in ports
.items():
175 self
._append
(" connect {} {}\n", port
, wire
)
176 self
._append
(" end\n")
179 def process(self
, name
=None, attrs
={}, src
=""):
180 name
= self
._make
_name
(name
, local
=True)
181 return _ProcessBuilder(self
, name
, attrs
, src
)
184 class _ProcessBuilder(_BufferedBuilder
, _AttrBuilder
):
185 def __init__(self
, rtlil
, name
, attrs
, src
):
193 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=1)
194 self
._append
(" process {}\n", self
.name
)
197 def __exit__(self
, *args
):
198 self
._append
(" end\n")
199 self
.rtlil
._buffer
.write(str(self
))
202 return _CaseBuilder(self
, indent
=2)
204 def sync(self
, kind
, cond
=None):
205 return _SyncBuilder(self
, kind
, cond
)
208 class _CaseBuilder(_ProxiedBuilder
):
209 def __init__(self
, rtlil
, indent
):
216 def __exit__(self
, *args
):
219 def assign(self
, lhs
, rhs
):
220 self
._append
("{}assign {} {}\n", " " * self
.indent
, lhs
, rhs
)
222 def switch(self
, cond
, attrs
={}, src
=""):
223 return _SwitchBuilder(self
.rtlil
, cond
, attrs
, src
, self
.indent
)
226 class _SwitchBuilder(_ProxiedBuilder
, _AttrBuilder
):
227 def __init__(self
, rtlil
, cond
, attrs
, src
, indent
):
235 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=self
.indent
)
236 self
._append
("{}switch {}\n", " " * self
.indent
, self
.cond
)
239 def __exit__(self
, *args
):
240 self
._append
("{}end\n", " " * self
.indent
)
242 def case(self
, *values
, attrs
={}, src
=""):
243 self
._attributes
(attrs
, src
=src
, indent
=self
.indent
+ 1)
245 self
._append
("{}case\n", " " * (self
.indent
+ 1))
247 self
._append
("{}case {}\n", " " * (self
.indent
+ 1),
248 ", ".join("{}'{}".format(len(value
), value
) for value
in values
))
249 return _CaseBuilder(self
.rtlil
, self
.indent
+ 2)
252 class _SyncBuilder(_ProxiedBuilder
):
253 def __init__(self
, rtlil
, kind
, cond
):
259 if self
.cond
is None:
260 self
._append
(" sync {}\n", self
.kind
)
262 self
._append
(" sync {} {}\n", self
.kind
, self
.cond
)
265 def __exit__(self
, *args
):
268 def update(self
, lhs
, rhs
):
269 self
._append
(" update {} {}\n", lhs
, rhs
)
276 return "{}:{}".format(file, line
)
279 class _LegalizeValue(Exception):
280 def __init__(self
, value
, branches
, src_loc
):
282 self
.branches
= list(branches
)
283 self
.src_loc
= src_loc
286 class _ValueCompilerState
:
287 def __init__(self
, rtlil
):
289 self
.wires
= ast
.SignalDict()
290 self
.driven
= ast
.SignalDict()
291 self
.ports
= ast
.SignalDict()
292 self
.anys
= ast
.ValueDict()
294 self
.expansions
= ast
.ValueDict()
296 def add_driven(self
, signal
, sync
):
297 self
.driven
[signal
] = sync
299 def add_port(self
, signal
, kind
):
300 assert kind
in ("i", "o", "io")
307 self
.ports
[signal
] = (len(self
.ports
), kind
)
309 def resolve(self
, signal
, prefix
=None):
313 if signal
in self
.wires
:
314 return self
.wires
[signal
]
316 if signal
in self
.ports
:
317 port_id
, port_kind
= self
.ports
[signal
]
319 port_id
= port_kind
= None
320 if prefix
is not None:
321 wire_name
= "{}_{}".format(prefix
, signal
.name
)
323 wire_name
= signal
.name
325 attrs
= dict(signal
.attrs
)
326 if signal
._enum
_class
is not None:
327 attrs
["enum_base_type"] = signal
._enum
_class
.__name
__
328 for value
in signal
._enum
_class
:
329 attrs
["enum_value_{:0{}b}".format(value
.value
, signal
.width
)] = value
.name
331 wire_curr
= self
.rtlil
.wire(width
=signal
.width
, name
=wire_name
,
332 port_id
=port_id
, port_kind
=port_kind
,
333 attrs
=attrs
, src
=_src(signal
.src_loc
))
334 if signal
in self
.driven
and self
.driven
[signal
]:
335 wire_next
= self
.rtlil
.wire(width
=signal
.width
, name
=wire_curr
+ "$next",
336 src
=_src(signal
.src_loc
))
339 self
.wires
[signal
] = (wire_curr
, wire_next
)
341 return wire_curr
, wire_next
343 def resolve_curr(self
, signal
, prefix
=None):
344 wire_curr
, wire_next
= self
.resolve(signal
, prefix
)
347 def expand(self
, value
):
348 if not self
.expansions
:
350 return self
.expansions
.get(value
, value
)
353 def expand_to(self
, value
, expansion
):
355 assert value
not in self
.expansions
356 self
.expansions
[value
] = expansion
359 del self
.expansions
[value
]
362 class _ValueCompiler(xfrm
.ValueVisitor
):
363 def __init__(self
, state
):
366 def on_unknown(self
, value
):
370 super().on_unknown(value
)
372 def on_ClockSignal(self
, value
):
373 raise NotImplementedError # :nocov:
375 def on_ResetSignal(self
, value
):
376 raise NotImplementedError # :nocov:
378 def on_Sample(self
, value
):
379 raise NotImplementedError # :nocov:
381 def on_Initial(self
, value
):
382 raise NotImplementedError # :nocov:
384 def on_Cat(self
, value
):
385 return "{{ {} }}".format(" ".join(reversed([self(o
) for o
in value
.parts
])))
387 def _prepare_value_for_Slice(self
, value
):
388 raise NotImplementedError # :nocov:
390 def on_Slice(self
, value
):
391 if value
.start
== 0 and value
.stop
== len(value
.value
):
392 return self(value
.value
)
394 if isinstance(value
.value
, ast
.UserValue
):
395 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
._lazy
_lower
())
397 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
)
399 if value
.start
== value
.stop
:
401 elif value
.start
+ 1 == value
.stop
:
402 return "{} [{}]".format(sigspec
, value
.start
)
404 return "{} [{}:{}]".format(sigspec
, value
.stop
- 1, value
.start
)
406 def on_ArrayProxy(self
, value
):
407 index
= self
.s
.expand(value
.index
)
408 if isinstance(index
, ast
.Const
):
409 if index
.value
< len(value
.elems
):
410 elem
= value
.elems
[index
.value
]
412 elem
= value
.elems
[-1]
413 return self
.match_shape(elem
, *value
.shape())
415 max_index
= 1 << len(value
.index
)
416 max_elem
= len(value
.elems
)
417 raise _LegalizeValue(value
.index
, range(min(max_index
, max_elem
)), value
.src_loc
)
420 class _RHSValueCompiler(_ValueCompiler
):
424 (1, "b"): "$reduce_bool",
425 (1, "r|"): "$reduce_or",
426 (1, "r&"): "$reduce_and",
427 (1, "r^"): "$reduce_xor",
448 def on_value(self
, value
):
449 return super().on_value(self
.s
.expand(value
))
451 def on_Const(self
, value
):
454 def on_AnyConst(self
, value
):
455 if value
in self
.s
.anys
:
456 return self
.s
.anys
[value
]
458 res_bits
, res_sign
= value
.shape()
459 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
460 self
.s
.rtlil
.cell("$anyconst", ports
={
464 }, src
=_src(value
.src_loc
))
465 self
.s
.anys
[value
] = res
468 def on_AnySeq(self
, value
):
469 if value
in self
.s
.anys
:
470 return self
.s
.anys
[value
]
472 res_bits
, res_sign
= value
.shape()
473 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
474 self
.s
.rtlil
.cell("$anyseq", ports
={
478 }, src
=_src(value
.src_loc
))
479 self
.s
.anys
[value
] = res
482 def on_Signal(self
, value
):
483 wire_curr
, wire_next
= self
.s
.resolve(value
)
486 def on_Operator_unary(self
, value
):
487 arg
, = value
.operands
488 if value
.operator
in ("u", "s"):
489 # These operators don't change the bit pattern, only its interpretation.
492 arg_bits
, arg_sign
= arg
.shape()
493 res_bits
, res_sign
= value
.shape()
494 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
495 self
.s
.rtlil
.cell(self
.operator_map
[(1, value
.operator
)], ports
={
499 "A_SIGNED": arg_sign
,
502 }, src
=_src(value
.src_loc
))
505 def match_shape(self
, value
, new_bits
, new_sign
):
506 if isinstance(value
, ast
.Const
):
507 return self(ast
.Const(value
.value
, ast
.Shape(new_bits
, new_sign
)))
509 value_bits
, value_sign
= value
.shape()
510 if new_bits
<= value_bits
:
511 return self(ast
.Slice(value
, 0, new_bits
))
513 res
= self
.s
.rtlil
.wire(width
=new_bits
, src
=_src(value
.src_loc
))
514 self
.s
.rtlil
.cell("$pos", ports
={
518 "A_SIGNED": value_sign
,
519 "A_WIDTH": value_bits
,
521 }, src
=_src(value
.src_loc
))
524 def on_Operator_binary(self
, value
):
525 lhs
, rhs
= value
.operands
526 lhs_bits
, lhs_sign
= lhs
.shape()
527 rhs_bits
, rhs_sign
= rhs
.shape()
528 if lhs_sign
== rhs_sign
or value
.operator
in ("<<", ">>", "**"):
532 lhs_sign
= rhs_sign
= True
533 lhs_bits
= rhs_bits
= max(lhs_bits
, rhs_bits
)
534 lhs_wire
= self
.match_shape(lhs
, lhs_bits
, lhs_sign
)
535 rhs_wire
= self
.match_shape(rhs
, rhs_bits
, rhs_sign
)
536 res_bits
, res_sign
= value
.shape()
537 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
538 self
.s
.rtlil
.cell(self
.operator_map
[(2, value
.operator
)], ports
={
543 "A_SIGNED": lhs_sign
,
545 "B_SIGNED": rhs_sign
,
548 }, src
=_src(value
.src_loc
))
549 if value
.operator
in ("//", "%"):
550 # RTLIL leaves division by zero undefined, but we require it to return zero.
552 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
553 self
.s
.rtlil
.cell("$mux", ports
={
555 "\\B": self(ast
.Const(0, ast
.Shape(res_bits
, res_sign
))),
556 "\\S": self(rhs
== 0),
560 }, src
=_src(value
.src_loc
))
563 def on_Operator_mux(self
, value
):
564 sel
, val1
, val0
= value
.operands
565 val1_bits
, val1_sign
= val1
.shape()
566 val0_bits
, val0_sign
= val0
.shape()
567 res_bits
, res_sign
= value
.shape()
568 val1_bits
= val0_bits
= res_bits
= max(val1_bits
, val0_bits
, res_bits
)
569 val1_wire
= self
.match_shape(val1
, val1_bits
, val1_sign
)
570 val0_wire
= self
.match_shape(val0
, val0_bits
, val0_sign
)
571 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
572 self
.s
.rtlil
.cell("$mux", ports
={
579 }, src
=_src(value
.src_loc
))
582 def on_Operator(self
, value
):
583 if len(value
.operands
) == 1:
584 return self
.on_Operator_unary(value
)
585 elif len(value
.operands
) == 2:
586 return self
.on_Operator_binary(value
)
587 elif len(value
.operands
) == 3:
588 assert value
.operator
== "m"
589 return self
.on_Operator_mux(value
)
591 raise TypeError # :nocov:
593 def _prepare_value_for_Slice(self
, value
):
594 if isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
._InternalCat
)):
595 sigspec
= self(value
)
597 sigspec
= self
.s
.rtlil
.wire(len(value
), src
=_src(value
.src_loc
))
598 self
.s
.rtlil
.connect(sigspec
, self(value
))
601 def on_Part(self
, value
):
602 lhs
, rhs
= value
.value
, value
.offset
603 if value
.stride
!= 1:
605 lhs_bits
, lhs_sign
= lhs
.shape()
606 rhs_bits
, rhs_sign
= rhs
.shape()
607 res_bits
, res_sign
= value
.shape()
608 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
609 # Note: Verilog's x[o+:w] construct produces a $shiftx cell, not a $shift cell.
610 # However, nMigen's semantics defines the out-of-range bits to be zero, so it is correct
611 # to use a $shift cell here instead, even though it produces less idiomatic Verilog.
612 self
.s
.rtlil
.cell("$shift", ports
={
617 "A_SIGNED": lhs_sign
,
619 "B_SIGNED": rhs_sign
,
622 }, src
=_src(value
.src_loc
))
625 def on_Repl(self
, value
):
626 return "{{ {} }}".format(" ".join(self(value
.value
) for _
in range(value
.count
)))
629 class _LHSValueCompiler(_ValueCompiler
):
630 def on_Const(self
, value
):
631 raise TypeError # :nocov:
633 def on_AnyConst(self
, value
):
634 raise TypeError # :nocov:
636 def on_AnySeq(self
, value
):
637 raise TypeError # :nocov:
639 def on_Operator(self
, value
):
640 raise TypeError # :nocov:
642 def match_shape(self
, value
, new_bits
, new_sign
):
643 value_bits
, value_sign
= value
.shape()
644 if new_bits
== value_bits
:
646 elif new_bits
< value_bits
:
647 return self(ast
.Slice(value
, 0, new_bits
))
648 else: # new_bits > value_bits
649 dummy_bits
= new_bits
- value_bits
650 dummy_wire
= self
.s
.rtlil
.wire(dummy_bits
)
651 return "{{ {} {} }}".format(dummy_wire
, self(value
))
653 def on_Signal(self
, value
):
654 if value
not in self
.s
.driven
:
655 raise ValueError("No LHS wire for non-driven signal {}".format(repr(value
)))
656 wire_curr
, wire_next
= self
.s
.resolve(value
)
657 return wire_next
or wire_curr
659 def _prepare_value_for_Slice(self
, value
):
660 assert isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
._InternalCat
))
663 def on_Part(self
, value
):
664 offset
= self
.s
.expand(value
.offset
)
665 if isinstance(offset
, ast
.Const
):
666 start
= offset
.value
* value
.stride
667 stop
= start
+ value
.width
668 slice = self(ast
.Slice(value
.value
, start
, min(len(value
.value
), stop
)))
669 if len(value
.value
) >= stop
:
672 dummy_wire
= self
.s
.rtlil
.wire(stop
- len(value
.value
))
673 return "{{ {} {} }}".format(dummy_wire
, slice)
675 # Only so many possible parts. The amount of branches is exponential; if value.offset
676 # is large (e.g. 32-bit wide), trying to naively legalize it is likely to exhaust
678 max_branches
= len(value
.value
) // value
.stride
+ 1
679 raise _LegalizeValue(value
.offset
,
680 range(1 << len(value
.offset
))[:max_branches
],
683 def on_Repl(self
, value
):
684 raise TypeError # :nocov:
687 class _StatementCompiler(xfrm
.StatementVisitor
):
688 def __init__(self
, state
, rhs_compiler
, lhs_compiler
):
690 self
.rhs_compiler
= rhs_compiler
691 self
.lhs_compiler
= lhs_compiler
694 self
._test
_cache
= {}
695 self
._has
_rhs
= False
696 self
._wrap
_assign
= False
699 def case(self
, switch
, values
, attrs
={}, src
=""):
701 old_case
= self
._case
702 with switch
.case(*values
, attrs
=attrs
, src
=src
) as self
._case
:
705 self
._case
= old_case
707 def _check_rhs(self
, value
):
708 if self
._has
_rhs
or next(iter(value
._rhs
_signals
()), None) is not None:
711 def on_Assign(self
, stmt
):
712 self
._check
_rhs
(stmt
.rhs
)
714 lhs_bits
, lhs_sign
= stmt
.lhs
.shape()
715 rhs_bits
, rhs_sign
= stmt
.rhs
.shape()
716 if lhs_bits
== rhs_bits
:
717 rhs_sigspec
= self
.rhs_compiler(stmt
.rhs
)
719 # In RTLIL, LHS and RHS of assignment must have exactly same width.
720 rhs_sigspec
= self
.rhs_compiler
.match_shape(
721 stmt
.rhs
, lhs_bits
, lhs_sign
)
722 if self
._wrap
_assign
:
723 # In RTLIL, all assigns are logically sequenced before all switches, even if they are
724 # interleaved in the source. In nMigen, the source ordering is used. To handle this
725 # mismatch, we wrap all assigns following a switch in a dummy switch.
726 with self
._case
.switch("{ }") as wrap_switch
:
727 with wrap_switch
.case() as wrap_case
:
728 wrap_case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
730 self
._case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
732 def on_property(self
, stmt
):
733 self(stmt
._check
.eq(stmt
.test
))
736 en_wire
= self
.rhs_compiler(stmt
._en
)
737 check_wire
= self
.rhs_compiler(stmt
._check
)
738 self
.state
.rtlil
.cell("$" + stmt
._kind
, ports
={
741 }, src
=_src(stmt
.src_loc
))
743 on_Assert
= on_property
744 on_Assume
= on_property
745 on_Cover
= on_property
747 def on_Switch(self
, stmt
):
748 self
._check
_rhs
(stmt
.test
)
750 if not self
.state
.expansions
:
751 # We repeatedly translate the same switches over and over (see the LHSGroupAnalyzer
752 # related code below), and translating the switch test only once helps readability.
753 if stmt
not in self
._test
_cache
:
754 self
._test
_cache
[stmt
] = self
.rhs_compiler(stmt
.test
)
755 test_sigspec
= self
._test
_cache
[stmt
]
757 # However, if the switch test contains an illegal value, then it may not be cached
758 # (since the illegal value will be repeatedly replaced with different constants), so
759 # don't cache anything in that case.
760 test_sigspec
= self
.rhs_compiler(stmt
.test
)
762 with self
._case
.switch(test_sigspec
, src
=_src(stmt
.src_loc
)) as switch
:
763 for values
, stmts
in stmt
.cases
.items():
765 if values
in stmt
.case_src_locs
:
766 case_attrs
["src"] = _src(stmt
.case_src_locs
[values
])
767 if isinstance(stmt
.test
, ast
.Signal
) and stmt
.test
.decoder
:
771 decoded_values
.append("<multiple>")
773 decoded_values
.append(stmt
.test
.decoder(int(value
, 2)))
774 case_attrs
["nmigen.decoding"] = "|".join(decoded_values
)
775 with self
.case(switch
, values
, attrs
=case_attrs
):
776 self
._wrap
_assign
= False
777 self
.on_statements(stmts
)
778 self
._wrap
_assign
= True
780 def on_statement(self
, stmt
):
782 super().on_statement(stmt
)
783 except _LegalizeValue
as legalize
:
784 with self
._case
.switch(self
.rhs_compiler(legalize
.value
),
785 src
=_src(legalize
.src_loc
)) as switch
:
786 shape
= legalize
.value
.shape()
787 tests
= ["{:0{}b}".format(v
, shape
.width
) for v
in legalize
.branches
]
789 tests
[-1] = "-" * shape
.width
790 for branch
, test
in zip(legalize
.branches
, tests
):
791 with self
.case(switch
, (test
,)):
792 self
._wrap
_assign
= False
793 branch_value
= ast
.Const(branch
, shape
)
794 with self
.state
.expand_to(legalize
.value
, branch_value
):
795 self
.on_statement(stmt
)
796 self
._wrap
_assign
= True
798 def on_statements(self
, stmts
):
800 self
.on_statement(stmt
)
803 def _convert_fragment(builder
, fragment
, name_map
, hierarchy
):
804 if isinstance(fragment
, ir
.Instance
):
805 port_map
= OrderedDict()
806 for port_name
, (value
, dir) in fragment
.named_ports
.items():
807 port_map
["\\{}".format(port_name
)] = value
809 if fragment
.type[0] == "$":
810 return fragment
.type, port_map
812 return "\\{}".format(fragment
.type), port_map
814 module_name
= hierarchy
[-1] or "anonymous"
815 module_attrs
= OrderedDict()
816 if len(hierarchy
) == 1:
817 module_attrs
["top"] = 1
818 module_attrs
["nmigen.hierarchy"] = ".".join(name
or "anonymous" for name
in hierarchy
)
820 with builder
.module(module_name
, attrs
=module_attrs
) as module
:
821 compiler_state
= _ValueCompilerState(module
)
822 rhs_compiler
= _RHSValueCompiler(compiler_state
)
823 lhs_compiler
= _LHSValueCompiler(compiler_state
)
824 stmt_compiler
= _StatementCompiler(compiler_state
, rhs_compiler
, lhs_compiler
)
826 verilog_trigger
= None
827 verilog_trigger_sync_emitted
= False
829 # If the fragment is completely empty, add a dummy wire to it, or Yosys will interpret
830 # it as a black box by default (when read as Verilog).
831 if not fragment
.ports
and not fragment
.statements
and not fragment
.subfragments
:
832 module
.wire(1, name
="$empty_module_filler")
834 # Register all signals driven in the current fragment. This must be done first, as it
835 # affects further codegen; e.g. whether \sig$next signals will be generated and used.
836 for domain
, signal
in fragment
.iter_drivers():
837 compiler_state
.add_driven(signal
, sync
=domain
is not None)
839 # Transform all signals used as ports in the current fragment eagerly and outside of
840 # any hierarchy, to make sure they get sensible (non-prefixed) names.
841 for signal
in fragment
.ports
:
842 compiler_state
.add_port(signal
, fragment
.ports
[signal
])
843 compiler_state
.resolve_curr(signal
)
845 # Transform all clocks clocks and resets eagerly and outside of any hierarchy, to make
846 # sure they get sensible (non-prefixed) names. This does not affect semantics.
847 for domain
, _
in fragment
.iter_sync():
848 cd
= fragment
.domains
[domain
]
849 compiler_state
.resolve_curr(cd
.clk
)
850 if cd
.rst
is not None:
851 compiler_state
.resolve_curr(cd
.rst
)
853 # Transform all subfragments to their respective cells. Transforming signals connected
854 # to their ports into wires eagerly makes sure they get sensible (prefixed with submodule
856 memories
= OrderedDict()
857 for subfragment
, sub_name
in fragment
.subfragments
:
859 sub_name
= module
.anonymous()
861 sub_params
= OrderedDict()
862 if hasattr(subfragment
, "parameters"):
863 for param_name
, param_value
in subfragment
.parameters
.items():
864 if isinstance(param_value
, mem
.Memory
):
866 if memory
not in memories
:
867 memories
[memory
] = module
.memory(width
=memory
.width
, size
=memory
.depth
,
868 name
=memory
.name
, attrs
=memory
.attrs
)
869 addr_bits
= bits_for(memory
.depth
)
871 data_mask
= (1 << memory
.width
) - 1
872 for addr
in range(memory
.depth
):
873 if addr
< len(memory
.init
):
874 data
= memory
.init
[addr
] & data_mask
877 data_parts
.append("{:0{}b}".format(data
, memory
.width
))
878 module
.cell("$meminit", ports
={
879 "\\ADDR": rhs_compiler(ast
.Const(0, addr_bits
)),
880 "\\DATA": "{}'".format(memory
.width
* memory
.depth
) +
881 "".join(reversed(data_parts
)),
883 "MEMID": memories
[memory
],
885 "WIDTH": memory
.width
,
886 "WORDS": memory
.depth
,
890 param_value
= memories
[memory
]
892 sub_params
[param_name
] = param_value
894 sub_type
, sub_port_map
= \
895 _convert_fragment(builder
, subfragment
, name_map
,
896 hierarchy
=hierarchy
+ (sub_name
,))
898 sub_ports
= OrderedDict()
899 for port
, value
in sub_port_map
.items():
900 if not isinstance(subfragment
, ir
.Instance
):
901 for signal
in value
._rhs
_signals
():
902 compiler_state
.resolve_curr(signal
, prefix
=sub_name
)
904 sub_ports
[port
] = rhs_compiler(value
)
906 module
.cell(sub_type
, name
=sub_name
, ports
=sub_ports
, params
=sub_params
,
907 attrs
=subfragment
.attrs
)
909 # If we emit all of our combinatorial logic into a single RTLIL process, Verilog
910 # simulators will break horribly, because Yosys write_verilog transforms RTLIL processes
911 # into always @* blocks with blocking assignment, and that does not create delta cycles.
913 # Therefore, we translate the fragment as many times as there are independent groups
914 # of signals (a group is a transitive closure of signals that appear together on LHS),
915 # splitting them into many RTLIL (and thus Verilog) processes.
916 lhs_grouper
= xfrm
.LHSGroupAnalyzer()
917 lhs_grouper
.on_statements(fragment
.statements
)
919 for group
, group_signals
in lhs_grouper
.groups().items():
920 lhs_group_filter
= xfrm
.LHSGroupFilter(group_signals
)
921 group_stmts
= lhs_group_filter(fragment
.statements
)
923 with module
.process(name
="$group_{}".format(group
)) as process
:
924 with process
.case() as case
:
925 # For every signal in comb domain, assign \sig$next to the reset value.
926 # For every signal in sync domains, assign \sig$next to the current
928 for domain
, signal
in fragment
.iter_drivers():
929 if signal
not in group_signals
:
932 prev_value
= ast
.Const(signal
.reset
, signal
.width
)
935 case
.assign(lhs_compiler(signal
), rhs_compiler(prev_value
))
937 # Convert statements into decision trees.
938 stmt_compiler
._case
= case
939 stmt_compiler
._has
_rhs
= False
940 stmt_compiler
._wrap
_assign
= False
941 stmt_compiler(group_stmts
)
943 # Verilog `always @*` blocks will not run if `*` does not match anything, i.e.
944 # if the implicit sensitivity list is empty. We check this while translating,
945 # by looking for any signals on RHS. If there aren't any, we add some logic
946 # whose only purpose is to trigger Verilog simulators when it converts
947 # through RTLIL and to Verilog, by populating the sensitivity list.
949 # Unfortunately, while this workaround allows true (event-driven) Verilog
950 # simulators to work properly, and is universally ignored by synthesizers,
951 # Verilator rejects it.
953 # Yosys >=0.9+3468 emits a better workaround on its own, so this code can be
954 # removed completely once support for Yosys 0.9 is dropped.
955 if not stmt_compiler
._has
_rhs
:
956 if verilog_trigger
is None:
958 module
.wire(1, name
="$verilog_initial_trigger")
959 case
.assign(verilog_trigger
, verilog_trigger
)
961 # For every signal in the sync domain, assign \sig's initial value (which will
962 # end up as the \init reg attribute) to the reset value.
963 with process
.sync("init") as sync
:
964 for domain
, signal
in fragment
.iter_sync():
965 if signal
not in group_signals
:
967 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
968 sync
.update(wire_curr
, rhs_compiler(ast
.Const(signal
.reset
, signal
.width
)))
970 # The Verilog simulator trigger needs to change at time 0, so if we haven't
971 # yet done that in some process, do it.
972 if verilog_trigger
and not verilog_trigger_sync_emitted
:
973 sync
.update(verilog_trigger
, "1'0")
974 verilog_trigger_sync_emitted
= True
976 # For every signal in every sync domain, assign \sig to \sig$next. The sensitivity
977 # list, however, differs between domains: for domains with sync reset, it is
978 # `[pos|neg]edge clk`, for sync domains with async reset it is `[pos|neg]edge clk
980 for domain
, signals
in fragment
.drivers
.items():
984 signals
= signals
& group_signals
988 cd
= fragment
.domains
[domain
]
991 triggers
.append((cd
.clk_edge
+ "edge", compiler_state
.resolve_curr(cd
.clk
)))
993 triggers
.append(("posedge", compiler_state
.resolve_curr(cd
.rst
)))
995 for trigger
in triggers
:
996 with process
.sync(*trigger
) as sync
:
997 for signal
in signals
:
998 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
999 sync
.update(wire_curr
, wire_next
)
1001 # Any signals that are used but neither driven nor connected to an input port always
1002 # assume their reset values. We need to assign the reset value explicitly, since only
1003 # driven sync signals are handled by the logic above.
1005 # Because this assignment is done at a late stage, a single Signal object can get assigned
1006 # many times, once in each module it is used. This is a deliberate decision; the possible
1007 # alternatives are to add ports for undriven signals (which requires choosing one module
1008 # to drive it to reset value arbitrarily) or to replace them with their reset value (which
1009 # removes valuable source location information).
1010 driven
= ast
.SignalSet()
1011 for domain
, signals
in fragment
.iter_drivers():
1012 driven
.update(flatten(signal
._lhs
_signals
() for signal
in signals
))
1013 driven
.update(fragment
.iter_ports(dir="i"))
1014 driven
.update(fragment
.iter_ports(dir="io"))
1015 for subfragment
, sub_name
in fragment
.subfragments
:
1016 driven
.update(subfragment
.iter_ports(dir="o"))
1017 driven
.update(subfragment
.iter_ports(dir="io"))
1019 for wire
in compiler_state
.wires
:
1022 wire_curr
, _
= compiler_state
.wires
[wire
]
1023 module
.connect(wire_curr
, rhs_compiler(ast
.Const(wire
.reset
, wire
.width
)))
1025 # Collect the names we've given to our ports in RTLIL, and correlate these with the signals
1026 # represented by these ports. If we are a submodule, this will be necessary to create a cell
1027 # for us in the parent module.
1028 port_map
= OrderedDict()
1029 for signal
in fragment
.ports
:
1030 port_map
[compiler_state
.resolve_curr(signal
)] = signal
1032 # Finally, collect tha names we've given to each wire in RTLIL, and provide these to
1033 # the caller, to allow manipulating them in the toolchain.
1034 for signal
in compiler_state
.wires
:
1035 wire_name
= compiler_state
.resolve_curr(signal
)
1036 if wire_name
.startswith("\\"):
1037 wire_name
= wire_name
[1:]
1038 name_map
[signal
] = hierarchy
+ (wire_name
,)
1040 return module
.name
, port_map
1043 def convert_fragment(fragment
, name
="top"):
1044 assert isinstance(fragment
, ir
.Fragment
)
1045 builder
= _Builder()
1046 name_map
= ast
.SignalDict()
1047 _convert_fragment(builder
, fragment
, name_map
, hierarchy
=(name
,))
1048 return str(builder
), name_map
1051 def convert(elaboratable
, name
="top", platform
=None, **kwargs
):
1052 fragment
= ir
.Fragment
.get(elaboratable
, platform
).prepare(**kwargs
)
1053 il_text
, name_map
= convert_fragment(fragment
, name
)