back.rtlil: mask memory init values.
[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 _Bufferer:
33 _escape_map = str.maketrans({
34 "\"": "\\\"",
35 "\\": "\\\\",
36 "\t": "\\t",
37 "\r": "\\r",
38 "\n": "\\n",
39 })
40 def __init__(self):
41 super().__init__()
42 self._buffer = io.StringIO()
43
44 def __str__(self):
45 return self._buffer.getvalue()
46
47 def _append(self, fmt, *args, **kwargs):
48 self._buffer.write(fmt.format(*args, **kwargs))
49
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))
54 else:
55 self._append("{}attribute \\{} {}\n",
56 " " * indent, name, int(value))
57
58 def _src(self, src):
59 if src:
60 self.attribute("src", src)
61
62
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)
67
68
69 class _ModuleBuilder(_Namer, _Bufferer):
70 def __init__(self, rtlil, name, attrs):
71 super().__init__()
72 self.rtlil = rtlil
73 self.name = name
74 self.attrs = {"generator": "nMigen"}
75 self.attrs.update(attrs)
76
77 def __enter__(self):
78 for name, value in self.attrs.items():
79 self.attribute(name, value, indent=0)
80 self._append("module {}\n", self.name)
81 return self
82
83 def __exit__(self, *args):
84 self._append("end\n")
85 self.rtlil._buffer.write(str(self))
86
87 def attribute(self, name, value, indent=1):
88 super().attribute(name, value, indent)
89
90 def wire(self, width, port_id=None, port_kind=None, name=None, src=""):
91 self._src(src)
92 name = self._make_name(name, local=False)
93 if port_id is None:
94 self._append(" wire width {} {}\n", width, name)
95 else:
96 assert port_kind in ("input", "output", "inout")
97 self._append(" wire width {} {} {} {}\n", width, port_kind, port_id, name)
98 return name
99
100 def connect(self, lhs, rhs):
101 self._append(" connect {} {}\n", lhs, rhs)
102
103 def memory(self, width, size, name=None, src=""):
104 self._src(src)
105 name = self._make_name(name, local=False)
106 self._append(" memory width {} size {} {}\n", width, size, name)
107 return name
108
109 def cell(self, kind, name=None, params={}, ports={}, src=""):
110 self._src(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",
119 param, value)
120 elif isinstance(value, ast.Const):
121 self._append(" parameter \\{} {}'{:b}\n",
122 param, len(value), value.value)
123 else:
124 assert False
125 for port, wire in ports.items():
126 self._append(" connect {} {}\n", port, wire)
127 self._append(" end\n")
128 return name
129
130 def process(self, name=None, src=""):
131 name = self._make_name(name, local=True)
132 return _ProcessBuilder(self, name, src)
133
134
135 class _ProcessBuilder(_Bufferer):
136 def __init__(self, rtlil, name, src):
137 super().__init__()
138 self.rtlil = rtlil
139 self.name = name
140 self.src = src
141
142 def __enter__(self):
143 self._src(self.src)
144 self._append(" process {}\n", self.name)
145 return self
146
147 def __exit__(self, *args):
148 self._append(" end\n")
149 self.rtlil._buffer.write(str(self))
150
151 def case(self):
152 return _CaseBuilder(self, indent=2)
153
154 def sync(self, kind, cond=None):
155 return _SyncBuilder(self, kind, cond)
156
157
158 class _CaseBuilder:
159 def __init__(self, rtlil, indent):
160 self.rtlil = rtlil
161 self.indent = indent
162
163 def __enter__(self):
164 return self
165
166 def __exit__(self, *args):
167 pass
168
169 def assign(self, lhs, rhs):
170 self.rtlil._append("{}assign {} {}\n", " " * self.indent, lhs, rhs)
171
172 def switch(self, cond):
173 return _SwitchBuilder(self.rtlil, cond, self.indent)
174
175
176 class _SwitchBuilder:
177 def __init__(self, rtlil, cond, indent):
178 self.rtlil = rtlil
179 self.cond = cond
180 self.indent = indent
181
182 def __enter__(self):
183 self.rtlil._append("{}switch {}\n", " " * self.indent, self.cond)
184 return self
185
186 def __exit__(self, *args):
187 self.rtlil._append("{}end\n", " " * self.indent)
188
189 def case(self, value=None):
190 if value is None:
191 self.rtlil._append("{}case\n", " " * (self.indent + 1))
192 else:
193 self.rtlil._append("{}case {}'{}\n", " " * (self.indent + 1),
194 len(value), value)
195 return _CaseBuilder(self.rtlil, self.indent + 2)
196
197
198 class _SyncBuilder:
199 def __init__(self, rtlil, kind, cond):
200 self.rtlil = rtlil
201 self.kind = kind
202 self.cond = cond
203
204 def __enter__(self):
205 if self.cond is None:
206 self.rtlil._append(" sync {}\n", self.kind)
207 else:
208 self.rtlil._append(" sync {} {}\n", self.kind, self.cond)
209 return self
210
211 def __exit__(self, *args):
212 pass
213
214 def update(self, lhs, rhs):
215 self.rtlil._append(" update {} {}\n", lhs, rhs)
216
217
218 def src(src_loc):
219 file, line = src_loc
220 return "{}:{}".format(file, line)
221
222
223 class LegalizeValue(Exception):
224 def __init__(self, value, branches):
225 self.value = value
226 self.branches = list(branches)
227
228
229 class _ValueCompilerState:
230 def __init__(self, rtlil):
231 self.rtlil = rtlil
232 self.wires = ast.SignalDict()
233 self.driven = ast.SignalDict()
234 self.ports = ast.SignalDict()
235 self.anys = ast.ValueDict()
236
237 self.expansions = ast.ValueDict()
238
239 def add_driven(self, signal, sync):
240 self.driven[signal] = sync
241
242 def add_port(self, signal, kind):
243 assert kind in ("i", "o", "io")
244 if kind == "i":
245 kind = "input"
246 elif kind == "o":
247 kind = "output"
248 elif kind == "io":
249 kind = "inout"
250 self.ports[signal] = (len(self.ports), kind)
251
252 def resolve(self, signal, prefix=None):
253 if signal in self.wires:
254 return self.wires[signal]
255
256 if signal in self.ports:
257 port_id, port_kind = self.ports[signal]
258 else:
259 port_id = port_kind = None
260 if prefix is not None:
261 wire_name = "{}_{}".format(prefix, signal.name)
262 else:
263 wire_name = signal.name
264
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))
273 else:
274 wire_next = None
275 self.wires[signal] = (wire_curr, wire_next)
276
277 return wire_curr, wire_next
278
279 def resolve_curr(self, signal, prefix=None):
280 wire_curr, wire_next = self.resolve(signal, prefix)
281 return wire_curr
282
283 def expand(self, value):
284 if not self.expansions:
285 return value
286 return self.expansions.get(value, value)
287
288 @contextmanager
289 def expand_to(self, value, expansion):
290 try:
291 assert value not in self.expansions
292 self.expansions[value] = expansion
293 yield
294 finally:
295 del self.expansions[value]
296
297
298 class _ValueCompiler(xfrm.ValueVisitor):
299 def __init__(self, state):
300 self.s = state
301
302 def on_unknown(self, value):
303 if value is None:
304 return None
305 else:
306 super().on_unknown(value)
307
308 def on_ClockSignal(self, value):
309 raise NotImplementedError # :nocov:
310
311 def on_ResetSignal(self, value):
312 raise NotImplementedError # :nocov:
313
314 def on_Sample(self, value):
315 raise NotImplementedError # :nocov:
316
317 def on_Record(self, value):
318 return self(ast.Cat(value.fields.values()))
319
320 def on_Cat(self, value):
321 return "{{ {} }}".format(" ".join(reversed([self(o) for o in value.parts])))
322
323 def _prepare_value_for_Slice(self, value):
324 raise NotImplementedError # :nocov:
325
326 def on_Slice(self, value):
327 if value.start == 0 and value.end == len(value.value):
328 return self(value.value)
329
330 sigspec = self._prepare_value_for_Slice(value.value)
331 if value.start == value.end:
332 return "{}"
333 elif value.start + 1 == value.end:
334 return "{} [{}]".format(sigspec, value.start)
335 else:
336 return "{} [{}:{}]".format(sigspec, value.end - 1, value.start)
337
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]
343 else:
344 elem = value.elems[-1]
345 return self.match_shape(elem, *value.shape())
346 else:
347 raise LegalizeValue(value.index, range(len(value.elems)))
348
349
350 class _RHSValueCompiler(_ValueCompiler):
351 operator_map = {
352 (1, "~"): "$not",
353 (1, "-"): "$neg",
354 (1, "b"): "$reduce_bool",
355 (2, "+"): "$add",
356 (2, "-"): "$sub",
357 (2, "*"): "$mul",
358 (2, "/"): "$div",
359 (2, "%"): "$mod",
360 (2, "**"): "$pow",
361 (2, "<<"): "$sshl",
362 (2, ">>"): "$sshr",
363 (2, "&"): "$and",
364 (2, "^"): "$xor",
365 (2, "|"): "$or",
366 (2, "=="): "$eq",
367 (2, "!="): "$ne",
368 (2, "<"): "$lt",
369 (2, "<="): "$le",
370 (2, ">"): "$gt",
371 (2, ">="): "$ge",
372 (3, "m"): "$mux",
373 }
374
375 def on_value(self, value):
376 return super().on_value(self.s.expand(value))
377
378 def on_Const(self, value):
379 if isinstance(value.value, str):
380 return "{}'{}".format(value.nbits, value.value)
381 else:
382 value_twos_compl = value.value & ((1 << value.nbits) - 1)
383 return "{}'{:0{}b}".format(value.nbits, value_twos_compl, value.nbits)
384
385 def on_AnyConst(self, value):
386 if value in self.s.anys:
387 return self.s.anys[value]
388
389 res_bits, res_sign = value.shape()
390 res = self.s.rtlil.wire(width=res_bits)
391 self.s.rtlil.cell("$anyconst", ports={
392 "\\Y": res,
393 }, params={
394 "WIDTH": res_bits,
395 }, src=src(value.src_loc))
396 self.s.anys[value] = res
397 return res
398
399 def on_AnySeq(self, value):
400 if value in self.s.anys:
401 return self.s.anys[value]
402
403 res_bits, res_sign = value.shape()
404 res = self.s.rtlil.wire(width=res_bits)
405 self.s.rtlil.cell("$anyseq", ports={
406 "\\Y": res,
407 }, params={
408 "WIDTH": res_bits,
409 }, src=src(value.src_loc))
410 self.s.anys[value] = res
411 return res
412
413 def on_Signal(self, value):
414 wire_curr, wire_next = self.s.resolve(value)
415 return wire_curr
416
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={
423 "\\A": self(arg),
424 "\\Y": res,
425 }, params={
426 "A_SIGNED": arg_sign,
427 "A_WIDTH": arg_bits,
428 "Y_WIDTH": res_bits,
429 }, src=src(value.src_loc))
430 return res
431
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)))
435
436 value_bits, value_sign = value.shape()
437 if new_bits <= value_bits:
438 return self(ast.Slice(value, 0, new_bits))
439
440 res = self.s.rtlil.wire(width=new_bits)
441 self.s.rtlil.cell("$pos", ports={
442 "\\A": self(value),
443 "\\Y": res,
444 }, params={
445 "A_SIGNED": value_sign,
446 "A_WIDTH": value_bits,
447 "Y_WIDTH": new_bits,
448 }, src=src(value.src_loc))
449 return res
450
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:
456 lhs_wire = self(lhs)
457 rhs_wire = self(rhs)
458 else:
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={
466 "\\A": lhs_wire,
467 "\\B": rhs_wire,
468 "\\Y": res,
469 }, params={
470 "A_SIGNED": lhs_sign,
471 "A_WIDTH": lhs_bits,
472 "B_SIGNED": rhs_sign,
473 "B_WIDTH": rhs_bits,
474 "Y_WIDTH": res_bits,
475 }, src=src(value.src_loc))
476 return res
477
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={
488 "\\A": val0_wire,
489 "\\B": val1_wire,
490 "\\S": self(sel),
491 "\\Y": res,
492 }, params={
493 "WIDTH": res_bits
494 }, src=src(value.src_loc))
495 return res
496
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)
505 else:
506 raise TypeError # :nocov:
507
508 def _prepare_value_for_Slice(self, value):
509 if isinstance(value, (ast.Signal, ast.Slice, ast.Cat)):
510 sigspec = self(value)
511 else:
512 sigspec = self.s.rtlil.wire(len(value))
513 self.s.rtlil.connect(sigspec, self(value))
514 return sigspec
515
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={
526 "\\A": self(lhs),
527 "\\B": self(rhs),
528 "\\Y": res,
529 }, params={
530 "A_SIGNED": lhs_sign,
531 "A_WIDTH": lhs_bits,
532 "B_SIGNED": rhs_sign,
533 "B_WIDTH": rhs_bits,
534 "Y_WIDTH": res_bits,
535 }, src=src(value.src_loc))
536 return res
537
538 def on_Repl(self, value):
539 return "{{ {} }}".format(" ".join(self(value.value) for _ in range(value.count)))
540
541
542 class _LHSValueCompiler(_ValueCompiler):
543 def on_Const(self, value):
544 raise TypeError # :nocov:
545
546 def on_AnyConst(self, value):
547 raise TypeError # :nocov:
548
549 def on_AnySeq(self, value):
550 raise TypeError # :nocov:
551
552 def on_Operator(self, value):
553 raise TypeError # :nocov:
554
555 def match_shape(self, value, new_bits, new_sign):
556 assert value.shape() == (new_bits, new_sign)
557 return self(value)
558
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)))
563 return wire_next
564
565 def _prepare_value_for_Slice(self, value):
566 assert isinstance(value, (ast.Signal, ast.Slice, ast.Cat, rec.Record))
567 return self(value)
568
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))
573 else:
574 raise LegalizeValue(value.offset, range((1 << len(value.offset))))
575
576 def on_Repl(self, value):
577 raise TypeError # :nocov:
578
579
580 class _StatementCompiler(xfrm.StatementVisitor):
581 def __init__(self, state, rhs_compiler, lhs_compiler):
582 self.state = state
583 self.rhs_compiler = rhs_compiler
584 self.lhs_compiler = lhs_compiler
585
586 self._case = None
587 self._test_cache = {}
588 self._has_rhs = False
589
590 @contextmanager
591 def case(self, switch, value):
592 try:
593 old_case = self._case
594 with switch.case(value) as self._case:
595 yield
596 finally:
597 self._case = old_case
598
599 def _check_rhs(self, value):
600 if self._has_rhs or next(iter(value._rhs_signals()), None) is not None:
601 self._has_rhs = True
602
603 def on_Assign(self, stmt):
604 self._check_rhs(stmt.rhs)
605
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)
610 else:
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)
615
616 def on_Assert(self, stmt):
617 self(stmt._check.eq(stmt.test))
618 self(stmt._en.eq(1))
619
620 en_wire = self.rhs_compiler(stmt._en)
621 check_wire = self.rhs_compiler(stmt._check)
622 self.state.rtlil.cell("$assert", ports={
623 "\\A": check_wire,
624 "\\EN": en_wire,
625 }, src=src(stmt.src_loc))
626
627 def on_Assume(self, stmt):
628 self(stmt._check.eq(stmt.test))
629 self(stmt._en.eq(1))
630
631 en_wire = self.rhs_compiler(stmt._en)
632 check_wire = self.rhs_compiler(stmt._check)
633 self.state.rtlil.cell("$assume", ports={
634 "\\A": check_wire,
635 "\\EN": en_wire,
636 }, src=src(stmt.src_loc))
637
638 def on_Switch(self, stmt):
639 self._check_rhs(stmt.test)
640
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]
644
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)
649
650 def on_statement(self, stmt):
651 try:
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)
663
664 def on_statements(self, stmts):
665 for stmt in stmts:
666 self.on_statement(stmt)
667
668
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
674
675 if fragment.type[0] == "$":
676 return fragment.type, port_map
677 else:
678 return "\\{}".format(fragment.type), port_map
679
680 module_name = hierarchy[-1] or "anonymous"
681 module_attrs = {}
682 if len(hierarchy) == 1:
683 module_attrs["top"] = 1
684 module_attrs["nmigen.hierarchy"] = ".".join(name or "anonymous" for name in hierarchy)
685
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)
691
692 verilog_trigger = None
693 verilog_trigger_sync_emitted = False
694
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)
699
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)
705
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)
713
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
716 # name) names.
717 memories = OrderedDict()
718 for subfragment, sub_name in fragment.subfragments:
719 if not subfragment.ports:
720 continue
721
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):
726 memory = param_value
727 if memory not in memories:
728 memories[memory] = module.memory(width=memory.width, size=memory.depth,
729 name=memory.name)
730 addr_bits = bits_for(memory.depth)
731 data_parts = []
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
736 else:
737 data = 0
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)),
743 }, params={
744 "MEMID": memories[memory],
745 "ABITS": addr_bits,
746 "WIDTH": memory.width,
747 "WORDS": memory.depth,
748 "PRIORITY": 0,
749 })
750
751 param_value = memories[memory]
752
753 sub_params[param_name] = param_value
754
755 sub_type, sub_port_map = \
756 convert_fragment(builder, subfragment, hierarchy=hierarchy + (sub_name,))
757
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)
763
764 module.cell(sub_type, name=sub_name, ports=sub_ports, params=sub_params)
765
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.
769 #
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)
775
776 for group, group_signals in lhs_grouper.groups().items():
777 lhs_group_filter = xfrm.LHSGroupFilter(group_signals)
778
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
783 # value (\sig).
784 for domain, signal in fragment.iter_drivers():
785 if signal not in group_signals:
786 continue
787 if domain is None:
788 prev_value = ast.Const(signal.reset, signal.nbits)
789 else:
790 prev_value = signal
791 case.assign(lhs_compiler(signal), rhs_compiler(prev_value))
792
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))
797
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:
805 verilog_trigger = \
806 module.wire(1, name="$verilog_initial_trigger")
807 case.assign(verilog_trigger, verilog_trigger)
808
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:
814 continue
815 wire_curr, wire_next = compiler_state.resolve(signal)
816 sync.update(wire_curr, rhs_compiler(ast.Const(signal.reset, signal.nbits)))
817
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
823
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
830 if not signals:
831 continue
832
833 triggers = []
834 if domain is None:
835 triggers.append(("always",))
836 else:
837 cd = fragment.domains[domain]
838 triggers.append(("posedge", compiler_state.resolve_curr(cd.clk)))
839 if cd.async_reset:
840 triggers.append(("posedge", compiler_state.resolve_curr(cd.rst)))
841
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)
847
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.
851 #
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"))
865
866 for wire in compiler_state.wires:
867 if wire in driven:
868 continue
869 wire_curr, _ = compiler_state.wires[wire]
870 module.connect(wire_curr, rhs_compiler(ast.Const(wire.reset, wire.nbits)))
871
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
878
879 return module.name, port_map
880
881
882 def convert(fragment, name="top", platform=None, **kwargs):
883 fragment = ir.Fragment.get(fragment, platform).prepare(**kwargs)
884 builder = _Builder()
885 convert_fragment(builder, fragment, hierarchy=(name,))
886 return str(builder)