3 from collections
import defaultdict
, OrderedDict
4 from contextlib
import contextmanager
6 from .._utils
import bits_for
, flatten
7 from ..hdl
import ast
, rec
, ir
, mem
, xfrm
10 __all__
= ["convert", "convert_fragment"]
13 class ImplementationLimit(Exception):
17 _escape_map
= str.maketrans({
27 if isinstance(value
, str):
29 elif isinstance(value
, int):
31 elif isinstance(value
, ast
.Const
):
34 assert False, "Invalid constant {!r}".format(value
)
38 if isinstance(value
, str):
39 return "\"{}\"".format(value
.translate(_escape_map
))
40 elif isinstance(value
, int):
41 if value
in range(0, 2**31-1):
42 return "{:d}".format(value
)
44 # This code path is only used for Instances, where Verilog-like behavior is desirable.
45 # Verilog ensures that integers with unspecified width are 32 bits wide or more.
46 width
= max(32, bits_for(value
))
47 return const(ast
.Const(value
, width
))
48 elif isinstance(value
, ast
.Const
):
49 value_twos_compl
= value
.value
& ((1 << value
.width
) - 1)
50 return "{}'{:0{}b}".format(value
.width
, value_twos_compl
, value
.width
)
52 assert False, "Invalid constant {!r}".format(value
)
63 name
= "U$${}".format(self
._anon
)
64 assert name
not in self
._names
68 def _make_name(self
, name
, local
):
71 name
= "${}".format(self
._index
)
72 elif not local
and name
[0] not in "\\$":
73 name
= "\\{}".format(name
)
74 while name
in self
._names
:
76 name
= "{}${}".format(name
, self
._index
)
81 class _BufferedBuilder
:
84 self
._buffer
= io
.StringIO()
87 return self
._buffer
.getvalue()
89 def _append(self
, fmt
, *args
, **kwargs
):
90 self
._buffer
.write(fmt
.format(*args
, **kwargs
))
93 class _ProxiedBuilder
:
94 def _append(self
, *args
, **kwargs
):
95 self
.rtlil
._append
(*args
, **kwargs
)
99 def _attribute(self
, name
, value
, *, indent
=0):
100 self
._append
("{}attribute \\{} {}\n",
101 " " * indent
, name
, const(value
))
103 def _attributes(self
, attrs
, *, src
=None, **kwargs
):
104 for name
, value
in attrs
.items():
105 self
._attribute
(name
, value
, **kwargs
)
107 self
._attribute
("src", src
, **kwargs
)
110 class _Builder(_Namer
, _BufferedBuilder
):
111 def module(self
, name
=None, attrs
={}):
112 name
= self
._make
_name
(name
, local
=False)
113 return _ModuleBuilder(self
, name
, attrs
)
116 class _ModuleBuilder(_Namer
, _BufferedBuilder
, _AttrBuilder
):
117 def __init__(self
, rtlil
, name
, attrs
):
121 self
.attrs
= {"generator": "nMigen"}
122 self
.attrs
.update(attrs
)
125 self
._attributes
(self
.attrs
)
126 self
._append
("module {}\n", self
.name
)
129 def __exit__(self
, *args
):
130 self
._append
("end\n")
131 self
.rtlil
._buffer
.write(str(self
))
133 def wire(self
, width
, port_id
=None, port_kind
=None, name
=None, attrs
={}, src
=""):
134 # Very large wires are unlikely to work. Verilog 1364-2005 requires the limit on vectors
135 # to be at least 2**16 bits, and Yosys 0.9 breaks on wires of more than 2**32 bits, so
136 # those numbers are our hard bounds. Use 2**24 as the arbitrary boundary beyond which
137 # downstream bugs are more likely than not.
139 raise ImplementationLimit("Wire created at {} is {} bits wide, which is unlikely to "
140 "synthesize correctly"
141 .format(src
or "unknown location", width
))
143 self
._attributes
(attrs
, src
=src
, indent
=1)
144 name
= self
._make
_name
(name
, local
=False)
146 self
._append
(" wire width {} {}\n", width
, name
)
148 assert port_kind
in ("input", "output", "inout")
149 self
._append
(" wire width {} {} {} {}\n", width
, port_kind
, port_id
, name
)
152 def connect(self
, lhs
, rhs
):
153 self
._append
(" connect {} {}\n", lhs
, rhs
)
155 def memory(self
, width
, size
, name
=None, attrs
={}, src
=""):
156 self
._attributes
(attrs
, src
=src
, indent
=1)
157 name
= self
._make
_name
(name
, local
=False)
158 self
._append
(" memory width {} size {} {}\n", width
, size
, name
)
161 def cell(self
, kind
, name
=None, params
={}, ports
={}, attrs
={}, src
=""):
162 self
._attributes
(attrs
, src
=src
, indent
=1)
163 name
= self
._make
_name
(name
, local
=False)
164 self
._append
(" cell {} {}\n", kind
, name
)
165 for param
, value
in params
.items():
166 if isinstance(value
, float):
167 self
._append
(" parameter real \\{} \"{!r}\"\n",
170 self
._append
(" parameter signed \\{} {}\n",
173 self
._append
(" parameter \\{} {}\n",
175 for port
, wire
in ports
.items():
176 self
._append
(" connect {} {}\n", port
, wire
)
177 self
._append
(" end\n")
180 def process(self
, name
=None, attrs
={}, src
=""):
181 name
= self
._make
_name
(name
, local
=True)
182 return _ProcessBuilder(self
, name
, attrs
, src
)
185 class _ProcessBuilder(_BufferedBuilder
, _AttrBuilder
):
186 def __init__(self
, rtlil
, name
, attrs
, src
):
194 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=1)
195 self
._append
(" process {}\n", self
.name
)
198 def __exit__(self
, *args
):
199 self
._append
(" end\n")
200 self
.rtlil
._buffer
.write(str(self
))
203 return _CaseBuilder(self
, indent
=2)
205 def sync(self
, kind
, cond
=None):
206 return _SyncBuilder(self
, kind
, cond
)
209 class _CaseBuilder(_ProxiedBuilder
):
210 def __init__(self
, rtlil
, indent
):
217 def __exit__(self
, *args
):
220 def assign(self
, lhs
, rhs
):
221 self
._append
("{}assign {} {}\n", " " * self
.indent
, lhs
, rhs
)
223 def switch(self
, cond
, attrs
={}, src
=""):
224 return _SwitchBuilder(self
.rtlil
, cond
, attrs
, src
, self
.indent
)
227 class _SwitchBuilder(_ProxiedBuilder
, _AttrBuilder
):
228 def __init__(self
, rtlil
, cond
, attrs
, src
, indent
):
236 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=self
.indent
)
237 self
._append
("{}switch {}\n", " " * self
.indent
, self
.cond
)
240 def __exit__(self
, *args
):
241 self
._append
("{}end\n", " " * self
.indent
)
243 def case(self
, *values
, attrs
={}, src
=""):
244 self
._attributes
(attrs
, src
=src
, indent
=self
.indent
+ 1)
246 self
._append
("{}case\n", " " * (self
.indent
+ 1))
248 self
._append
("{}case {}\n", " " * (self
.indent
+ 1),
249 ", ".join("{}'{}".format(len(value
), value
) for value
in values
))
250 return _CaseBuilder(self
.rtlil
, self
.indent
+ 2)
253 class _SyncBuilder(_ProxiedBuilder
):
254 def __init__(self
, rtlil
, kind
, cond
):
260 if self
.cond
is None:
261 self
._append
(" sync {}\n", self
.kind
)
263 self
._append
(" sync {} {}\n", self
.kind
, self
.cond
)
266 def __exit__(self
, *args
):
269 def update(self
, lhs
, rhs
):
270 self
._append
(" update {} {}\n", lhs
, rhs
)
277 return "{}:{}".format(file, line
)
281 return "|".join(sorted(filter(lambda x
: x
, map(src
, src_locs
))))
284 class LegalizeValue(Exception):
285 def __init__(self
, value
, branches
, src_loc
):
287 self
.branches
= list(branches
)
288 self
.src_loc
= src_loc
291 class _ValueCompilerState
:
292 def __init__(self
, rtlil
):
294 self
.wires
= ast
.SignalDict()
295 self
.driven
= ast
.SignalDict()
296 self
.ports
= ast
.SignalDict()
297 self
.anys
= ast
.ValueDict()
299 self
.expansions
= ast
.ValueDict()
301 def add_driven(self
, signal
, sync
):
302 self
.driven
[signal
] = sync
304 def add_port(self
, signal
, kind
):
305 assert kind
in ("i", "o", "io")
312 self
.ports
[signal
] = (len(self
.ports
), kind
)
314 def resolve(self
, signal
, prefix
=None):
318 if signal
in self
.wires
:
319 return self
.wires
[signal
]
321 if signal
in self
.ports
:
322 port_id
, port_kind
= self
.ports
[signal
]
324 port_id
= port_kind
= None
325 if prefix
is not None:
326 wire_name
= "{}_{}".format(prefix
, signal
.name
)
328 wire_name
= signal
.name
330 attrs
= dict(signal
.attrs
)
331 if signal
._enum
_class
is not None:
332 attrs
["enum_base_type"] = signal
._enum
_class
.__name
__
333 for value
in signal
._enum
_class
:
334 attrs
["enum_value_{:0{}b}".format(value
.value
, signal
.width
)] = value
.name
336 wire_curr
= self
.rtlil
.wire(width
=signal
.width
, name
=wire_name
,
337 port_id
=port_id
, port_kind
=port_kind
,
338 attrs
=attrs
, src
=src(signal
.src_loc
))
339 if signal
in self
.driven
and self
.driven
[signal
]:
340 wire_next
= self
.rtlil
.wire(width
=signal
.width
, name
=wire_curr
+ "$next",
341 src
=src(signal
.src_loc
))
344 self
.wires
[signal
] = (wire_curr
, wire_next
)
346 return wire_curr
, wire_next
348 def resolve_curr(self
, signal
, prefix
=None):
349 wire_curr
, wire_next
= self
.resolve(signal
, prefix
)
352 def expand(self
, value
):
353 if not self
.expansions
:
355 return self
.expansions
.get(value
, value
)
358 def expand_to(self
, value
, expansion
):
360 assert value
not in self
.expansions
361 self
.expansions
[value
] = expansion
364 del self
.expansions
[value
]
367 class _ValueCompiler(xfrm
.ValueVisitor
):
368 def __init__(self
, state
):
371 def on_unknown(self
, value
):
375 super().on_unknown(value
)
377 def on_ClockSignal(self
, value
):
378 raise NotImplementedError # :nocov:
380 def on_ResetSignal(self
, value
):
381 raise NotImplementedError # :nocov:
383 def on_Sample(self
, value
):
384 raise NotImplementedError # :nocov:
386 def on_Initial(self
, value
):
387 raise NotImplementedError # :nocov:
389 def on_Cat(self
, value
):
390 return "{{ {} }}".format(" ".join(reversed([self(o
) for o
in value
.parts
])))
392 def _prepare_value_for_Slice(self
, value
):
393 raise NotImplementedError # :nocov:
395 def on_Slice(self
, value
):
396 if value
.start
== 0 and value
.stop
== len(value
.value
):
397 return self(value
.value
)
399 if isinstance(value
.value
, ast
.UserValue
):
400 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
._lazy
_lower
())
402 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
)
404 if value
.start
== value
.stop
:
406 elif value
.start
+ 1 == value
.stop
:
407 return "{} [{}]".format(sigspec
, value
.start
)
409 return "{} [{}:{}]".format(sigspec
, value
.stop
- 1, value
.start
)
411 def on_ArrayProxy(self
, value
):
412 index
= self
.s
.expand(value
.index
)
413 if isinstance(index
, ast
.Const
):
414 if index
.value
< len(value
.elems
):
415 elem
= value
.elems
[index
.value
]
417 elem
= value
.elems
[-1]
418 return self
.match_shape(elem
, *value
.shape())
420 max_index
= 1 << len(value
.index
)
421 max_elem
= len(value
.elems
)
422 raise LegalizeValue(value
.index
, range(min(max_index
, max_elem
)), value
.src_loc
)
425 class _RHSValueCompiler(_ValueCompiler
):
429 (1, "b"): "$reduce_bool",
430 (1, "r|"): "$reduce_or",
431 (1, "r&"): "$reduce_and",
432 (1, "r^"): "$reduce_xor",
453 def on_value(self
, value
):
454 return super().on_value(self
.s
.expand(value
))
456 def on_Const(self
, value
):
459 def on_AnyConst(self
, value
):
460 if value
in self
.s
.anys
:
461 return self
.s
.anys
[value
]
463 res_bits
, res_sign
= value
.shape()
464 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
465 self
.s
.rtlil
.cell("$anyconst", ports
={
469 }, src
=src(value
.src_loc
))
470 self
.s
.anys
[value
] = res
473 def on_AnySeq(self
, value
):
474 if value
in self
.s
.anys
:
475 return self
.s
.anys
[value
]
477 res_bits
, res_sign
= value
.shape()
478 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
479 self
.s
.rtlil
.cell("$anyseq", ports
={
483 }, src
=src(value
.src_loc
))
484 self
.s
.anys
[value
] = res
487 def on_Signal(self
, value
):
488 wire_curr
, wire_next
= self
.s
.resolve(value
)
491 def on_Operator_unary(self
, value
):
492 arg
, = value
.operands
493 if value
.operator
in ("u", "s"):
494 # These operators don't change the bit pattern, only its interpretation.
497 arg_bits
, arg_sign
= arg
.shape()
498 res_bits
, res_sign
= value
.shape()
499 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
500 self
.s
.rtlil
.cell(self
.operator_map
[(1, value
.operator
)], ports
={
504 "A_SIGNED": arg_sign
,
507 }, src
=src(value
.src_loc
))
510 def match_shape(self
, value
, new_bits
, new_sign
):
511 if isinstance(value
, ast
.Const
):
512 return self(ast
.Const(value
.value
, ast
.Shape(new_bits
, new_sign
)))
514 value_bits
, value_sign
= value
.shape()
515 if new_bits
<= value_bits
:
516 return self(ast
.Slice(value
, 0, new_bits
))
518 res
= self
.s
.rtlil
.wire(width
=new_bits
, src
=src(value
.src_loc
))
519 self
.s
.rtlil
.cell("$pos", ports
={
523 "A_SIGNED": value_sign
,
524 "A_WIDTH": value_bits
,
526 }, src
=src(value
.src_loc
))
529 def on_Operator_binary(self
, value
):
530 lhs
, rhs
= value
.operands
531 lhs_bits
, lhs_sign
= lhs
.shape()
532 rhs_bits
, rhs_sign
= rhs
.shape()
533 if lhs_sign
== rhs_sign
or value
.operator
in ("<<", ">>", "**"):
537 lhs_sign
= rhs_sign
= True
538 lhs_bits
= rhs_bits
= max(lhs_bits
, rhs_bits
)
539 lhs_wire
= self
.match_shape(lhs
, lhs_bits
, lhs_sign
)
540 rhs_wire
= self
.match_shape(rhs
, rhs_bits
, rhs_sign
)
541 res_bits
, res_sign
= value
.shape()
542 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
543 self
.s
.rtlil
.cell(self
.operator_map
[(2, value
.operator
)], ports
={
548 "A_SIGNED": lhs_sign
,
550 "B_SIGNED": rhs_sign
,
553 }, src
=src(value
.src_loc
))
554 if value
.operator
in ("//", "%"):
555 # RTLIL leaves division by zero undefined, but we require it to return zero.
557 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
558 self
.s
.rtlil
.cell("$mux", ports
={
560 "\\B": self(ast
.Const(0, ast
.Shape(res_bits
, res_sign
))),
561 "\\S": self(lhs
== 0),
565 }, src
=src(value
.src_loc
))
568 def on_Operator_mux(self
, value
):
569 sel
, val1
, val0
= value
.operands
570 val1_bits
, val1_sign
= val1
.shape()
571 val0_bits
, val0_sign
= val0
.shape()
572 res_bits
, res_sign
= value
.shape()
573 val1_bits
= val0_bits
= res_bits
= max(val1_bits
, val0_bits
, res_bits
)
574 val1_wire
= self
.match_shape(val1
, val1_bits
, val1_sign
)
575 val0_wire
= self
.match_shape(val0
, val0_bits
, val0_sign
)
576 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
577 self
.s
.rtlil
.cell("$mux", ports
={
584 }, src
=src(value
.src_loc
))
587 def on_Operator(self
, value
):
588 if len(value
.operands
) == 1:
589 return self
.on_Operator_unary(value
)
590 elif len(value
.operands
) == 2:
591 return self
.on_Operator_binary(value
)
592 elif len(value
.operands
) == 3:
593 assert value
.operator
== "m"
594 return self
.on_Operator_mux(value
)
596 raise TypeError # :nocov:
598 def _prepare_value_for_Slice(self
, value
):
599 if isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
)):
600 sigspec
= self(value
)
602 sigspec
= self
.s
.rtlil
.wire(len(value
), src
=src(value
.src_loc
))
603 self
.s
.rtlil
.connect(sigspec
, self(value
))
606 def on_Part(self
, value
):
607 lhs
, rhs
= value
.value
, value
.offset
608 if value
.stride
!= 1:
610 lhs_bits
, lhs_sign
= lhs
.shape()
611 rhs_bits
, rhs_sign
= rhs
.shape()
612 res_bits
, res_sign
= value
.shape()
613 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=src(value
.src_loc
))
614 # Note: Verilog's x[o+:w] construct produces a $shiftx cell, not a $shift cell.
615 # However, nMigen's semantics defines the out-of-range bits to be zero, so it is correct
616 # to use a $shift cell here instead, even though it produces less idiomatic Verilog.
617 self
.s
.rtlil
.cell("$shift", ports
={
622 "A_SIGNED": lhs_sign
,
624 "B_SIGNED": rhs_sign
,
627 }, src
=src(value
.src_loc
))
630 def on_Repl(self
, value
):
631 return "{{ {} }}".format(" ".join(self(value
.value
) for _
in range(value
.count
)))
634 class _LHSValueCompiler(_ValueCompiler
):
635 def on_Const(self
, value
):
636 raise TypeError # :nocov:
638 def on_AnyConst(self
, value
):
639 raise TypeError # :nocov:
641 def on_AnySeq(self
, value
):
642 raise TypeError # :nocov:
644 def on_Operator(self
, value
):
645 raise TypeError # :nocov:
647 def match_shape(self
, value
, new_bits
, new_sign
):
648 value_bits
, value_sign
= value
.shape()
649 if new_bits
== value_bits
:
651 elif new_bits
< value_bits
:
652 return self(ast
.Slice(value
, 0, new_bits
))
653 else: # new_bits > value_bits
654 dummy_bits
= new_bits
- value_bits
655 dummy_wire
= self
.s
.rtlil
.wire(dummy_bits
)
656 return "{{ {} {} }}".format(dummy_wire
, self(value
))
658 def on_Signal(self
, value
):
659 if value
not in self
.s
.driven
:
660 raise ValueError("No LHS wire for non-driven signal {}".format(repr(value
)))
661 wire_curr
, wire_next
= self
.s
.resolve(value
)
662 return wire_next
or wire_curr
664 def _prepare_value_for_Slice(self
, value
):
665 assert isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
))
668 def on_Part(self
, value
):
669 offset
= self
.s
.expand(value
.offset
)
670 if isinstance(offset
, ast
.Const
):
671 start
= offset
.value
* value
.stride
672 stop
= start
+ value
.width
673 slice = self(ast
.Slice(value
.value
, start
, min(len(value
.value
), stop
)))
674 if len(value
.value
) >= stop
:
677 dummy_wire
= self
.s
.rtlil
.wire(stop
- len(value
.value
))
678 return "{{ {} {} }}".format(dummy_wire
, slice)
680 # Only so many possible parts. The amount of branches is exponential; if value.offset
681 # is large (e.g. 32-bit wide), trying to naively legalize it is likely to exhaust
683 max_branches
= len(value
.value
) // value
.stride
+ 1
684 raise LegalizeValue(value
.offset
,
685 range(1 << len(value
.offset
))[:max_branches
],
688 def on_Repl(self
, value
):
689 raise TypeError # :nocov:
692 class _StatementCompiler(xfrm
.StatementVisitor
):
693 def __init__(self
, state
, rhs_compiler
, lhs_compiler
):
695 self
.rhs_compiler
= rhs_compiler
696 self
.lhs_compiler
= lhs_compiler
699 self
._test
_cache
= {}
700 self
._has
_rhs
= False
701 self
._wrap
_assign
= False
704 def case(self
, switch
, values
, attrs
={}, src
=""):
706 old_case
= self
._case
707 with switch
.case(*values
, attrs
=attrs
, src
=src
) as self
._case
:
710 self
._case
= old_case
712 def _check_rhs(self
, value
):
713 if self
._has
_rhs
or next(iter(value
._rhs
_signals
()), None) is not None:
716 def on_Assign(self
, stmt
):
717 self
._check
_rhs
(stmt
.rhs
)
719 lhs_bits
, lhs_sign
= stmt
.lhs
.shape()
720 rhs_bits
, rhs_sign
= stmt
.rhs
.shape()
721 if lhs_bits
== rhs_bits
:
722 rhs_sigspec
= self
.rhs_compiler(stmt
.rhs
)
724 # In RTLIL, LHS and RHS of assignment must have exactly same width.
725 rhs_sigspec
= self
.rhs_compiler
.match_shape(
726 stmt
.rhs
, lhs_bits
, lhs_sign
)
727 if self
._wrap
_assign
:
728 # In RTLIL, all assigns are logically sequenced before all switches, even if they are
729 # interleaved in the source. In nMigen, the source ordering is used. To handle this
730 # mismatch, we wrap all assigns following a switch in a dummy switch.
731 with self
._case
.switch("{ }") as wrap_switch
:
732 with wrap_switch
.case() as wrap_case
:
733 wrap_case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
735 self
._case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
737 def on_property(self
, stmt
):
738 self(stmt
._check
.eq(stmt
.test
))
741 en_wire
= self
.rhs_compiler(stmt
._en
)
742 check_wire
= self
.rhs_compiler(stmt
._check
)
743 self
.state
.rtlil
.cell("$" + stmt
._kind
, ports
={
746 }, src
=src(stmt
.src_loc
))
748 on_Assert
= on_property
749 on_Assume
= on_property
750 on_Cover
= on_property
752 def on_Switch(self
, stmt
):
753 self
._check
_rhs
(stmt
.test
)
755 if not self
.state
.expansions
:
756 # We repeatedly translate the same switches over and over (see the LHSGroupAnalyzer
757 # related code below), and translating the switch test only once helps readability.
758 if stmt
not in self
._test
_cache
:
759 self
._test
_cache
[stmt
] = self
.rhs_compiler(stmt
.test
)
760 test_sigspec
= self
._test
_cache
[stmt
]
762 # However, if the switch test contains an illegal value, then it may not be cached
763 # (since the illegal value will be repeatedly replaced with different constants), so
764 # don't cache anything in that case.
765 test_sigspec
= self
.rhs_compiler(stmt
.test
)
767 with self
._case
.switch(test_sigspec
, src
=src(stmt
.src_loc
)) as switch
:
768 for values
, stmts
in stmt
.cases
.items():
770 if values
in stmt
.case_src_locs
:
771 case_attrs
["src"] = src(stmt
.case_src_locs
[values
])
772 if isinstance(stmt
.test
, ast
.Signal
) and stmt
.test
.decoder
:
776 decoded_values
.append("<multiple>")
778 decoded_values
.append(stmt
.test
.decoder(int(value
, 2)))
779 case_attrs
["nmigen.decoding"] = "|".join(decoded_values
)
780 with self
.case(switch
, values
, attrs
=case_attrs
):
781 self
._wrap
_assign
= False
782 self
.on_statements(stmts
)
783 self
._wrap
_assign
= True
785 def on_statement(self
, stmt
):
787 super().on_statement(stmt
)
788 except LegalizeValue
as legalize
:
789 with self
._case
.switch(self
.rhs_compiler(legalize
.value
),
790 src
=src(legalize
.src_loc
)) as switch
:
791 shape
= legalize
.value
.shape()
792 tests
= ["{:0{}b}".format(v
, shape
.width
) for v
in legalize
.branches
]
794 tests
[-1] = "-" * shape
.width
795 for branch
, test
in zip(legalize
.branches
, tests
):
796 with self
.case(switch
, (test
,)):
797 self
._wrap
_assign
= False
798 branch_value
= ast
.Const(branch
, shape
)
799 with self
.state
.expand_to(legalize
.value
, branch_value
):
800 self
.on_statement(stmt
)
801 self
._wrap
_assign
= True
803 def on_statements(self
, stmts
):
805 self
.on_statement(stmt
)
808 def _convert_fragment(builder
, fragment
, name_map
, hierarchy
):
809 if isinstance(fragment
, ir
.Instance
):
810 port_map
= OrderedDict()
811 for port_name
, (value
, dir) in fragment
.named_ports
.items():
812 port_map
["\\{}".format(port_name
)] = value
814 if fragment
.type[0] == "$":
815 return fragment
.type, port_map
817 return "\\{}".format(fragment
.type), port_map
819 module_name
= hierarchy
[-1] or "anonymous"
820 module_attrs
= OrderedDict()
821 if len(hierarchy
) == 1:
822 module_attrs
["top"] = 1
823 module_attrs
["nmigen.hierarchy"] = ".".join(name
or "anonymous" for name
in hierarchy
)
825 with builder
.module(module_name
, attrs
=module_attrs
) as module
:
826 compiler_state
= _ValueCompilerState(module
)
827 rhs_compiler
= _RHSValueCompiler(compiler_state
)
828 lhs_compiler
= _LHSValueCompiler(compiler_state
)
829 stmt_compiler
= _StatementCompiler(compiler_state
, rhs_compiler
, lhs_compiler
)
831 verilog_trigger
= None
832 verilog_trigger_sync_emitted
= False
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
:
858 if not subfragment
.ports
:
862 sub_name
= module
.anonymous()
864 sub_params
= OrderedDict()
865 if hasattr(subfragment
, "parameters"):
866 for param_name
, param_value
in subfragment
.parameters
.items():
867 if isinstance(param_value
, mem
.Memory
):
869 if memory
not in memories
:
870 memories
[memory
] = module
.memory(width
=memory
.width
, size
=memory
.depth
,
871 name
=memory
.name
, attrs
=memory
.attrs
)
872 addr_bits
= bits_for(memory
.depth
)
874 data_mask
= (1 << memory
.width
) - 1
875 for addr
in range(memory
.depth
):
876 if addr
< len(memory
.init
):
877 data
= memory
.init
[addr
] & data_mask
880 data_parts
.append("{:0{}b}".format(data
, memory
.width
))
881 module
.cell("$meminit", ports
={
882 "\\ADDR": rhs_compiler(ast
.Const(0, addr_bits
)),
883 "\\DATA": "{}'".format(memory
.width
* memory
.depth
) +
884 "".join(reversed(data_parts
)),
886 "MEMID": memories
[memory
],
888 "WIDTH": memory
.width
,
889 "WORDS": memory
.depth
,
893 param_value
= memories
[memory
]
895 sub_params
[param_name
] = param_value
897 sub_type
, sub_port_map
= \
898 _convert_fragment(builder
, subfragment
, name_map
,
899 hierarchy
=hierarchy
+ (sub_name
,))
901 sub_ports
= OrderedDict()
902 for port
, value
in sub_port_map
.items():
903 if not isinstance(subfragment
, ir
.Instance
):
904 for signal
in value
._rhs
_signals
():
905 compiler_state
.resolve_curr(signal
, prefix
=sub_name
)
907 sub_ports
[port
] = rhs_compiler(value
)
909 module
.cell(sub_type
, name
=sub_name
, ports
=sub_ports
, params
=sub_params
,
910 attrs
=subfragment
.attrs
)
912 # If we emit all of our combinatorial logic into a single RTLIL process, Verilog
913 # simulators will break horribly, because Yosys write_verilog transforms RTLIL processes
914 # into always @* blocks with blocking assignment, and that does not create delta cycles.
916 # Therefore, we translate the fragment as many times as there are independent groups
917 # of signals (a group is a transitive closure of signals that appear together on LHS),
918 # splitting them into many RTLIL (and thus Verilog) processes.
919 lhs_grouper
= xfrm
.LHSGroupAnalyzer()
920 lhs_grouper
.on_statements(fragment
.statements
)
922 for group
, group_signals
in lhs_grouper
.groups().items():
923 lhs_group_filter
= xfrm
.LHSGroupFilter(group_signals
)
924 group_stmts
= lhs_group_filter(fragment
.statements
)
926 with module
.process(name
="$group_{}".format(group
)) as process
:
927 with process
.case() as case
:
928 # For every signal in comb domain, assign \sig$next to the reset value.
929 # For every signal in sync domains, assign \sig$next to the current
931 for domain
, signal
in fragment
.iter_drivers():
932 if signal
not in group_signals
:
935 prev_value
= ast
.Const(signal
.reset
, signal
.width
)
938 case
.assign(lhs_compiler(signal
), rhs_compiler(prev_value
))
940 # Convert statements into decision trees.
941 stmt_compiler
._case
= case
942 stmt_compiler
._has
_rhs
= False
943 stmt_compiler
._wrap
_assign
= False
944 stmt_compiler(group_stmts
)
946 # Verilog `always @*` blocks will not run if `*` does not match anything, i.e.
947 # if the implicit sensitivity list is empty. We check this while translating,
948 # by looking for any signals on RHS. If there aren't any, we add some logic
949 # whose only purpose is to trigger Verilog simulators when it converts
950 # through RTLIL and to Verilog, by populating the sensitivity list.
952 # Unfortunately, while this workaround allows true (event-driven) Verilog
953 # simulators to work properly, and is universally ignored by synthesizers,
954 # Verilator rejects it.
956 # Running the Yosys proc_prune pass converts such pathological `always @*`
957 # blocks to `assign` statements, so this workaround can be removed completely
958 # once support for Yosys 0.9 is dropped.
959 if not stmt_compiler
._has
_rhs
:
960 if verilog_trigger
is None:
962 module
.wire(1, name
="$verilog_initial_trigger")
963 case
.assign(verilog_trigger
, verilog_trigger
)
965 # For every signal in the sync domain, assign \sig's initial value (which will
966 # end up as the \init reg attribute) to the reset value.
967 with process
.sync("init") as sync
:
968 for domain
, signal
in fragment
.iter_sync():
969 if signal
not in group_signals
:
971 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
972 sync
.update(wire_curr
, rhs_compiler(ast
.Const(signal
.reset
, signal
.width
)))
974 # The Verilog simulator trigger needs to change at time 0, so if we haven't
975 # yet done that in some process, do it.
976 if verilog_trigger
and not verilog_trigger_sync_emitted
:
977 sync
.update(verilog_trigger
, "1'0")
978 verilog_trigger_sync_emitted
= True
980 # For every signal in every sync domain, assign \sig to \sig$next. The sensitivity
981 # list, however, differs between domains: for domains with sync reset, it is
982 # `[pos|neg]edge clk`, for sync domains with async reset it is `[pos|neg]edge clk
984 for domain
, signals
in fragment
.drivers
.items():
988 signals
= signals
& group_signals
992 cd
= fragment
.domains
[domain
]
995 triggers
.append((cd
.clk_edge
+ "edge", compiler_state
.resolve_curr(cd
.clk
)))
997 triggers
.append(("posedge", compiler_state
.resolve_curr(cd
.rst
)))
999 for trigger
in triggers
:
1000 with process
.sync(*trigger
) as sync
:
1001 for signal
in signals
:
1002 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
1003 sync
.update(wire_curr
, wire_next
)
1005 # Any signals that are used but neither driven nor connected to an input port always
1006 # assume their reset values. We need to assign the reset value explicitly, since only
1007 # driven sync signals are handled by the logic above.
1009 # Because this assignment is done at a late stage, a single Signal object can get assigned
1010 # many times, once in each module it is used. This is a deliberate decision; the possible
1011 # alternatives are to add ports for undriven signals (which requires choosing one module
1012 # to drive it to reset value arbitrarily) or to replace them with their reset value (which
1013 # removes valuable source location information).
1014 driven
= ast
.SignalSet()
1015 for domain
, signals
in fragment
.iter_drivers():
1016 driven
.update(flatten(signal
._lhs
_signals
() for signal
in signals
))
1017 driven
.update(fragment
.iter_ports(dir="i"))
1018 driven
.update(fragment
.iter_ports(dir="io"))
1019 for subfragment
, sub_name
in fragment
.subfragments
:
1020 driven
.update(subfragment
.iter_ports(dir="o"))
1021 driven
.update(subfragment
.iter_ports(dir="io"))
1023 for wire
in compiler_state
.wires
:
1026 wire_curr
, _
= compiler_state
.wires
[wire
]
1027 module
.connect(wire_curr
, rhs_compiler(ast
.Const(wire
.reset
, wire
.width
)))
1029 # Collect the names we've given to our ports in RTLIL, and correlate these with the signals
1030 # represented by these ports. If we are a submodule, this will be necessary to create a cell
1031 # for us in the parent module.
1032 port_map
= OrderedDict()
1033 for signal
in fragment
.ports
:
1034 port_map
[compiler_state
.resolve_curr(signal
)] = signal
1036 # Finally, collect tha names we've given to each wire in RTLIL, and provide these to
1037 # the caller, to allow manipulating them in the toolchain.
1038 for signal
in compiler_state
.wires
:
1039 wire_name
= compiler_state
.resolve_curr(signal
)
1040 if wire_name
.startswith("\\"):
1041 wire_name
= wire_name
[1:]
1042 name_map
[signal
] = hierarchy
+ (wire_name
,)
1044 return module
.name
, port_map
1047 def convert_fragment(fragment
, name
="top"):
1048 assert isinstance(fragment
, ir
.Fragment
)
1049 builder
= _Builder()
1050 name_map
= ast
.SignalDict()
1051 _convert_fragment(builder
, fragment
, name_map
, hierarchy
=(name
,))
1052 return str(builder
), name_map
1055 def convert(elaboratable
, name
="top", platform
=None, **kwargs
):
1056 fragment
= ir
.Fragment
.get(elaboratable
, platform
).prepare(**kwargs
)
1057 il_text
, name_map
= convert_fragment(fragment
, name
)