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