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
)
33 _escape_map
= str.maketrans({
42 self
._buffer
= io
.StringIO()
45 return self
._buffer
.getvalue()
47 def _append(self
, fmt
, *args
, **kwargs
):
48 self
._buffer
.write(fmt
.format(*args
, **kwargs
))
50 def attribute(self
, name
, value
, indent
=0):
51 if isinstance(value
, str):
52 self
._append
("{}attribute \\{} \"{}\"\n",
53 " " * indent
, name
, value
.translate(self
._escape
_map
))
55 self
._append
("{}attribute \\{} {}\n",
56 " " * indent
, name
, int(value
))
60 self
.attribute("src", src
)
63 class _Builder(_Namer
, _Bufferer
):
64 def module(self
, name
=None, attrs
={}):
65 name
= self
._make
_name
(name
, local
=False)
66 return _ModuleBuilder(self
, name
, attrs
)
69 class _ModuleBuilder(_Namer
, _Bufferer
):
70 def __init__(self
, rtlil
, name
, attrs
):
74 self
.attrs
= {"generator": "nMigen"}
75 self
.attrs
.update(attrs
)
78 for name
, value
in self
.attrs
.items():
79 self
.attribute(name
, value
, indent
=0)
80 self
._append
("module {}\n", self
.name
)
83 def __exit__(self
, *args
):
85 self
.rtlil
._buffer
.write(str(self
))
87 def attribute(self
, name
, value
, indent
=1):
88 super().attribute(name
, value
, indent
)
90 def wire(self
, width
, port_id
=None, port_kind
=None, name
=None, src
=""):
92 name
= self
._make
_name
(name
, local
=False)
94 self
._append
(" wire width {} {}\n", width
, name
)
96 assert port_kind
in ("input", "output", "inout")
97 self
._append
(" wire width {} {} {} {}\n", width
, port_kind
, port_id
, name
)
100 def connect(self
, lhs
, rhs
):
101 self
._append
(" connect {} {}\n", lhs
, rhs
)
103 def memory(self
, width
, size
, name
=None, src
=""):
105 name
= self
._make
_name
(name
, local
=False)
106 self
._append
(" memory width {} size {} {}\n", width
, size
, name
)
109 def cell(self
, kind
, name
=None, params
={}, ports
={}, src
=""):
111 name
= self
._make
_name
(name
, local
=False)
112 self
._append
(" cell {} {}\n", kind
, name
)
113 for param
, value
in params
.items():
114 if isinstance(value
, str):
115 self
._append
(" parameter \\{} \"{}\"\n",
116 param
, value
.translate(self
._escape
_map
))
117 elif isinstance(value
, int):
118 self
._append
(" parameter \\{} {:d}\n",
120 elif isinstance(value
, ast
.Const
):
121 self
._append
(" parameter \\{} {}'{:b}\n",
122 param
, len(value
), value
.value
)
125 for port
, wire
in ports
.items():
126 self
._append
(" connect {} {}\n", port
, wire
)
127 self
._append
(" end\n")
130 def process(self
, name
=None, src
=""):
131 name
= self
._make
_name
(name
, local
=True)
132 return _ProcessBuilder(self
, name
, src
)
135 class _ProcessBuilder(_Bufferer
):
136 def __init__(self
, rtlil
, name
, src
):
144 self
._append
(" process {}\n", self
.name
)
147 def __exit__(self
, *args
):
148 self
._append
(" end\n")
149 self
.rtlil
._buffer
.write(str(self
))
152 return _CaseBuilder(self
, indent
=2)
154 def sync(self
, kind
, cond
=None):
155 return _SyncBuilder(self
, kind
, cond
)
159 def __init__(self
, rtlil
, indent
):
166 def __exit__(self
, *args
):
169 def assign(self
, lhs
, rhs
):
170 self
.rtlil
._append
("{}assign {} {}\n", " " * self
.indent
, lhs
, rhs
)
172 def switch(self
, cond
):
173 return _SwitchBuilder(self
.rtlil
, cond
, self
.indent
)
176 class _SwitchBuilder
:
177 def __init__(self
, rtlil
, cond
, indent
):
183 self
.rtlil
._append
("{}switch {}\n", " " * self
.indent
, self
.cond
)
186 def __exit__(self
, *args
):
187 self
.rtlil
._append
("{}end\n", " " * self
.indent
)
189 def case(self
, value
=None):
191 self
.rtlil
._append
("{}case\n", " " * (self
.indent
+ 1))
193 self
.rtlil
._append
("{}case {}'{}\n", " " * (self
.indent
+ 1),
195 return _CaseBuilder(self
.rtlil
, self
.indent
+ 2)
199 def __init__(self
, rtlil
, kind
, cond
):
205 if self
.cond
is None:
206 self
.rtlil
._append
(" sync {}\n", self
.kind
)
208 self
.rtlil
._append
(" sync {} {}\n", self
.kind
, self
.cond
)
211 def __exit__(self
, *args
):
214 def update(self
, lhs
, rhs
):
215 self
.rtlil
._append
(" update {} {}\n", lhs
, rhs
)
220 return "{}:{}".format(file, line
)
223 class LegalizeValue(Exception):
224 def __init__(self
, value
, branches
):
226 self
.branches
= list(branches
)
229 class _ValueCompilerState
:
230 def __init__(self
, rtlil
):
232 self
.wires
= ast
.SignalDict()
233 self
.driven
= ast
.SignalDict()
234 self
.ports
= ast
.SignalDict()
235 self
.anys
= ast
.ValueDict()
237 self
.expansions
= ast
.ValueDict()
239 def add_driven(self
, signal
, sync
):
240 self
.driven
[signal
] = sync
242 def add_port(self
, signal
, kind
):
243 assert kind
in ("i", "o", "io")
250 self
.ports
[signal
] = (len(self
.ports
), kind
)
252 def resolve(self
, signal
, prefix
=None):
253 if signal
in self
.wires
:
254 return self
.wires
[signal
]
256 if signal
in self
.ports
:
257 port_id
, port_kind
= self
.ports
[signal
]
259 port_id
= port_kind
= None
260 if prefix
is not None:
261 wire_name
= "{}_{}".format(prefix
, signal
.name
)
263 wire_name
= signal
.name
265 for attr_name
, attr_signal
in signal
.attrs
.items():
266 self
.rtlil
.attribute(attr_name
, attr_signal
)
267 wire_curr
= self
.rtlil
.wire(width
=signal
.nbits
, name
=wire_name
,
268 port_id
=port_id
, port_kind
=port_kind
,
269 src
=src(signal
.src_loc
))
270 if signal
in self
.driven
:
271 wire_next
= self
.rtlil
.wire(width
=signal
.nbits
, name
="$next" + wire_curr
,
272 src
=src(signal
.src_loc
))
275 self
.wires
[signal
] = (wire_curr
, wire_next
)
277 return wire_curr
, wire_next
279 def resolve_curr(self
, signal
, prefix
=None):
280 wire_curr
, wire_next
= self
.resolve(signal
, prefix
)
283 def expand(self
, value
):
284 if not self
.expansions
:
286 return self
.expansions
.get(value
, value
)
289 def expand_to(self
, value
, expansion
):
291 assert value
not in self
.expansions
292 self
.expansions
[value
] = expansion
295 del self
.expansions
[value
]
298 class _ValueCompiler(xfrm
.ValueVisitor
):
299 def __init__(self
, state
):
302 def on_unknown(self
, value
):
306 super().on_unknown(value
)
308 def on_ClockSignal(self
, value
):
309 raise NotImplementedError # :nocov:
311 def on_ResetSignal(self
, value
):
312 raise NotImplementedError # :nocov:
314 def on_Sample(self
, value
):
315 raise NotImplementedError # :nocov:
317 def on_Record(self
, value
):
318 return self(ast
.Cat(value
.fields
.values()))
320 def on_Cat(self
, value
):
321 return "{{ {} }}".format(" ".join(reversed([self(o
) for o
in value
.parts
])))
323 def _prepare_value_for_Slice(self
, value
):
324 raise NotImplementedError # :nocov:
326 def on_Slice(self
, value
):
327 if value
.start
== 0 and value
.end
== len(value
.value
):
328 return self(value
.value
)
330 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
)
331 if value
.start
== value
.end
:
333 elif value
.start
+ 1 == value
.end
:
334 return "{} [{}]".format(sigspec
, value
.start
)
336 return "{} [{}:{}]".format(sigspec
, value
.end
- 1, value
.start
)
338 def on_ArrayProxy(self
, value
):
339 index
= self
.s
.expand(value
.index
)
340 if isinstance(index
, ast
.Const
):
341 if index
.value
< len(value
.elems
):
342 elem
= value
.elems
[index
.value
]
344 elem
= value
.elems
[-1]
345 return self
.match_shape(elem
, *value
.shape())
347 raise LegalizeValue(value
.index
, range(len(value
.elems
)))
350 class _RHSValueCompiler(_ValueCompiler
):
354 (1, "b"): "$reduce_bool",
375 def on_value(self
, value
):
376 return super().on_value(self
.s
.expand(value
))
378 def on_Const(self
, value
):
379 if isinstance(value
.value
, str):
380 return "{}'{}".format(value
.nbits
, value
.value
)
382 value_twos_compl
= value
.value
& ((1 << value
.nbits
) - 1)
383 return "{}'{:0{}b}".format(value
.nbits
, value_twos_compl
, value
.nbits
)
385 def on_AnyConst(self
, value
):
386 if value
in self
.s
.anys
:
387 return self
.s
.anys
[value
]
389 res_bits
, res_sign
= value
.shape()
390 res
= self
.s
.rtlil
.wire(width
=res_bits
)
391 self
.s
.rtlil
.cell("$anyconst", ports
={
395 }, src
=src(value
.src_loc
))
396 self
.s
.anys
[value
] = res
399 def on_AnySeq(self
, value
):
400 if value
in self
.s
.anys
:
401 return self
.s
.anys
[value
]
403 res_bits
, res_sign
= value
.shape()
404 res
= self
.s
.rtlil
.wire(width
=res_bits
)
405 self
.s
.rtlil
.cell("$anyseq", ports
={
409 }, src
=src(value
.src_loc
))
410 self
.s
.anys
[value
] = res
413 def on_Signal(self
, value
):
414 wire_curr
, wire_next
= self
.s
.resolve(value
)
417 def on_Operator_unary(self
, value
):
418 arg
, = value
.operands
419 arg_bits
, arg_sign
= arg
.shape()
420 res_bits
, res_sign
= value
.shape()
421 res
= self
.s
.rtlil
.wire(width
=res_bits
)
422 self
.s
.rtlil
.cell(self
.operator_map
[(1, value
.op
)], ports
={
426 "A_SIGNED": arg_sign
,
429 }, src
=src(value
.src_loc
))
432 def match_shape(self
, value
, new_bits
, new_sign
):
433 if isinstance(value
, ast
.Const
):
434 return self(ast
.Const(value
.value
, (new_bits
, new_sign
)))
436 value_bits
, value_sign
= value
.shape()
437 if new_bits
<= value_bits
:
438 return self(ast
.Slice(value
, 0, new_bits
))
440 res
= self
.s
.rtlil
.wire(width
=new_bits
)
441 self
.s
.rtlil
.cell("$pos", ports
={
445 "A_SIGNED": value_sign
,
446 "A_WIDTH": value_bits
,
448 }, src
=src(value
.src_loc
))
451 def on_Operator_binary(self
, value
):
452 lhs
, rhs
= value
.operands
453 lhs_bits
, lhs_sign
= lhs
.shape()
454 rhs_bits
, rhs_sign
= rhs
.shape()
455 if lhs_sign
== rhs_sign
:
459 lhs_sign
= rhs_sign
= True
460 lhs_bits
= rhs_bits
= max(lhs_bits
, rhs_bits
)
461 lhs_wire
= self
.match_shape(lhs
, lhs_bits
, lhs_sign
)
462 rhs_wire
= self
.match_shape(rhs
, rhs_bits
, rhs_sign
)
463 res_bits
, res_sign
= value
.shape()
464 res
= self
.s
.rtlil
.wire(width
=res_bits
)
465 self
.s
.rtlil
.cell(self
.operator_map
[(2, value
.op
)], ports
={
470 "A_SIGNED": lhs_sign
,
472 "B_SIGNED": rhs_sign
,
475 }, src
=src(value
.src_loc
))
478 def on_Operator_mux(self
, value
):
479 sel
, val1
, val0
= value
.operands
480 val1_bits
, val1_sign
= val1
.shape()
481 val0_bits
, val0_sign
= val0
.shape()
482 res_bits
, res_sign
= value
.shape()
483 val1_bits
= val0_bits
= res_bits
= max(val1_bits
, val0_bits
, res_bits
)
484 val1_wire
= self
.match_shape(val1
, val1_bits
, val1_sign
)
485 val0_wire
= self
.match_shape(val0
, val0_bits
, val0_sign
)
486 res
= self
.s
.rtlil
.wire(width
=res_bits
)
487 self
.s
.rtlil
.cell("$mux", ports
={
494 }, src
=src(value
.src_loc
))
497 def on_Operator(self
, value
):
498 if len(value
.operands
) == 1:
499 return self
.on_Operator_unary(value
)
500 elif len(value
.operands
) == 2:
501 return self
.on_Operator_binary(value
)
502 elif len(value
.operands
) == 3:
503 assert value
.op
== "m"
504 return self
.on_Operator_mux(value
)
506 raise TypeError # :nocov:
508 def _prepare_value_for_Slice(self
, value
):
509 if isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
)):
510 sigspec
= self(value
)
512 sigspec
= self
.s
.rtlil
.wire(len(value
))
513 self
.s
.rtlil
.connect(sigspec
, self(value
))
516 def on_Part(self
, value
):
517 lhs
, rhs
= value
.value
, value
.offset
518 lhs_bits
, lhs_sign
= lhs
.shape()
519 rhs_bits
, rhs_sign
= rhs
.shape()
520 res_bits
, res_sign
= value
.shape()
521 res
= self
.s
.rtlil
.wire(width
=res_bits
)
522 # Note: Verilog's x[o+:w] construct produces a $shiftx cell, not a $shift cell.
523 # However, Migen's semantics defines the out-of-range bits to be zero, so it is correct
524 # to use a $shift cell here instead, even though it produces less idiomatic Verilog.
525 self
.s
.rtlil
.cell("$shift", ports
={
530 "A_SIGNED": lhs_sign
,
532 "B_SIGNED": rhs_sign
,
535 }, src
=src(value
.src_loc
))
538 def on_Repl(self
, value
):
539 return "{{ {} }}".format(" ".join(self(value
.value
) for _
in range(value
.count
)))
542 class _LHSValueCompiler(_ValueCompiler
):
543 def on_Const(self
, value
):
544 raise TypeError # :nocov:
546 def on_AnyConst(self
, value
):
547 raise TypeError # :nocov:
549 def on_AnySeq(self
, value
):
550 raise TypeError # :nocov:
552 def on_Operator(self
, value
):
553 raise TypeError # :nocov:
555 def match_shape(self
, value
, new_bits
, new_sign
):
556 assert value
.shape() == (new_bits
, new_sign
)
559 def on_Signal(self
, value
):
560 wire_curr
, wire_next
= self
.s
.resolve(value
)
561 if wire_next
is None:
562 raise ValueError("No LHS wire for non-driven signal {}".format(repr(value
)))
565 def _prepare_value_for_Slice(self
, value
):
566 assert isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
, rec
.Record
))
569 def on_Part(self
, value
):
570 offset
= self
.s
.expand(value
.offset
)
571 if isinstance(offset
, ast
.Const
):
572 return self(ast
.Slice(value
.value
, offset
.value
, offset
.value
+ value
.width
))
574 raise LegalizeValue(value
.offset
, range((1 << len(value
.offset
))))
576 def on_Repl(self
, value
):
577 raise TypeError # :nocov:
580 class _StatementCompiler(xfrm
.StatementVisitor
):
581 def __init__(self
, state
, rhs_compiler
, lhs_compiler
):
583 self
.rhs_compiler
= rhs_compiler
584 self
.lhs_compiler
= lhs_compiler
587 self
._test
_cache
= {}
588 self
._has
_rhs
= False
591 def case(self
, switch
, value
):
593 old_case
= self
._case
594 with switch
.case(value
) as self
._case
:
597 self
._case
= old_case
599 def _check_rhs(self
, value
):
600 if self
._has
_rhs
or next(iter(value
._rhs
_signals
()), None) is not None:
603 def on_Assign(self
, stmt
):
604 self
._check
_rhs
(stmt
.rhs
)
606 lhs_bits
, lhs_sign
= stmt
.lhs
.shape()
607 rhs_bits
, rhs_sign
= stmt
.rhs
.shape()
608 if lhs_bits
== rhs_bits
:
609 rhs_sigspec
= self
.rhs_compiler(stmt
.rhs
)
611 # In RTLIL, LHS and RHS of assignment must have exactly same width.
612 rhs_sigspec
= self
.rhs_compiler
.match_shape(
613 stmt
.rhs
, lhs_bits
, lhs_sign
)
614 self
._case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
616 def on_Assert(self
, stmt
):
617 self(stmt
._check
.eq(stmt
.test
))
620 en_wire
= self
.rhs_compiler(stmt
._en
)
621 check_wire
= self
.rhs_compiler(stmt
._check
)
622 self
.state
.rtlil
.cell("$assert", ports
={
625 }, src
=src(stmt
.src_loc
))
627 def on_Assume(self
, stmt
):
628 self(stmt
._check
.eq(stmt
.test
))
631 en_wire
= self
.rhs_compiler(stmt
._en
)
632 check_wire
= self
.rhs_compiler(stmt
._check
)
633 self
.state
.rtlil
.cell("$assume", ports
={
636 }, src
=src(stmt
.src_loc
))
638 def on_Switch(self
, stmt
):
639 self
._check
_rhs
(stmt
.test
)
641 if stmt
not in self
._test
_cache
:
642 self
._test
_cache
[stmt
] = self
.rhs_compiler(stmt
.test
)
643 test_sigspec
= self
._test
_cache
[stmt
]
645 with self
._case
.switch(test_sigspec
) as switch
:
646 for value
, stmts
in stmt
.cases
.items():
647 with self
.case(switch
, value
):
648 self
.on_statements(stmts
)
650 def on_statement(self
, stmt
):
652 super().on_statement(stmt
)
653 except LegalizeValue
as legalize
:
654 with self
._case
.switch(self
.rhs_compiler(legalize
.value
)) as switch
:
655 bits
, sign
= legalize
.value
.shape()
656 tests
= ["{:0{}b}".format(v
, bits
) for v
in legalize
.branches
]
657 tests
[-1] = "-" * bits
658 for branch
, test
in zip(legalize
.branches
, tests
):
659 with self
.case(switch
, test
):
660 branch_value
= ast
.Const(branch
, (bits
, sign
))
661 with self
.state
.expand_to(legalize
.value
, branch_value
):
662 super().on_statement(stmt
)
664 def on_statements(self
, stmts
):
666 self
.on_statement(stmt
)
669 def convert_fragment(builder
, fragment
, hierarchy
):
670 if isinstance(fragment
, ir
.Instance
):
671 port_map
= OrderedDict()
672 for port_name
, (value
, dir) in fragment
.named_ports
.items():
673 port_map
["\\{}".format(port_name
)] = value
675 if fragment
.type[0] == "$":
676 return fragment
.type, port_map
678 return "\\{}".format(fragment
.type), port_map
680 module_name
= hierarchy
[-1] or "anonymous"
682 if len(hierarchy
) == 1:
683 module_attrs
["top"] = 1
684 module_attrs
["nmigen.hierarchy"] = ".".join(name
or "anonymous" for name
in hierarchy
)
686 with builder
.module(module_name
, attrs
=module_attrs
) as module
:
687 compiler_state
= _ValueCompilerState(module
)
688 rhs_compiler
= _RHSValueCompiler(compiler_state
)
689 lhs_compiler
= _LHSValueCompiler(compiler_state
)
690 stmt_compiler
= _StatementCompiler(compiler_state
, rhs_compiler
, lhs_compiler
)
692 verilog_trigger
= None
693 verilog_trigger_sync_emitted
= False
695 # Register all signals driven in the current fragment. This must be done first, as it
696 # affects further codegen; e.g. whether $next\sig signals will be generated and used.
697 for domain
, signal
in fragment
.iter_drivers():
698 compiler_state
.add_driven(signal
, sync
=domain
is not None)
700 # Transform all signals used as ports in the current fragment eagerly and outside of
701 # any hierarchy, to make sure they get sensible (non-prefixed) names.
702 for signal
in fragment
.ports
:
703 compiler_state
.add_port(signal
, fragment
.ports
[signal
])
704 compiler_state
.resolve_curr(signal
)
706 # Transform all clocks clocks and resets eagerly and outside of any hierarchy, to make
707 # sure they get sensible (non-prefixed) names. This does not affect semantics.
708 for domain
, _
in fragment
.iter_sync():
709 cd
= fragment
.domains
[domain
]
710 compiler_state
.resolve_curr(cd
.clk
)
711 if cd
.rst
is not None:
712 compiler_state
.resolve_curr(cd
.rst
)
714 # Transform all subfragments to their respective cells. Transforming signals connected
715 # to their ports into wires eagerly makes sure they get sensible (prefixed with submodule
717 memories
= OrderedDict()
718 for subfragment
, sub_name
in fragment
.subfragments
:
719 if not subfragment
.ports
:
722 sub_params
= OrderedDict()
723 if hasattr(subfragment
, "parameters"):
724 for param_name
, param_value
in subfragment
.parameters
.items():
725 if isinstance(param_value
, mem
.Memory
):
727 if memory
not in memories
:
728 memories
[memory
] = module
.memory(width
=memory
.width
, size
=memory
.depth
,
730 addr_bits
= bits_for(memory
.depth
)
732 data_mask
= (1 << memory
.width
) - 1
733 for addr
in range(memory
.depth
):
734 if addr
< len(memory
.init
):
735 data
= memory
.init
[addr
] & data_mask
738 data_parts
.append("{:0{}b}".format(data
, memory
.width
))
739 module
.cell("$meminit", ports
={
740 "\\ADDR": rhs_compiler(ast
.Const(0, addr_bits
)),
741 "\\DATA": "{}'".format(memory
.width
* memory
.depth
) +
742 "".join(reversed(data_parts
)),
744 "MEMID": memories
[memory
],
746 "WIDTH": memory
.width
,
747 "WORDS": memory
.depth
,
751 param_value
= memories
[memory
]
753 sub_params
[param_name
] = param_value
755 sub_type
, sub_port_map
= \
756 convert_fragment(builder
, subfragment
, hierarchy
=hierarchy
+ (sub_name
,))
758 sub_ports
= OrderedDict()
759 for port
, value
in sub_port_map
.items():
760 for signal
in value
._rhs
_signals
():
761 compiler_state
.resolve_curr(signal
, prefix
=sub_name
)
762 sub_ports
[port
] = rhs_compiler(value
)
764 module
.cell(sub_type
, name
=sub_name
, ports
=sub_ports
, params
=sub_params
)
766 # If we emit all of our combinatorial logic into a single RTLIL process, Verilog
767 # simulators will break horribly, because Yosys write_verilog transforms RTLIL processes
768 # into always @* blocks with blocking assignment, and that does not create delta cycles.
770 # Therefore, we translate the fragment as many times as there are independent groups
771 # of signals (a group is a transitive closure of signals that appear together on LHS),
772 # splitting them into many RTLIL (and thus Verilog) processes.
773 lhs_grouper
= xfrm
.LHSGroupAnalyzer()
774 lhs_grouper
.on_statements(fragment
.statements
)
776 for group
, group_signals
in lhs_grouper
.groups().items():
777 lhs_group_filter
= xfrm
.LHSGroupFilter(group_signals
)
779 with module
.process(name
="$group_{}".format(group
)) as process
:
780 with process
.case() as case
:
781 # For every signal in comb domain, assign $next\sig to the reset value.
782 # For every signal in sync domains, assign $next\sig to the current
784 for domain
, signal
in fragment
.iter_drivers():
785 if signal
not in group_signals
:
788 prev_value
= ast
.Const(signal
.reset
, signal
.nbits
)
791 case
.assign(lhs_compiler(signal
), rhs_compiler(prev_value
))
793 # Convert statements into decision trees.
794 stmt_compiler
._case
= case
795 stmt_compiler
._has
_rhs
= False
796 stmt_compiler(lhs_group_filter(fragment
.statements
))
798 # Verilog `always @*` blocks will not run if `*` does not match anything, i.e.
799 # if the implicit sensitivity list is empty. We check this while translating,
800 # by looking for any signals on RHS. If there aren't any, we add some logic
801 # whose only purpose is to trigger Verilog simulators when it converts
802 # through RTLIL and to Verilog, by populating the sensitivity list.
803 if not stmt_compiler
._has
_rhs
:
804 if verilog_trigger
is None:
806 module
.wire(1, name
="$verilog_initial_trigger")
807 case
.assign(verilog_trigger
, verilog_trigger
)
809 # For every signal in the sync domain, assign \sig's initial value (which will
810 # end up as the \init reg attribute) to the reset value.
811 with process
.sync("init") as sync
:
812 for domain
, signal
in fragment
.iter_sync():
813 if signal
not in group_signals
:
815 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
816 sync
.update(wire_curr
, rhs_compiler(ast
.Const(signal
.reset
, signal
.nbits
)))
818 # The Verilog simulator trigger needs to change at time 0, so if we haven't
819 # yet done that in some process, do it.
820 if verilog_trigger
and not verilog_trigger_sync_emitted
:
821 sync
.update(verilog_trigger
, "1'0")
822 verilog_trigger_sync_emitted
= True
824 # For every signal in every domain, assign \sig to $next\sig. The sensitivity list,
825 # however, differs between domains: for comb domains, it is `always`, for sync
826 # domains with sync reset, it is `posedge clk`, for sync domains with async reset
827 # it is `posedge clk or posedge rst`.
828 for domain
, signals
in fragment
.drivers
.items():
829 signals
= signals
& group_signals
835 triggers
.append(("always",))
837 cd
= fragment
.domains
[domain
]
838 triggers
.append(("posedge", compiler_state
.resolve_curr(cd
.clk
)))
840 triggers
.append(("posedge", compiler_state
.resolve_curr(cd
.rst
)))
842 for trigger
in triggers
:
843 with process
.sync(*trigger
) as sync
:
844 for signal
in signals
:
845 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
846 sync
.update(wire_curr
, wire_next
)
848 # Any signals that are used but neither driven nor connected to an input port always
849 # assume their reset values. We need to assign the reset value explicitly, since only
850 # driven sync signals are handled by the logic above.
852 # Because this assignment is done at a late stage, a single Signal object can get assigned
853 # many times, once in each module it is used. This is a deliberate decision; the possible
854 # alternatives are to add ports for undriven signals (which requires choosing one module
855 # to drive it to reset value arbitrarily) or to replace them with their reset value (which
856 # removes valuable source location information).
857 driven
= ast
.SignalSet()
858 for domain
, signals
in fragment
.iter_drivers():
859 driven
.update(flatten(signal
._lhs
_signals
() for signal
in signals
))
860 driven
.update(fragment
.iter_ports(dir="i"))
861 driven
.update(fragment
.iter_ports(dir="io"))
862 for subfragment
, sub_name
in fragment
.subfragments
:
863 driven
.update(subfragment
.iter_ports(dir="o"))
864 driven
.update(subfragment
.iter_ports(dir="io"))
866 for wire
in compiler_state
.wires
:
869 wire_curr
, _
= compiler_state
.wires
[wire
]
870 module
.connect(wire_curr
, rhs_compiler(ast
.Const(wire
.reset
, wire
.nbits
)))
872 # Finally, collect the names we've given to our ports in RTLIL, and correlate these with
873 # the signals represented by these ports. If we are a submodule, this will be necessary
874 # to create a cell for us in the parent module.
875 port_map
= OrderedDict()
876 for signal
in fragment
.ports
:
877 port_map
[compiler_state
.resolve_curr(signal
)] = signal
879 return module
.name
, port_map
882 def convert(fragment
, name
="top", platform
=None, **kwargs
):
883 fragment
= ir
.Fragment
.get(fragment
, platform
).prepare(**kwargs
)
885 convert_fragment(builder
, fragment
, hierarchy
=(name
,))