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