back.rtlil: give private items an appropriate name. NFCI.
[nmigen.git] / nmigen / back / rtlil.py
1 import io
2 import textwrap
3 from collections import defaultdict, OrderedDict
4 from contextlib import contextmanager
5
6 from .._utils import bits_for, flatten
7 from ..hdl import ast, rec, ir, mem, xfrm
8
9
10 __all__ = ["convert", "convert_fragment"]
11
12
13 class ImplementationLimit(Exception):
14 pass
15
16
17 _escape_map = str.maketrans({
18 "\"": "\\\"",
19 "\\": "\\\\",
20 "\t": "\\t",
21 "\r": "\\r",
22 "\n": "\\n",
23 })
24
25
26 def _signed(value):
27 if isinstance(value, str):
28 return False
29 elif isinstance(value, int):
30 return value < 0
31 elif isinstance(value, ast.Const):
32 return value.signed
33 else:
34 assert False, "Invalid constant {!r}".format(value)
35
36
37 def _const(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)
43 else:
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)
51 else:
52 assert False, "Invalid constant {!r}".format(value)
53
54
55 class _Namer:
56 def __init__(self):
57 super().__init__()
58 self._anon = 0
59 self._index = 0
60 self._names = set()
61
62 def anonymous(self):
63 name = "U$${}".format(self._anon)
64 assert name not in self._names
65 self._anon += 1
66 return name
67
68 def _make_name(self, name, local):
69 if name is None:
70 self._index += 1
71 name = "${}".format(self._index)
72 elif not local and name[0] not in "\\$":
73 name = "\\{}".format(name)
74 while name in self._names:
75 self._index += 1
76 name = "{}${}".format(name, self._index)
77 self._names.add(name)
78 return name
79
80
81 class _BufferedBuilder:
82 def __init__(self):
83 super().__init__()
84 self._buffer = io.StringIO()
85
86 def __str__(self):
87 return self._buffer.getvalue()
88
89 def _append(self, fmt, *args, **kwargs):
90 self._buffer.write(fmt.format(*args, **kwargs))
91
92
93 class _ProxiedBuilder:
94 def _append(self, *args, **kwargs):
95 self.rtlil._append(*args, **kwargs)
96
97
98 class _AttrBuilder:
99 def _attribute(self, name, value, *, indent=0):
100 self._append("{}attribute \\{} {}\n",
101 " " * indent, name, _const(value))
102
103 def _attributes(self, attrs, *, src=None, **kwargs):
104 for name, value in attrs.items():
105 self._attribute(name, value, **kwargs)
106 if src:
107 self._attribute("src", src, **kwargs)
108
109
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)
114
115
116 class _ModuleBuilder(_Namer, _BufferedBuilder, _AttrBuilder):
117 def __init__(self, rtlil, name, attrs):
118 super().__init__()
119 self.rtlil = rtlil
120 self.name = name
121 self.attrs = {"generator": "nMigen"}
122 self.attrs.update(attrs)
123
124 def __enter__(self):
125 self._attributes(self.attrs)
126 self._append("module {}\n", self.name)
127 return self
128
129 def __exit__(self, *args):
130 self._append("end\n")
131 self.rtlil._buffer.write(str(self))
132
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 cannot read RTLIL with wires larger than 2**32
136 # bits. In practice, wires larger than 2**16 bits, although accepted, cause performance
137 # problems without an immediately visible cause, so conservatively limit wire size.
138 if width > 2 ** 16:
139 raise ImplementationLimit("Wire created at {} is {} bits wide, which is unlikely to "
140 "synthesize correctly"
141 .format(src or "unknown location", width))
142
143 self._attributes(attrs, src=src, indent=1)
144 name = self._make_name(name, local=False)
145 if port_id is None:
146 self._append(" wire width {} {}\n", width, name)
147 else:
148 assert port_kind in ("input", "output", "inout")
149 self._append(" wire width {} {} {} {}\n", width, port_kind, port_id, name)
150 return name
151
152 def connect(self, lhs, rhs):
153 self._append(" connect {} {}\n", lhs, rhs)
154
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)
159 return name
160
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",
168 param, value)
169 elif _signed(value):
170 self._append(" parameter signed \\{} {}\n",
171 param, _const(value))
172 else:
173 self._append(" parameter \\{} {}\n",
174 param, _const(value))
175 for port, wire in ports.items():
176 self._append(" connect {} {}\n", port, wire)
177 self._append(" end\n")
178 return name
179
180 def process(self, name=None, attrs={}, src=""):
181 name = self._make_name(name, local=True)
182 return _ProcessBuilder(self, name, attrs, src)
183
184
185 class _ProcessBuilder(_BufferedBuilder, _AttrBuilder):
186 def __init__(self, rtlil, name, attrs, src):
187 super().__init__()
188 self.rtlil = rtlil
189 self.name = name
190 self.attrs = {}
191 self.src = src
192
193 def __enter__(self):
194 self._attributes(self.attrs, src=self.src, indent=1)
195 self._append(" process {}\n", self.name)
196 return self
197
198 def __exit__(self, *args):
199 self._append(" end\n")
200 self.rtlil._buffer.write(str(self))
201
202 def case(self):
203 return _CaseBuilder(self, indent=2)
204
205 def sync(self, kind, cond=None):
206 return _SyncBuilder(self, kind, cond)
207
208
209 class _CaseBuilder(_ProxiedBuilder):
210 def __init__(self, rtlil, indent):
211 self.rtlil = rtlil
212 self.indent = indent
213
214 def __enter__(self):
215 return self
216
217 def __exit__(self, *args):
218 pass
219
220 def assign(self, lhs, rhs):
221 self._append("{}assign {} {}\n", " " * self.indent, lhs, rhs)
222
223 def switch(self, cond, attrs={}, src=""):
224 return _SwitchBuilder(self.rtlil, cond, attrs, src, self.indent)
225
226
227 class _SwitchBuilder(_ProxiedBuilder, _AttrBuilder):
228 def __init__(self, rtlil, cond, attrs, src, indent):
229 self.rtlil = rtlil
230 self.cond = cond
231 self.attrs = attrs
232 self.src = src
233 self.indent = indent
234
235 def __enter__(self):
236 self._attributes(self.attrs, src=self.src, indent=self.indent)
237 self._append("{}switch {}\n", " " * self.indent, self.cond)
238 return self
239
240 def __exit__(self, *args):
241 self._append("{}end\n", " " * self.indent)
242
243 def case(self, *values, attrs={}, src=""):
244 self._attributes(attrs, src=src, indent=self.indent + 1)
245 if values == ():
246 self._append("{}case\n", " " * (self.indent + 1))
247 else:
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)
251
252
253 class _SyncBuilder(_ProxiedBuilder):
254 def __init__(self, rtlil, kind, cond):
255 self.rtlil = rtlil
256 self.kind = kind
257 self.cond = cond
258
259 def __enter__(self):
260 if self.cond is None:
261 self._append(" sync {}\n", self.kind)
262 else:
263 self._append(" sync {} {}\n", self.kind, self.cond)
264 return self
265
266 def __exit__(self, *args):
267 pass
268
269 def update(self, lhs, rhs):
270 self._append(" update {} {}\n", lhs, rhs)
271
272
273 def _src(src_loc):
274 if src_loc is None:
275 return None
276 file, line = src_loc
277 return "{}:{}".format(file, line)
278
279
280 class _LegalizeValue(Exception):
281 def __init__(self, value, branches, src_loc):
282 self.value = value
283 self.branches = list(branches)
284 self.src_loc = src_loc
285
286
287 class _ValueCompilerState:
288 def __init__(self, rtlil):
289 self.rtlil = rtlil
290 self.wires = ast.SignalDict()
291 self.driven = ast.SignalDict()
292 self.ports = ast.SignalDict()
293 self.anys = ast.ValueDict()
294
295 self.expansions = ast.ValueDict()
296
297 def add_driven(self, signal, sync):
298 self.driven[signal] = sync
299
300 def add_port(self, signal, kind):
301 assert kind in ("i", "o", "io")
302 if kind == "i":
303 kind = "input"
304 elif kind == "o":
305 kind = "output"
306 elif kind == "io":
307 kind = "inout"
308 self.ports[signal] = (len(self.ports), kind)
309
310 def resolve(self, signal, prefix=None):
311 if len(signal) == 0:
312 return "{ }", "{ }"
313
314 if signal in self.wires:
315 return self.wires[signal]
316
317 if signal in self.ports:
318 port_id, port_kind = self.ports[signal]
319 else:
320 port_id = port_kind = None
321 if prefix is not None:
322 wire_name = "{}_{}".format(prefix, signal.name)
323 else:
324 wire_name = signal.name
325
326 attrs = dict(signal.attrs)
327 if signal._enum_class is not None:
328 attrs["enum_base_type"] = signal._enum_class.__name__
329 for value in signal._enum_class:
330 attrs["enum_value_{:0{}b}".format(value.value, signal.width)] = value.name
331
332 wire_curr = self.rtlil.wire(width=signal.width, name=wire_name,
333 port_id=port_id, port_kind=port_kind,
334 attrs=attrs, src=_src(signal.src_loc))
335 if signal in self.driven and self.driven[signal]:
336 wire_next = self.rtlil.wire(width=signal.width, name=wire_curr + "$next",
337 src=_src(signal.src_loc))
338 else:
339 wire_next = None
340 self.wires[signal] = (wire_curr, wire_next)
341
342 return wire_curr, wire_next
343
344 def resolve_curr(self, signal, prefix=None):
345 wire_curr, wire_next = self.resolve(signal, prefix)
346 return wire_curr
347
348 def expand(self, value):
349 if not self.expansions:
350 return value
351 return self.expansions.get(value, value)
352
353 @contextmanager
354 def expand_to(self, value, expansion):
355 try:
356 assert value not in self.expansions
357 self.expansions[value] = expansion
358 yield
359 finally:
360 del self.expansions[value]
361
362
363 class _ValueCompiler(xfrm.ValueVisitor):
364 def __init__(self, state):
365 self.s = state
366
367 def on_unknown(self, value):
368 if value is None:
369 return None
370 else:
371 super().on_unknown(value)
372
373 def on_ClockSignal(self, value):
374 raise NotImplementedError # :nocov:
375
376 def on_ResetSignal(self, value):
377 raise NotImplementedError # :nocov:
378
379 def on_Sample(self, value):
380 raise NotImplementedError # :nocov:
381
382 def on_Initial(self, value):
383 raise NotImplementedError # :nocov:
384
385 def on_Cat(self, value):
386 return "{{ {} }}".format(" ".join(reversed([self(o) for o in value.parts])))
387
388 def _prepare_value_for_Slice(self, value):
389 raise NotImplementedError # :nocov:
390
391 def on_Slice(self, value):
392 if value.start == 0 and value.stop == len(value.value):
393 return self(value.value)
394
395 if isinstance(value.value, ast.UserValue):
396 sigspec = self._prepare_value_for_Slice(value.value._lazy_lower())
397 else:
398 sigspec = self._prepare_value_for_Slice(value.value)
399
400 if value.start == value.stop:
401 return "{}"
402 elif value.start + 1 == value.stop:
403 return "{} [{}]".format(sigspec, value.start)
404 else:
405 return "{} [{}:{}]".format(sigspec, value.stop - 1, value.start)
406
407 def on_ArrayProxy(self, value):
408 index = self.s.expand(value.index)
409 if isinstance(index, ast.Const):
410 if index.value < len(value.elems):
411 elem = value.elems[index.value]
412 else:
413 elem = value.elems[-1]
414 return self.match_shape(elem, *value.shape())
415 else:
416 max_index = 1 << len(value.index)
417 max_elem = len(value.elems)
418 raise _LegalizeValue(value.index, range(min(max_index, max_elem)), value.src_loc)
419
420
421 class _RHSValueCompiler(_ValueCompiler):
422 operator_map = {
423 (1, "~"): "$not",
424 (1, "-"): "$neg",
425 (1, "b"): "$reduce_bool",
426 (1, "r|"): "$reduce_or",
427 (1, "r&"): "$reduce_and",
428 (1, "r^"): "$reduce_xor",
429 (2, "+"): "$add",
430 (2, "-"): "$sub",
431 (2, "*"): "$mul",
432 (2, "//"): "$div",
433 (2, "%"): "$mod",
434 (2, "**"): "$pow",
435 (2, "<<"): "$sshl",
436 (2, ">>"): "$sshr",
437 (2, "&"): "$and",
438 (2, "^"): "$xor",
439 (2, "|"): "$or",
440 (2, "=="): "$eq",
441 (2, "!="): "$ne",
442 (2, "<"): "$lt",
443 (2, "<="): "$le",
444 (2, ">"): "$gt",
445 (2, ">="): "$ge",
446 (3, "m"): "$mux",
447 }
448
449 def on_value(self, value):
450 return super().on_value(self.s.expand(value))
451
452 def on_Const(self, value):
453 return _const(value)
454
455 def on_AnyConst(self, value):
456 if value in self.s.anys:
457 return self.s.anys[value]
458
459 res_bits, res_sign = value.shape()
460 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
461 self.s.rtlil.cell("$anyconst", ports={
462 "\\Y": res,
463 }, params={
464 "WIDTH": res_bits,
465 }, src=_src(value.src_loc))
466 self.s.anys[value] = res
467 return res
468
469 def on_AnySeq(self, value):
470 if value in self.s.anys:
471 return self.s.anys[value]
472
473 res_bits, res_sign = value.shape()
474 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
475 self.s.rtlil.cell("$anyseq", ports={
476 "\\Y": res,
477 }, params={
478 "WIDTH": res_bits,
479 }, src=_src(value.src_loc))
480 self.s.anys[value] = res
481 return res
482
483 def on_Signal(self, value):
484 wire_curr, wire_next = self.s.resolve(value)
485 return wire_curr
486
487 def on_Operator_unary(self, value):
488 arg, = value.operands
489 if value.operator in ("u", "s"):
490 # These operators don't change the bit pattern, only its interpretation.
491 return self(arg)
492
493 arg_bits, arg_sign = arg.shape()
494 res_bits, res_sign = value.shape()
495 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
496 self.s.rtlil.cell(self.operator_map[(1, value.operator)], ports={
497 "\\A": self(arg),
498 "\\Y": res,
499 }, params={
500 "A_SIGNED": arg_sign,
501 "A_WIDTH": arg_bits,
502 "Y_WIDTH": res_bits,
503 }, src=_src(value.src_loc))
504 return res
505
506 def match_shape(self, value, new_bits, new_sign):
507 if isinstance(value, ast.Const):
508 return self(ast.Const(value.value, ast.Shape(new_bits, new_sign)))
509
510 value_bits, value_sign = value.shape()
511 if new_bits <= value_bits:
512 return self(ast.Slice(value, 0, new_bits))
513
514 res = self.s.rtlil.wire(width=new_bits, src=_src(value.src_loc))
515 self.s.rtlil.cell("$pos", ports={
516 "\\A": self(value),
517 "\\Y": res,
518 }, params={
519 "A_SIGNED": value_sign,
520 "A_WIDTH": value_bits,
521 "Y_WIDTH": new_bits,
522 }, src=_src(value.src_loc))
523 return res
524
525 def on_Operator_binary(self, value):
526 lhs, rhs = value.operands
527 lhs_bits, lhs_sign = lhs.shape()
528 rhs_bits, rhs_sign = rhs.shape()
529 if lhs_sign == rhs_sign or value.operator in ("<<", ">>", "**"):
530 lhs_wire = self(lhs)
531 rhs_wire = self(rhs)
532 else:
533 lhs_sign = rhs_sign = True
534 lhs_bits = rhs_bits = max(lhs_bits, rhs_bits)
535 lhs_wire = self.match_shape(lhs, lhs_bits, lhs_sign)
536 rhs_wire = self.match_shape(rhs, rhs_bits, rhs_sign)
537 res_bits, res_sign = value.shape()
538 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
539 self.s.rtlil.cell(self.operator_map[(2, value.operator)], ports={
540 "\\A": lhs_wire,
541 "\\B": rhs_wire,
542 "\\Y": res,
543 }, params={
544 "A_SIGNED": lhs_sign,
545 "A_WIDTH": lhs_bits,
546 "B_SIGNED": rhs_sign,
547 "B_WIDTH": rhs_bits,
548 "Y_WIDTH": res_bits,
549 }, src=_src(value.src_loc))
550 if value.operator in ("//", "%"):
551 # RTLIL leaves division by zero undefined, but we require it to return zero.
552 divmod_res = res
553 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
554 self.s.rtlil.cell("$mux", ports={
555 "\\A": divmod_res,
556 "\\B": self(ast.Const(0, ast.Shape(res_bits, res_sign))),
557 "\\S": self(rhs == 0),
558 "\\Y": res,
559 }, params={
560 "WIDTH": res_bits
561 }, src=_src(value.src_loc))
562 return res
563
564 def on_Operator_mux(self, value):
565 sel, val1, val0 = value.operands
566 val1_bits, val1_sign = val1.shape()
567 val0_bits, val0_sign = val0.shape()
568 res_bits, res_sign = value.shape()
569 val1_bits = val0_bits = res_bits = max(val1_bits, val0_bits, res_bits)
570 val1_wire = self.match_shape(val1, val1_bits, val1_sign)
571 val0_wire = self.match_shape(val0, val0_bits, val0_sign)
572 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
573 self.s.rtlil.cell("$mux", ports={
574 "\\A": val0_wire,
575 "\\B": val1_wire,
576 "\\S": self(sel),
577 "\\Y": res,
578 }, params={
579 "WIDTH": res_bits
580 }, src=_src(value.src_loc))
581 return res
582
583 def on_Operator(self, value):
584 if len(value.operands) == 1:
585 return self.on_Operator_unary(value)
586 elif len(value.operands) == 2:
587 return self.on_Operator_binary(value)
588 elif len(value.operands) == 3:
589 assert value.operator == "m"
590 return self.on_Operator_mux(value)
591 else:
592 raise TypeError # :nocov:
593
594 def _prepare_value_for_Slice(self, value):
595 if isinstance(value, (ast.Signal, ast.Slice, ast.Cat)):
596 sigspec = self(value)
597 else:
598 sigspec = self.s.rtlil.wire(len(value), src=_src(value.src_loc))
599 self.s.rtlil.connect(sigspec, self(value))
600 return sigspec
601
602 def on_Part(self, value):
603 lhs, rhs = value.value, value.offset
604 if value.stride != 1:
605 rhs *= value.stride
606 lhs_bits, lhs_sign = lhs.shape()
607 rhs_bits, rhs_sign = rhs.shape()
608 res_bits, res_sign = value.shape()
609 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
610 # Note: Verilog's x[o+:w] construct produces a $shiftx cell, not a $shift cell.
611 # However, nMigen's semantics defines the out-of-range bits to be zero, so it is correct
612 # to use a $shift cell here instead, even though it produces less idiomatic Verilog.
613 self.s.rtlil.cell("$shift", ports={
614 "\\A": self(lhs),
615 "\\B": self(rhs),
616 "\\Y": res,
617 }, params={
618 "A_SIGNED": lhs_sign,
619 "A_WIDTH": lhs_bits,
620 "B_SIGNED": rhs_sign,
621 "B_WIDTH": rhs_bits,
622 "Y_WIDTH": res_bits,
623 }, src=_src(value.src_loc))
624 return res
625
626 def on_Repl(self, value):
627 return "{{ {} }}".format(" ".join(self(value.value) for _ in range(value.count)))
628
629
630 class _LHSValueCompiler(_ValueCompiler):
631 def on_Const(self, value):
632 raise TypeError # :nocov:
633
634 def on_AnyConst(self, value):
635 raise TypeError # :nocov:
636
637 def on_AnySeq(self, value):
638 raise TypeError # :nocov:
639
640 def on_Operator(self, value):
641 raise TypeError # :nocov:
642
643 def match_shape(self, value, new_bits, new_sign):
644 value_bits, value_sign = value.shape()
645 if new_bits == value_bits:
646 return self(value)
647 elif new_bits < value_bits:
648 return self(ast.Slice(value, 0, new_bits))
649 else: # new_bits > value_bits
650 dummy_bits = new_bits - value_bits
651 dummy_wire = self.s.rtlil.wire(dummy_bits)
652 return "{{ {} {} }}".format(dummy_wire, self(value))
653
654 def on_Signal(self, value):
655 if value not in self.s.driven:
656 raise ValueError("No LHS wire for non-driven signal {}".format(repr(value)))
657 wire_curr, wire_next = self.s.resolve(value)
658 return wire_next or wire_curr
659
660 def _prepare_value_for_Slice(self, value):
661 assert isinstance(value, (ast.Signal, ast.Slice, ast.Cat))
662 return self(value)
663
664 def on_Part(self, value):
665 offset = self.s.expand(value.offset)
666 if isinstance(offset, ast.Const):
667 start = offset.value * value.stride
668 stop = start + value.width
669 slice = self(ast.Slice(value.value, start, min(len(value.value), stop)))
670 if len(value.value) >= stop:
671 return slice
672 else:
673 dummy_wire = self.s.rtlil.wire(stop - len(value.value))
674 return "{{ {} {} }}".format(dummy_wire, slice)
675 else:
676 # Only so many possible parts. The amount of branches is exponential; if value.offset
677 # is large (e.g. 32-bit wide), trying to naively legalize it is likely to exhaust
678 # system resources.
679 max_branches = len(value.value) // value.stride + 1
680 raise _LegalizeValue(value.offset,
681 range(1 << len(value.offset))[:max_branches],
682 value.src_loc)
683
684 def on_Repl(self, value):
685 raise TypeError # :nocov:
686
687
688 class _StatementCompiler(xfrm.StatementVisitor):
689 def __init__(self, state, rhs_compiler, lhs_compiler):
690 self.state = state
691 self.rhs_compiler = rhs_compiler
692 self.lhs_compiler = lhs_compiler
693
694 self._case = None
695 self._test_cache = {}
696 self._has_rhs = False
697 self._wrap_assign = False
698
699 @contextmanager
700 def case(self, switch, values, attrs={}, src=""):
701 try:
702 old_case = self._case
703 with switch.case(*values, attrs=attrs, src=src) as self._case:
704 yield
705 finally:
706 self._case = old_case
707
708 def _check_rhs(self, value):
709 if self._has_rhs or next(iter(value._rhs_signals()), None) is not None:
710 self._has_rhs = True
711
712 def on_Assign(self, stmt):
713 self._check_rhs(stmt.rhs)
714
715 lhs_bits, lhs_sign = stmt.lhs.shape()
716 rhs_bits, rhs_sign = stmt.rhs.shape()
717 if lhs_bits == rhs_bits:
718 rhs_sigspec = self.rhs_compiler(stmt.rhs)
719 else:
720 # In RTLIL, LHS and RHS of assignment must have exactly same width.
721 rhs_sigspec = self.rhs_compiler.match_shape(
722 stmt.rhs, lhs_bits, lhs_sign)
723 if self._wrap_assign:
724 # In RTLIL, all assigns are logically sequenced before all switches, even if they are
725 # interleaved in the source. In nMigen, the source ordering is used. To handle this
726 # mismatch, we wrap all assigns following a switch in a dummy switch.
727 with self._case.switch("{ }") as wrap_switch:
728 with wrap_switch.case() as wrap_case:
729 wrap_case.assign(self.lhs_compiler(stmt.lhs), rhs_sigspec)
730 else:
731 self._case.assign(self.lhs_compiler(stmt.lhs), rhs_sigspec)
732
733 def on_property(self, stmt):
734 self(stmt._check.eq(stmt.test))
735 self(stmt._en.eq(1))
736
737 en_wire = self.rhs_compiler(stmt._en)
738 check_wire = self.rhs_compiler(stmt._check)
739 self.state.rtlil.cell("$" + stmt._kind, ports={
740 "\\A": check_wire,
741 "\\EN": en_wire,
742 }, src=_src(stmt.src_loc))
743
744 on_Assert = on_property
745 on_Assume = on_property
746 on_Cover = on_property
747
748 def on_Switch(self, stmt):
749 self._check_rhs(stmt.test)
750
751 if not self.state.expansions:
752 # We repeatedly translate the same switches over and over (see the LHSGroupAnalyzer
753 # related code below), and translating the switch test only once helps readability.
754 if stmt not in self._test_cache:
755 self._test_cache[stmt] = self.rhs_compiler(stmt.test)
756 test_sigspec = self._test_cache[stmt]
757 else:
758 # However, if the switch test contains an illegal value, then it may not be cached
759 # (since the illegal value will be repeatedly replaced with different constants), so
760 # don't cache anything in that case.
761 test_sigspec = self.rhs_compiler(stmt.test)
762
763 with self._case.switch(test_sigspec, src=_src(stmt.src_loc)) as switch:
764 for values, stmts in stmt.cases.items():
765 case_attrs = {}
766 if values in stmt.case_src_locs:
767 case_attrs["src"] = _src(stmt.case_src_locs[values])
768 if isinstance(stmt.test, ast.Signal) and stmt.test.decoder:
769 decoded_values = []
770 for value in values:
771 if "-" in value:
772 decoded_values.append("<multiple>")
773 else:
774 decoded_values.append(stmt.test.decoder(int(value, 2)))
775 case_attrs["nmigen.decoding"] = "|".join(decoded_values)
776 with self.case(switch, values, attrs=case_attrs):
777 self._wrap_assign = False
778 self.on_statements(stmts)
779 self._wrap_assign = True
780
781 def on_statement(self, stmt):
782 try:
783 super().on_statement(stmt)
784 except _LegalizeValue as legalize:
785 with self._case.switch(self.rhs_compiler(legalize.value),
786 src=_src(legalize.src_loc)) as switch:
787 shape = legalize.value.shape()
788 tests = ["{:0{}b}".format(v, shape.width) for v in legalize.branches]
789 if tests:
790 tests[-1] = "-" * shape.width
791 for branch, test in zip(legalize.branches, tests):
792 with self.case(switch, (test,)):
793 self._wrap_assign = False
794 branch_value = ast.Const(branch, shape)
795 with self.state.expand_to(legalize.value, branch_value):
796 self.on_statement(stmt)
797 self._wrap_assign = True
798
799 def on_statements(self, stmts):
800 for stmt in stmts:
801 self.on_statement(stmt)
802
803
804 def _convert_fragment(builder, fragment, name_map, hierarchy):
805 if isinstance(fragment, ir.Instance):
806 port_map = OrderedDict()
807 for port_name, (value, dir) in fragment.named_ports.items():
808 port_map["\\{}".format(port_name)] = value
809
810 if fragment.type[0] == "$":
811 return fragment.type, port_map
812 else:
813 return "\\{}".format(fragment.type), port_map
814
815 module_name = hierarchy[-1] or "anonymous"
816 module_attrs = OrderedDict()
817 if len(hierarchy) == 1:
818 module_attrs["top"] = 1
819 module_attrs["nmigen.hierarchy"] = ".".join(name or "anonymous" for name in hierarchy)
820
821 with builder.module(module_name, attrs=module_attrs) as module:
822 compiler_state = _ValueCompilerState(module)
823 rhs_compiler = _RHSValueCompiler(compiler_state)
824 lhs_compiler = _LHSValueCompiler(compiler_state)
825 stmt_compiler = _StatementCompiler(compiler_state, rhs_compiler, lhs_compiler)
826
827 verilog_trigger = None
828 verilog_trigger_sync_emitted = False
829
830 # If the fragment is completely empty, add a dummy wire to it, or Yosys will interpret
831 # it as a black box by default (when read as Verilog).
832 if not fragment.ports and not fragment.statements and not fragment.subfragments:
833 module.wire(1, name="$empty_module_filler")
834
835 # Register all signals driven in the current fragment. This must be done first, as it
836 # affects further codegen; e.g. whether \sig$next signals will be generated and used.
837 for domain, signal in fragment.iter_drivers():
838 compiler_state.add_driven(signal, sync=domain is not None)
839
840 # Transform all signals used as ports in the current fragment eagerly and outside of
841 # any hierarchy, to make sure they get sensible (non-prefixed) names.
842 for signal in fragment.ports:
843 compiler_state.add_port(signal, fragment.ports[signal])
844 compiler_state.resolve_curr(signal)
845
846 # Transform all clocks clocks and resets eagerly and outside of any hierarchy, to make
847 # sure they get sensible (non-prefixed) names. This does not affect semantics.
848 for domain, _ in fragment.iter_sync():
849 cd = fragment.domains[domain]
850 compiler_state.resolve_curr(cd.clk)
851 if cd.rst is not None:
852 compiler_state.resolve_curr(cd.rst)
853
854 # Transform all subfragments to their respective cells. Transforming signals connected
855 # to their ports into wires eagerly makes sure they get sensible (prefixed with submodule
856 # name) names.
857 memories = OrderedDict()
858 for subfragment, sub_name in fragment.subfragments:
859 if sub_name is None:
860 sub_name = module.anonymous()
861
862 sub_params = OrderedDict()
863 if hasattr(subfragment, "parameters"):
864 for param_name, param_value in subfragment.parameters.items():
865 if isinstance(param_value, mem.Memory):
866 memory = param_value
867 if memory not in memories:
868 memories[memory] = module.memory(width=memory.width, size=memory.depth,
869 name=memory.name, attrs=memory.attrs)
870 addr_bits = bits_for(memory.depth)
871 data_parts = []
872 data_mask = (1 << memory.width) - 1
873 for addr in range(memory.depth):
874 if addr < len(memory.init):
875 data = memory.init[addr] & data_mask
876 else:
877 data = 0
878 data_parts.append("{:0{}b}".format(data, memory.width))
879 module.cell("$meminit", ports={
880 "\\ADDR": rhs_compiler(ast.Const(0, addr_bits)),
881 "\\DATA": "{}'".format(memory.width * memory.depth) +
882 "".join(reversed(data_parts)),
883 }, params={
884 "MEMID": memories[memory],
885 "ABITS": addr_bits,
886 "WIDTH": memory.width,
887 "WORDS": memory.depth,
888 "PRIORITY": 0,
889 })
890
891 param_value = memories[memory]
892
893 sub_params[param_name] = param_value
894
895 sub_type, sub_port_map = \
896 _convert_fragment(builder, subfragment, name_map,
897 hierarchy=hierarchy + (sub_name,))
898
899 sub_ports = OrderedDict()
900 for port, value in sub_port_map.items():
901 if not isinstance(subfragment, ir.Instance):
902 for signal in value._rhs_signals():
903 compiler_state.resolve_curr(signal, prefix=sub_name)
904 if len(value) > 0:
905 sub_ports[port] = rhs_compiler(value)
906
907 module.cell(sub_type, name=sub_name, ports=sub_ports, params=sub_params,
908 attrs=subfragment.attrs)
909
910 # If we emit all of our combinatorial logic into a single RTLIL process, Verilog
911 # simulators will break horribly, because Yosys write_verilog transforms RTLIL processes
912 # into always @* blocks with blocking assignment, and that does not create delta cycles.
913 #
914 # Therefore, we translate the fragment as many times as there are independent groups
915 # of signals (a group is a transitive closure of signals that appear together on LHS),
916 # splitting them into many RTLIL (and thus Verilog) processes.
917 lhs_grouper = xfrm.LHSGroupAnalyzer()
918 lhs_grouper.on_statements(fragment.statements)
919
920 for group, group_signals in lhs_grouper.groups().items():
921 lhs_group_filter = xfrm.LHSGroupFilter(group_signals)
922 group_stmts = lhs_group_filter(fragment.statements)
923
924 with module.process(name="$group_{}".format(group)) as process:
925 with process.case() as case:
926 # For every signal in comb domain, assign \sig$next to the reset value.
927 # For every signal in sync domains, assign \sig$next to the current
928 # value (\sig).
929 for domain, signal in fragment.iter_drivers():
930 if signal not in group_signals:
931 continue
932 if domain is None:
933 prev_value = ast.Const(signal.reset, signal.width)
934 else:
935 prev_value = signal
936 case.assign(lhs_compiler(signal), rhs_compiler(prev_value))
937
938 # Convert statements into decision trees.
939 stmt_compiler._case = case
940 stmt_compiler._has_rhs = False
941 stmt_compiler._wrap_assign = False
942 stmt_compiler(group_stmts)
943
944 # Verilog `always @*` blocks will not run if `*` does not match anything, i.e.
945 # if the implicit sensitivity list is empty. We check this while translating,
946 # by looking for any signals on RHS. If there aren't any, we add some logic
947 # whose only purpose is to trigger Verilog simulators when it converts
948 # through RTLIL and to Verilog, by populating the sensitivity list.
949 #
950 # Unfortunately, while this workaround allows true (event-driven) Verilog
951 # simulators to work properly, and is universally ignored by synthesizers,
952 # Verilator rejects it.
953 #
954 # Yosys >=0.9+3468 emits a better workaround on its own, so this code can be
955 # removed completely once support for Yosys 0.9 is dropped.
956 if not stmt_compiler._has_rhs:
957 if verilog_trigger is None:
958 verilog_trigger = \
959 module.wire(1, name="$verilog_initial_trigger")
960 case.assign(verilog_trigger, verilog_trigger)
961
962 # For every signal in the sync domain, assign \sig's initial value (which will
963 # end up as the \init reg attribute) to the reset value.
964 with process.sync("init") as sync:
965 for domain, signal in fragment.iter_sync():
966 if signal not in group_signals:
967 continue
968 wire_curr, wire_next = compiler_state.resolve(signal)
969 sync.update(wire_curr, rhs_compiler(ast.Const(signal.reset, signal.width)))
970
971 # The Verilog simulator trigger needs to change at time 0, so if we haven't
972 # yet done that in some process, do it.
973 if verilog_trigger and not verilog_trigger_sync_emitted:
974 sync.update(verilog_trigger, "1'0")
975 verilog_trigger_sync_emitted = True
976
977 # For every signal in every sync domain, assign \sig to \sig$next. The sensitivity
978 # list, however, differs between domains: for domains with sync reset, it is
979 # `[pos|neg]edge clk`, for sync domains with async reset it is `[pos|neg]edge clk
980 # or posedge rst`.
981 for domain, signals in fragment.drivers.items():
982 if domain is None:
983 continue
984
985 signals = signals & group_signals
986 if not signals:
987 continue
988
989 cd = fragment.domains[domain]
990
991 triggers = []
992 triggers.append((cd.clk_edge + "edge", compiler_state.resolve_curr(cd.clk)))
993 if cd.async_reset:
994 triggers.append(("posedge", compiler_state.resolve_curr(cd.rst)))
995
996 for trigger in triggers:
997 with process.sync(*trigger) as sync:
998 for signal in signals:
999 wire_curr, wire_next = compiler_state.resolve(signal)
1000 sync.update(wire_curr, wire_next)
1001
1002 # Any signals that are used but neither driven nor connected to an input port always
1003 # assume their reset values. We need to assign the reset value explicitly, since only
1004 # driven sync signals are handled by the logic above.
1005 #
1006 # Because this assignment is done at a late stage, a single Signal object can get assigned
1007 # many times, once in each module it is used. This is a deliberate decision; the possible
1008 # alternatives are to add ports for undriven signals (which requires choosing one module
1009 # to drive it to reset value arbitrarily) or to replace them with their reset value (which
1010 # removes valuable source location information).
1011 driven = ast.SignalSet()
1012 for domain, signals in fragment.iter_drivers():
1013 driven.update(flatten(signal._lhs_signals() for signal in signals))
1014 driven.update(fragment.iter_ports(dir="i"))
1015 driven.update(fragment.iter_ports(dir="io"))
1016 for subfragment, sub_name in fragment.subfragments:
1017 driven.update(subfragment.iter_ports(dir="o"))
1018 driven.update(subfragment.iter_ports(dir="io"))
1019
1020 for wire in compiler_state.wires:
1021 if wire in driven:
1022 continue
1023 wire_curr, _ = compiler_state.wires[wire]
1024 module.connect(wire_curr, rhs_compiler(ast.Const(wire.reset, wire.width)))
1025
1026 # Collect the names we've given to our ports in RTLIL, and correlate these with the signals
1027 # represented by these ports. If we are a submodule, this will be necessary to create a cell
1028 # for us in the parent module.
1029 port_map = OrderedDict()
1030 for signal in fragment.ports:
1031 port_map[compiler_state.resolve_curr(signal)] = signal
1032
1033 # Finally, collect tha names we've given to each wire in RTLIL, and provide these to
1034 # the caller, to allow manipulating them in the toolchain.
1035 for signal in compiler_state.wires:
1036 wire_name = compiler_state.resolve_curr(signal)
1037 if wire_name.startswith("\\"):
1038 wire_name = wire_name[1:]
1039 name_map[signal] = hierarchy + (wire_name,)
1040
1041 return module.name, port_map
1042
1043
1044 def convert_fragment(fragment, name="top"):
1045 assert isinstance(fragment, ir.Fragment)
1046 builder = _Builder()
1047 name_map = ast.SignalDict()
1048 _convert_fragment(builder, fragment, name_map, hierarchy=(name,))
1049 return str(builder), name_map
1050
1051
1052 def convert(elaboratable, name="top", platform=None, **kwargs):
1053 fragment = ir.Fragment.get(elaboratable, platform).prepare(**kwargs)
1054 il_text, name_map = convert_fragment(fragment, name)
1055 return il_text