Merge pull request #2480 from YosysHQ/dave/nexus-lram
[yosys.git] / backends / cxxrtl / cxxrtl_backend.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2019-2020 whitequark <whitequark@whitequark.org>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/utils.h"
24 #include "kernel/celltypes.h"
25 #include "kernel/mem.h"
26 #include "kernel/log.h"
27
28 USING_YOSYS_NAMESPACE
29 PRIVATE_NAMESPACE_BEGIN
30
31 // [[CITE]]
32 // Peter Eades; Xuemin Lin; W. F. Smyth, "A Fast Effective Heuristic For The Feedback Arc Set Problem"
33 // Information Processing Letters, Vol. 47, pp 319-323, 1993
34 // https://pdfs.semanticscholar.org/c7ed/d9acce96ca357876540e19664eb9d976637f.pdf
35
36 // A topological sort (on a cell/wire graph) is always possible in a fully flattened RTLIL design without
37 // processes or logic loops where every wire has a single driver. Logic loops are illegal in RTLIL and wires
38 // with multiple drivers can be split by the `splitnets` pass; however, interdependencies between processes
39 // or module instances can create strongly connected components without introducing evaluation nondeterminism.
40 // We wish to support designs with such benign SCCs (as well as designs with multiple drivers per wire), so
41 // we sort the graph in a way that minimizes feedback arcs. If there are no feedback arcs in the sorted graph,
42 // then a more efficient evaluation method is possible, since eval() will always immediately converge.
43 template<class T>
44 struct Scheduler {
45 struct Vertex {
46 T *data;
47 Vertex *prev, *next;
48 pool<Vertex*, hash_ptr_ops> preds, succs;
49
50 Vertex() : data(NULL), prev(this), next(this) {}
51 Vertex(T *data) : data(data), prev(NULL), next(NULL) {}
52
53 bool empty() const
54 {
55 log_assert(data == NULL);
56 if (next == this) {
57 log_assert(prev == next);
58 return true;
59 }
60 return false;
61 }
62
63 void link(Vertex *list)
64 {
65 log_assert(prev == NULL && next == NULL);
66 next = list;
67 prev = list->prev;
68 list->prev->next = this;
69 list->prev = this;
70 }
71
72 void unlink()
73 {
74 log_assert(prev->next == this && next->prev == this);
75 prev->next = next;
76 next->prev = prev;
77 next = prev = NULL;
78 }
79
80 int delta() const
81 {
82 return succs.size() - preds.size();
83 }
84 };
85
86 std::vector<Vertex*> vertices;
87 Vertex *sources = new Vertex;
88 Vertex *sinks = new Vertex;
89 dict<int, Vertex*> bins;
90
91 ~Scheduler()
92 {
93 delete sources;
94 delete sinks;
95 for (auto bin : bins)
96 delete bin.second;
97 for (auto vertex : vertices)
98 delete vertex;
99 }
100
101 Vertex *add(T *data)
102 {
103 Vertex *vertex = new Vertex(data);
104 vertices.push_back(vertex);
105 return vertex;
106 }
107
108 void relink(Vertex *vertex)
109 {
110 if (vertex->succs.empty())
111 vertex->link(sinks);
112 else if (vertex->preds.empty())
113 vertex->link(sources);
114 else {
115 int delta = vertex->delta();
116 if (!bins.count(delta))
117 bins[delta] = new Vertex;
118 vertex->link(bins[delta]);
119 }
120 }
121
122 Vertex *remove(Vertex *vertex)
123 {
124 vertex->unlink();
125 for (auto pred : vertex->preds) {
126 if (pred == vertex)
127 continue;
128 log_assert(pred->succs[vertex]);
129 pred->unlink();
130 pred->succs.erase(vertex);
131 relink(pred);
132 }
133 for (auto succ : vertex->succs) {
134 if (succ == vertex)
135 continue;
136 log_assert(succ->preds[vertex]);
137 succ->unlink();
138 succ->preds.erase(vertex);
139 relink(succ);
140 }
141 vertex->preds.clear();
142 vertex->succs.clear();
143 return vertex;
144 }
145
146 std::vector<Vertex*> schedule()
147 {
148 std::vector<Vertex*> s1, s2r;
149 for (auto vertex : vertices)
150 relink(vertex);
151 bool bins_empty = false;
152 while (!(sinks->empty() && sources->empty() && bins_empty)) {
153 while (!sinks->empty())
154 s2r.push_back(remove(sinks->next));
155 while (!sources->empty())
156 s1.push_back(remove(sources->next));
157 // Choosing u in this implementation isn't O(1), but the paper handwaves which data structure they suggest
158 // using to get O(1) relinking *and* find-max-key ("it is clear"... no it isn't), so this code uses a very
159 // naive implementation of find-max-key.
160 bins_empty = true;
161 bins.template sort<std::greater<int>>();
162 for (auto bin : bins) {
163 if (!bin.second->empty()) {
164 bins_empty = false;
165 s1.push_back(remove(bin.second->next));
166 break;
167 }
168 }
169 }
170 s1.insert(s1.end(), s2r.rbegin(), s2r.rend());
171 return s1;
172 }
173 };
174
175 bool is_unary_cell(RTLIL::IdString type)
176 {
177 return type.in(
178 ID($not), ID($logic_not), ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool),
179 ID($pos), ID($neg));
180 }
181
182 bool is_binary_cell(RTLIL::IdString type)
183 {
184 return type.in(
185 ID($and), ID($or), ID($xor), ID($xnor), ID($logic_and), ID($logic_or),
186 ID($shl), ID($sshl), ID($shr), ID($sshr), ID($shift), ID($shiftx),
187 ID($eq), ID($ne), ID($eqx), ID($nex), ID($gt), ID($ge), ID($lt), ID($le),
188 ID($add), ID($sub), ID($mul), ID($div), ID($mod));
189 }
190
191 bool is_extending_cell(RTLIL::IdString type)
192 {
193 return !type.in(
194 ID($logic_not), ID($logic_and), ID($logic_or),
195 ID($reduce_and), ID($reduce_or), ID($reduce_xor), ID($reduce_xnor), ID($reduce_bool));
196 }
197
198 bool is_inlinable_cell(RTLIL::IdString type)
199 {
200 return is_unary_cell(type) || is_binary_cell(type) || type.in(
201 ID($mux), ID($concat), ID($slice), ID($pmux));
202 }
203
204 bool is_ff_cell(RTLIL::IdString type)
205 {
206 return type.in(
207 ID($dff), ID($dffe), ID($sdff), ID($sdffe), ID($sdffce),
208 ID($adff), ID($adffe), ID($dffsr), ID($dffsre),
209 ID($dlatch), ID($adlatch), ID($dlatchsr), ID($sr));
210 }
211
212 bool is_internal_cell(RTLIL::IdString type)
213 {
214 return !type.isPublic() && !type.begins_with("$paramod");
215 }
216
217 bool is_effectful_cell(RTLIL::IdString type)
218 {
219 return type == ID($memwr) || type.isPublic();
220 }
221
222 bool is_cxxrtl_blackbox_cell(const RTLIL::Cell *cell)
223 {
224 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
225 log_assert(cell_module != nullptr);
226 return cell_module->get_bool_attribute(ID(cxxrtl_blackbox));
227 }
228
229 enum class CxxrtlPortType {
230 UNKNOWN = 0, // or mixed comb/sync
231 COMB = 1,
232 SYNC = 2,
233 };
234
235 CxxrtlPortType cxxrtl_port_type(RTLIL::Module *module, RTLIL::IdString port)
236 {
237 RTLIL::Wire *output_wire = module->wire(port);
238 log_assert(output_wire != nullptr);
239 bool is_comb = output_wire->get_bool_attribute(ID(cxxrtl_comb));
240 bool is_sync = output_wire->get_bool_attribute(ID(cxxrtl_sync));
241 if (is_comb && is_sync)
242 log_cmd_error("Port `%s.%s' is marked as both `cxxrtl_comb` and `cxxrtl_sync`.\n",
243 log_id(module), log_signal(output_wire));
244 else if (is_comb)
245 return CxxrtlPortType::COMB;
246 else if (is_sync)
247 return CxxrtlPortType::SYNC;
248 return CxxrtlPortType::UNKNOWN;
249 }
250
251 CxxrtlPortType cxxrtl_port_type(const RTLIL::Cell *cell, RTLIL::IdString port)
252 {
253 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
254 if (cell_module == nullptr || !cell_module->get_bool_attribute(ID(cxxrtl_blackbox)))
255 return CxxrtlPortType::UNKNOWN;
256 return cxxrtl_port_type(cell_module, port);
257 }
258
259 bool is_cxxrtl_comb_port(const RTLIL::Cell *cell, RTLIL::IdString port)
260 {
261 return cxxrtl_port_type(cell, port) == CxxrtlPortType::COMB;
262 }
263
264 bool is_cxxrtl_sync_port(const RTLIL::Cell *cell, RTLIL::IdString port)
265 {
266 return cxxrtl_port_type(cell, port) == CxxrtlPortType::SYNC;
267 }
268
269 struct FlowGraph {
270 struct Node {
271 enum class Type {
272 CONNECT,
273 CELL_SYNC,
274 CELL_EVAL,
275 PROCESS_SYNC,
276 PROCESS_CASE,
277 };
278
279 Type type;
280 RTLIL::SigSig connect = {};
281 const RTLIL::Cell *cell = NULL;
282 const RTLIL::Process *process = NULL;
283 };
284
285 std::vector<Node*> nodes;
286 dict<const RTLIL::Wire*, pool<Node*, hash_ptr_ops>> wire_comb_defs, wire_sync_defs, wire_uses;
287 dict<Node*, pool<const RTLIL::Wire*>, hash_ptr_ops> node_comb_defs, node_sync_defs, node_uses;
288 dict<const RTLIL::Wire*, bool> wire_def_inlinable;
289 dict<const RTLIL::Wire*, dict<Node*, bool, hash_ptr_ops>> wire_use_inlinable;
290 dict<RTLIL::SigBit, bool> bit_has_state;
291
292 ~FlowGraph()
293 {
294 for (auto node : nodes)
295 delete node;
296 }
297
298 void add_defs(Node *node, const RTLIL::SigSpec &sig, bool is_ff, bool inlinable)
299 {
300 for (auto chunk : sig.chunks())
301 if (chunk.wire) {
302 if (is_ff) {
303 // A sync def means that a wire holds design state because it is driven directly by
304 // a flip-flop output. Such a wire can never be unbuffered.
305 wire_sync_defs[chunk.wire].insert(node);
306 node_sync_defs[node].insert(chunk.wire);
307 } else {
308 // A comb def means that a wire doesn't hold design state. It might still be connected,
309 // indirectly, to a flip-flop output.
310 wire_comb_defs[chunk.wire].insert(node);
311 node_comb_defs[node].insert(chunk.wire);
312 }
313 }
314 for (auto bit : sig.bits())
315 bit_has_state[bit] |= is_ff;
316 // Only comb defs of an entire wire in the right order can be inlined.
317 if (!is_ff && sig.is_wire())
318 wire_def_inlinable[sig.as_wire()] = inlinable;
319 }
320
321 void add_uses(Node *node, const RTLIL::SigSpec &sig)
322 {
323 for (auto chunk : sig.chunks())
324 if (chunk.wire) {
325 wire_uses[chunk.wire].insert(node);
326 node_uses[node].insert(chunk.wire);
327 // Only a single use of an entire wire in the right order can be inlined. (But the use can include
328 // other chunks.) This is tracked per-node because a wire used by multiple nodes can still be inlined
329 // if all but one of those nodes is dead.
330 if (!wire_use_inlinable[chunk.wire].count(node))
331 wire_use_inlinable[chunk.wire][node] = true;
332 else
333 wire_use_inlinable[chunk.wire][node] = false;
334 }
335 }
336
337 bool is_inlinable(const RTLIL::Wire *wire) const
338 {
339 // Can the wire be inlined at all?
340 if (wire_def_inlinable.count(wire))
341 return wire_def_inlinable.at(wire);
342 return false;
343 }
344
345 bool is_inlinable(const RTLIL::Wire *wire, const pool<Node*, hash_ptr_ops> &nodes) const
346 {
347 // Can the wire be inlined, knowing that the given nodes are reachable?
348 if (nodes.size() != 1)
349 return false;
350 Node *node = *nodes.begin();
351 log_assert(node_uses.at(node).count(wire));
352 if (is_inlinable(wire) && wire_use_inlinable.count(wire) && wire_use_inlinable.at(wire).count(node))
353 return wire_use_inlinable.at(wire).at(node);
354 return false;
355 }
356
357 // Connections
358 void add_connect_defs_uses(Node *node, const RTLIL::SigSig &conn)
359 {
360 add_defs(node, conn.first, /*is_ff=*/false, /*inlinable=*/true);
361 add_uses(node, conn.second);
362 }
363
364 Node *add_node(const RTLIL::SigSig &conn)
365 {
366 Node *node = new Node;
367 node->type = Node::Type::CONNECT;
368 node->connect = conn;
369 nodes.push_back(node);
370 add_connect_defs_uses(node, conn);
371 return node;
372 }
373
374 // Cells
375 void add_cell_sync_defs(Node *node, const RTLIL::Cell *cell)
376 {
377 // To understand why this node type is necessary and why it produces comb defs, consider a cell
378 // with input \i and sync output \o, used in a design such that \i is connected to \o. This does
379 // not result in a feedback arc because the output is synchronous. However, a naive implementation
380 // of code generation for cells that assigns to inputs, evaluates cells, assigns from outputs
381 // would not be able to immediately converge...
382 //
383 // wire<1> i_tmp;
384 // cell->p_i = i_tmp.curr;
385 // cell->eval();
386 // i_tmp.next = cell->p_o.curr;
387 //
388 // ... since the wire connecting the input and output ports would not be localizable. To solve
389 // this, the cell is split into two scheduling nodes; one exclusively for sync outputs, and
390 // another for inputs and all non-sync outputs. This way the generated code can be rearranged...
391 //
392 // value<1> i_tmp;
393 // i_tmp = cell->p_o.curr;
394 // cell->p_i = i_tmp;
395 // cell->eval();
396 //
397 // eliminating the unnecessary delta cycle. Conceptually, the CELL_SYNC node type is a series of
398 // connections of the form `connect \lhs \cell.\sync_output`; the right-hand side of these is not
399 // expressible as a wire in RTLIL. If it was expressible, then `\cell.\sync_output` would have
400 // a sync def, and this node would be an ordinary CONNECT node, with `\lhs` having a comb def.
401 // Because it isn't, a special node type is used, the right-hand side does not appear anywhere,
402 // and the left-hand side has a comb def.
403 for (auto conn : cell->connections())
404 if (cell->output(conn.first))
405 if (is_cxxrtl_sync_port(cell, conn.first)) {
406 // See note regarding inlinability below.
407 add_defs(node, conn.second, /*is_ff=*/false, /*inlinable=*/false);
408 }
409 }
410
411 void add_cell_eval_defs_uses(Node *node, const RTLIL::Cell *cell)
412 {
413 for (auto conn : cell->connections()) {
414 if (cell->output(conn.first)) {
415 if (is_inlinable_cell(cell->type))
416 add_defs(node, conn.second, /*is_ff=*/false, /*inlinable=*/true);
417 else if (is_ff_cell(cell->type) || (cell->type == ID($memrd) && cell->getParam(ID::CLK_ENABLE).as_bool()))
418 add_defs(node, conn.second, /*is_ff=*/true, /*inlinable=*/false);
419 else if (is_internal_cell(cell->type))
420 add_defs(node, conn.second, /*is_ff=*/false, /*inlinable=*/false);
421 else if (!is_cxxrtl_sync_port(cell, conn.first)) {
422 // Although at first it looks like outputs of user-defined cells may always be inlined, the reality is
423 // more complex. Fully sync outputs produce no defs and so don't participate in inlining. Fully comb
424 // outputs are assigned in a different way depending on whether the cell's eval() immediately converged.
425 // Unknown/mixed outputs could be inlined, but should be rare in practical designs and don't justify
426 // the infrastructure required to inline outputs of cells with many of them.
427 add_defs(node, conn.second, /*is_ff=*/false, /*inlinable=*/false);
428 }
429 }
430 if (cell->input(conn.first))
431 add_uses(node, conn.second);
432 }
433 }
434
435 Node *add_node(const RTLIL::Cell *cell)
436 {
437 log_assert(cell->known());
438
439 bool has_fully_sync_outputs = false;
440 for (auto conn : cell->connections())
441 if (cell->output(conn.first) && is_cxxrtl_sync_port(cell, conn.first)) {
442 has_fully_sync_outputs = true;
443 break;
444 }
445 if (has_fully_sync_outputs) {
446 Node *node = new Node;
447 node->type = Node::Type::CELL_SYNC;
448 node->cell = cell;
449 nodes.push_back(node);
450 add_cell_sync_defs(node, cell);
451 }
452
453 Node *node = new Node;
454 node->type = Node::Type::CELL_EVAL;
455 node->cell = cell;
456 nodes.push_back(node);
457 add_cell_eval_defs_uses(node, cell);
458 return node;
459 }
460
461 // Processes
462 void add_case_rule_defs_uses(Node *node, const RTLIL::CaseRule *case_)
463 {
464 for (auto &action : case_->actions) {
465 add_defs(node, action.first, /*is_ff=*/false, /*inlinable=*/false);
466 add_uses(node, action.second);
467 }
468 for (auto sub_switch : case_->switches) {
469 add_uses(node, sub_switch->signal);
470 for (auto sub_case : sub_switch->cases) {
471 for (auto &compare : sub_case->compare)
472 add_uses(node, compare);
473 add_case_rule_defs_uses(node, sub_case);
474 }
475 }
476 }
477
478 void add_sync_rules_defs_uses(Node *node, const RTLIL::Process *process)
479 {
480 for (auto sync : process->syncs)
481 for (auto action : sync->actions) {
482 if (sync->type == RTLIL::STp || sync->type == RTLIL::STn || sync->type == RTLIL::STe)
483 add_defs(node, action.first, /*is_ff=*/true, /*inlinable=*/false);
484 else
485 add_defs(node, action.first, /*is_ff=*/false, /*inlinable=*/false);
486 add_uses(node, action.second);
487 }
488 }
489
490 Node *add_node(const RTLIL::Process *process)
491 {
492 Node *node = new Node;
493 node->type = Node::Type::PROCESS_SYNC;
494 node->process = process;
495 nodes.push_back(node);
496 add_sync_rules_defs_uses(node, process);
497
498 node = new Node;
499 node->type = Node::Type::PROCESS_CASE;
500 node->process = process;
501 nodes.push_back(node);
502 add_case_rule_defs_uses(node, &process->root_case);
503 return node;
504 }
505 };
506
507 std::vector<std::string> split_by(const std::string &str, const std::string &sep)
508 {
509 std::vector<std::string> result;
510 size_t prev = 0;
511 while (true) {
512 size_t curr = str.find_first_of(sep, prev);
513 if (curr == std::string::npos) {
514 std::string part = str.substr(prev);
515 if (!part.empty()) result.push_back(part);
516 break;
517 } else {
518 std::string part = str.substr(prev, curr - prev);
519 if (!part.empty()) result.push_back(part);
520 prev = curr + 1;
521 }
522 }
523 return result;
524 }
525
526 std::string escape_cxx_string(const std::string &input)
527 {
528 std::string output = "\"";
529 for (auto c : input) {
530 if (::isprint(c)) {
531 if (c == '\\')
532 output.push_back('\\');
533 output.push_back(c);
534 } else {
535 char l = c & 0xf, h = (c >> 4) & 0xf;
536 output.append("\\x");
537 output.push_back((h < 10 ? '0' + h : 'a' + h - 10));
538 output.push_back((l < 10 ? '0' + l : 'a' + l - 10));
539 }
540 }
541 output.push_back('"');
542 if (output.find('\0') != std::string::npos) {
543 output.insert(0, "std::string {");
544 output.append(stringf(", %zu}", input.size()));
545 }
546 return output;
547 }
548
549 template<class T>
550 std::string get_hdl_name(T *object)
551 {
552 if (object->has_attribute(ID::hdlname))
553 return object->get_string_attribute(ID::hdlname);
554 else
555 return object->name.str().substr(1);
556 }
557
558 struct WireType {
559 enum Type {
560 // Non-referenced wire; is not a part of the design.
561 UNUSED,
562 // Double-buffered wire; is a class member, and holds design state.
563 BUFFERED,
564 // Single-buffered wire; is a class member, but holds no state.
565 MEMBER,
566 // Single-buffered wire; is a class member, and is computed on demand.
567 OUTLINE,
568 // Local wire; is a local variable in eval method.
569 LOCAL,
570 // Inline wire; is an unnamed temporary in eval method.
571 INLINE,
572 // Alias wire; is replaced with aliasee, except in debug info.
573 ALIAS,
574 // Const wire; is replaced with constant, except in debug info.
575 CONST,
576 };
577
578 Type type = UNUSED;
579 const RTLIL::Cell *cell_subst = nullptr; // for INLINE
580 RTLIL::SigSpec sig_subst = {}; // for INLINE, ALIAS, and CONST
581
582 WireType() = default;
583
584 WireType(Type type) : type(type) {
585 log_assert(type == UNUSED || type == BUFFERED || type == MEMBER || type == OUTLINE || type == LOCAL);
586 }
587
588 WireType(Type type, const RTLIL::Cell *cell) : type(type), cell_subst(cell) {
589 log_assert(type == INLINE && is_inlinable_cell(cell->type));
590 }
591
592 WireType(Type type, RTLIL::SigSpec sig) : type(type), sig_subst(sig) {
593 log_assert(type == INLINE || (type == ALIAS && sig.is_wire()) || (type == CONST && sig.is_fully_const()));
594 }
595
596 bool is_buffered() const { return type == BUFFERED; }
597 bool is_member() const { return type == BUFFERED || type == MEMBER || type == OUTLINE; }
598 bool is_outline() const { return type == OUTLINE; }
599 bool is_named() const { return is_member() || type == LOCAL; }
600 bool is_local() const { return type == LOCAL || type == INLINE; }
601 bool is_exact() const { return type == ALIAS || type == CONST; }
602 };
603
604 struct CxxrtlWorker {
605 bool split_intf = false;
606 std::string intf_filename;
607 std::string design_ns = "cxxrtl_design";
608 std::ostream *impl_f = nullptr;
609 std::ostream *intf_f = nullptr;
610
611 bool run_hierarchy = false;
612 bool run_flatten = false;
613 bool run_proc = false;
614
615 bool unbuffer_internal = false;
616 bool unbuffer_public = false;
617 bool localize_internal = false;
618 bool localize_public = false;
619 bool inline_internal = false;
620 bool inline_public = false;
621
622 bool debug_info = false;
623 bool debug_member = false;
624 bool debug_alias = false;
625 bool debug_eval = false;
626
627 std::ostringstream f;
628 std::string indent;
629 int temporary = 0;
630
631 dict<const RTLIL::Module*, SigMap> sigmaps;
632 pool<const RTLIL::Wire*> edge_wires;
633 dict<RTLIL::SigBit, RTLIL::SyncType> edge_types;
634 pool<const RTLIL::Memory*> writable_memories;
635 dict<const RTLIL::Cell*, pool<const RTLIL::Cell*>> transparent_for;
636 dict<const RTLIL::Module*, std::vector<FlowGraph::Node>> schedule, debug_schedule;
637 dict<const RTLIL::Wire*, WireType> wire_types, debug_wire_types;
638 dict<RTLIL::SigBit, bool> bit_has_state;
639 dict<const RTLIL::Module*, pool<std::string>> blackbox_specializations;
640 dict<const RTLIL::Module*, bool> eval_converges;
641
642 void inc_indent() {
643 indent += "\t";
644 }
645 void dec_indent() {
646 indent.resize(indent.size() - 1);
647 }
648
649 // RTLIL allows any characters in names other than whitespace. This presents an issue for generating C++ code
650 // because C++ identifiers may be only alphanumeric, cannot clash with C++ keywords, and cannot clash with cxxrtl
651 // identifiers. This issue can be solved with a name mangling scheme. We choose a name mangling scheme that results
652 // in readable identifiers, does not depend on an up-to-date list of C++ keywords, and is easy to apply. Its rules:
653 // 1. All generated identifiers start with `_`.
654 // 1a. Generated identifiers for public names (beginning with `\`) start with `p_`.
655 // 1b. Generated identifiers for internal names (beginning with `$`) start with `i_`.
656 // 2. An underscore is escaped with another underscore, i.e. `__`.
657 // 3. Any other non-alnum character is escaped with underscores around its lowercase hex code, e.g. `@` as `_40_`.
658 std::string mangle_name(const RTLIL::IdString &name)
659 {
660 std::string mangled;
661 bool first = true;
662 for (char c : name.str()) {
663 if (first) {
664 first = false;
665 if (c == '\\')
666 mangled += "p_";
667 else if (c == '$')
668 mangled += "i_";
669 else
670 log_assert(false);
671 } else {
672 if (isalnum(c)) {
673 mangled += c;
674 } else if (c == '_') {
675 mangled += "__";
676 } else {
677 char l = c & 0xf, h = (c >> 4) & 0xf;
678 mangled += '_';
679 mangled += (h < 10 ? '0' + h : 'a' + h - 10);
680 mangled += (l < 10 ? '0' + l : 'a' + l - 10);
681 mangled += '_';
682 }
683 }
684 }
685 return mangled;
686 }
687
688 std::string mangle_module_name(const RTLIL::IdString &name, bool is_blackbox = false)
689 {
690 // Class namespace.
691 if (is_blackbox)
692 return "bb_" + mangle_name(name);
693 return mangle_name(name);
694 }
695
696 std::string mangle_memory_name(const RTLIL::IdString &name)
697 {
698 // Class member namespace.
699 return "memory_" + mangle_name(name);
700 }
701
702 std::string mangle_cell_name(const RTLIL::IdString &name)
703 {
704 // Class member namespace.
705 return "cell_" + mangle_name(name);
706 }
707
708 std::string mangle_wire_name(const RTLIL::IdString &name)
709 {
710 // Class member namespace.
711 return mangle_name(name);
712 }
713
714 std::string mangle(const RTLIL::Module *module)
715 {
716 return mangle_module_name(module->name, /*is_blackbox=*/module->get_bool_attribute(ID(cxxrtl_blackbox)));
717 }
718
719 std::string mangle(const RTLIL::Memory *memory)
720 {
721 return mangle_memory_name(memory->name);
722 }
723
724 std::string mangle(const RTLIL::Cell *cell)
725 {
726 return mangle_cell_name(cell->name);
727 }
728
729 std::string mangle(const RTLIL::Wire *wire)
730 {
731 return mangle_wire_name(wire->name);
732 }
733
734 std::string mangle(RTLIL::SigBit sigbit)
735 {
736 log_assert(sigbit.wire != NULL);
737 if (sigbit.wire->width == 1)
738 return mangle(sigbit.wire);
739 return mangle(sigbit.wire) + "_" + std::to_string(sigbit.offset);
740 }
741
742 std::vector<std::string> template_param_names(const RTLIL::Module *module)
743 {
744 if (!module->has_attribute(ID(cxxrtl_template)))
745 return {};
746
747 if (module->attributes.at(ID(cxxrtl_template)).flags != RTLIL::CONST_FLAG_STRING)
748 log_cmd_error("Attribute `cxxrtl_template' of module `%s' is not a string.\n", log_id(module));
749
750 std::vector<std::string> param_names = split_by(module->get_string_attribute(ID(cxxrtl_template)), " \t");
751 for (const auto &param_name : param_names) {
752 // Various lowercase prefixes (p_, i_, cell_, ...) are used for member variables, so require
753 // parameters to start with an uppercase letter to avoid name conflicts. (This is the convention
754 // in both Verilog and C++, anyway.)
755 if (!isupper(param_name[0]))
756 log_cmd_error("Attribute `cxxrtl_template' of module `%s' includes a parameter `%s', "
757 "which does not start with an uppercase letter.\n",
758 log_id(module), param_name.c_str());
759 }
760 return param_names;
761 }
762
763 std::string template_params(const RTLIL::Module *module, bool is_decl)
764 {
765 std::vector<std::string> param_names = template_param_names(module);
766 if (param_names.empty())
767 return "";
768
769 std::string params = "<";
770 bool first = true;
771 for (const auto &param_name : param_names) {
772 if (!first)
773 params += ", ";
774 first = false;
775 if (is_decl)
776 params += "size_t ";
777 params += param_name;
778 }
779 params += ">";
780 return params;
781 }
782
783 std::string template_args(const RTLIL::Cell *cell)
784 {
785 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
786 log_assert(cell_module != nullptr);
787 if (!cell_module->get_bool_attribute(ID(cxxrtl_blackbox)))
788 return "";
789
790 std::vector<std::string> param_names = template_param_names(cell_module);
791 if (param_names.empty())
792 return "";
793
794 std::string params = "<";
795 bool first = true;
796 for (const auto &param_name : param_names) {
797 if (!first)
798 params += ", ";
799 first = false;
800 params += "/*" + param_name + "=*/";
801 RTLIL::IdString id_param_name = '\\' + param_name;
802 if (!cell->hasParam(id_param_name))
803 log_cmd_error("Cell `%s.%s' does not have a parameter `%s', which is required by the templated module `%s'.\n",
804 log_id(cell->module), log_id(cell), param_name.c_str(), log_id(cell_module));
805 RTLIL::Const param_value = cell->getParam(id_param_name);
806 if (((param_value.flags & ~RTLIL::CONST_FLAG_SIGNED) != 0) || param_value.as_int() < 0)
807 log_cmd_error("Parameter `%s' of cell `%s.%s', which is required by the templated module `%s', "
808 "is not a positive integer.\n",
809 param_name.c_str(), log_id(cell->module), log_id(cell), log_id(cell_module));
810 params += std::to_string(cell->getParam(id_param_name).as_int());
811 }
812 params += ">";
813 return params;
814 }
815
816 std::string fresh_temporary()
817 {
818 return stringf("tmp_%d", temporary++);
819 }
820
821 void dump_attrs(const RTLIL::AttrObject *object)
822 {
823 for (auto attr : object->attributes) {
824 f << indent << "// " << attr.first.str() << ": ";
825 if (attr.second.flags & RTLIL::CONST_FLAG_STRING) {
826 f << attr.second.decode_string();
827 } else {
828 f << attr.second.as_int(/*is_signed=*/attr.second.flags & RTLIL::CONST_FLAG_SIGNED);
829 }
830 f << "\n";
831 }
832 }
833
834 void dump_const_init(const RTLIL::Const &data, int width, int offset = 0, bool fixed_width = false)
835 {
836 const int CHUNK_SIZE = 32;
837 f << "{";
838 while (width > 0) {
839 int chunk_width = min(width, CHUNK_SIZE);
840 uint32_t chunk = data.extract(offset, chunk_width).as_int();
841 if (fixed_width)
842 f << stringf("0x%.*xu", (3 + chunk_width) / 4, chunk);
843 else
844 f << stringf("%#xu", chunk);
845 if (width > CHUNK_SIZE)
846 f << ',';
847 offset += CHUNK_SIZE;
848 width -= CHUNK_SIZE;
849 }
850 f << "}";
851 }
852
853 void dump_const_init(const RTLIL::Const &data)
854 {
855 dump_const_init(data, data.size());
856 }
857
858 void dump_const(const RTLIL::Const &data, int width, int offset = 0, bool fixed_width = false)
859 {
860 f << "value<" << width << ">";
861 dump_const_init(data, width, offset, fixed_width);
862 }
863
864 void dump_const(const RTLIL::Const &data)
865 {
866 dump_const(data, data.size());
867 }
868
869 bool dump_sigchunk(const RTLIL::SigChunk &chunk, bool is_lhs, bool for_debug = false)
870 {
871 if (chunk.wire == NULL) {
872 dump_const(chunk.data, chunk.width, chunk.offset);
873 return false;
874 } else {
875 const auto &wire_type = (for_debug ? debug_wire_types : wire_types)[chunk.wire];
876 switch (wire_type.type) {
877 case WireType::BUFFERED:
878 f << mangle(chunk.wire) << (is_lhs ? ".next" : ".curr");
879 break;
880 case WireType::MEMBER:
881 case WireType::LOCAL:
882 case WireType::OUTLINE:
883 f << mangle(chunk.wire);
884 break;
885 case WireType::INLINE:
886 log_assert(!is_lhs);
887 if (wire_type.cell_subst != nullptr) {
888 dump_cell_expr(wire_type.cell_subst, for_debug);
889 break;
890 }
891 YS_FALLTHROUGH
892 case WireType::ALIAS:
893 case WireType::CONST:
894 log_assert(!is_lhs);
895 return dump_sigspec(wire_type.sig_subst.extract(chunk.offset, chunk.width), is_lhs, for_debug);
896 case WireType::UNUSED:
897 log_assert(is_lhs);
898 f << "value<" << chunk.width << ">()";
899 return false;
900 }
901 if (chunk.width == chunk.wire->width && chunk.offset == 0)
902 return false;
903 else if (chunk.width == 1)
904 f << ".slice<" << chunk.offset << ">()";
905 else
906 f << ".slice<" << chunk.offset+chunk.width-1 << "," << chunk.offset << ">()";
907 return true;
908 }
909 }
910
911 bool dump_sigspec(const RTLIL::SigSpec &sig, bool is_lhs, bool for_debug = false)
912 {
913 if (sig.empty()) {
914 f << "value<0>()";
915 return false;
916 } else if (sig.is_chunk()) {
917 return dump_sigchunk(sig.as_chunk(), is_lhs, for_debug);
918 } else {
919 bool first = true;
920 auto chunks = sig.chunks();
921 for (auto it = chunks.rbegin(); it != chunks.rend(); it++) {
922 if (!first)
923 f << ".concat(";
924 bool is_complex = dump_sigchunk(*it, is_lhs, for_debug);
925 if (!is_lhs && it->width == 1) {
926 size_t repeat = 1;
927 while ((it + repeat) != chunks.rend() && *(it + repeat) == *it)
928 repeat++;
929 if (repeat > 1) {
930 if (is_complex)
931 f << ".val()";
932 f << ".repeat<" << repeat << ">()";
933 }
934 it += repeat - 1;
935 }
936 if (!first)
937 f << ")";
938 first = false;
939 }
940 return true;
941 }
942 }
943
944 void dump_sigspec_lhs(const RTLIL::SigSpec &sig, bool for_debug = false)
945 {
946 dump_sigspec(sig, /*is_lhs=*/true, for_debug);
947 }
948
949 void dump_sigspec_rhs(const RTLIL::SigSpec &sig, bool for_debug = false)
950 {
951 // In the contexts where we want template argument deduction to occur for `template<size_t Bits> ... value<Bits>`,
952 // it is necessary to have the argument to already be a `value<N>`, since template argument deduction and implicit
953 // type conversion are mutually exclusive. In these contexts, we use dump_sigspec_rhs() to emit an explicit
954 // type conversion, but only if the expression needs it.
955 bool is_complex = dump_sigspec(sig, /*is_lhs=*/false, for_debug);
956 if (is_complex)
957 f << ".val()";
958 }
959
960 void dump_inlined_cells(const std::vector<const RTLIL::Cell*> &cells)
961 {
962 if (cells.empty()) {
963 f << indent << "// connection\n";
964 } else if (cells.size() == 1) {
965 dump_attrs(cells.front());
966 f << indent << "// cell " << cells.front()->name.str() << "\n";
967 } else {
968 f << indent << "// cells";
969 for (auto cell : cells)
970 f << " " << cell->name.str();
971 f << "\n";
972 }
973 }
974
975 void collect_sigspec_rhs(const RTLIL::SigSpec &sig, bool for_debug, std::vector<const RTLIL::Cell*> &cells)
976 {
977 for (auto chunk : sig.chunks()) {
978 if (!chunk.wire)
979 continue;
980 const auto &wire_type = wire_types[chunk.wire];
981 switch (wire_type.type) {
982 case WireType::INLINE:
983 if (wire_type.cell_subst != nullptr) {
984 collect_cell_eval(wire_type.cell_subst, for_debug, cells);
985 break;
986 }
987 YS_FALLTHROUGH
988 case WireType::ALIAS:
989 collect_sigspec_rhs(wire_type.sig_subst, for_debug, cells);
990 break;
991 default:
992 break;
993 }
994 }
995 }
996
997 void dump_connect_expr(const RTLIL::SigSig &conn, bool for_debug = false)
998 {
999 dump_sigspec_rhs(conn.second, for_debug);
1000 }
1001
1002 void dump_connect(const RTLIL::SigSig &conn, bool for_debug = false)
1003 {
1004 std::vector<const RTLIL::Cell*> inlined_cells;
1005 collect_sigspec_rhs(conn.second, for_debug, inlined_cells);
1006 dump_inlined_cells(inlined_cells);
1007
1008 f << indent;
1009 dump_sigspec_lhs(conn.first, for_debug);
1010 f << " = ";
1011 dump_connect_expr(conn, for_debug);
1012 f << ";\n";
1013 }
1014
1015 void collect_connect(const RTLIL::SigSig &conn, bool for_debug, std::vector<const RTLIL::Cell*> &cells)
1016 {
1017 collect_sigspec_rhs(conn.second, for_debug, cells);
1018 }
1019
1020 void dump_cell_sync(const RTLIL::Cell *cell, bool for_debug = false)
1021 {
1022 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
1023 f << indent << "// cell " << cell->name.str() << " syncs\n";
1024 for (auto conn : cell->connections())
1025 if (cell->output(conn.first))
1026 if (is_cxxrtl_sync_port(cell, conn.first)) {
1027 f << indent;
1028 dump_sigspec_lhs(conn.second, for_debug);
1029 f << " = " << mangle(cell) << access << mangle_wire_name(conn.first) << ".curr;\n";
1030 }
1031 }
1032
1033 void dump_cell_expr(const RTLIL::Cell *cell, bool for_debug = false)
1034 {
1035 // Unary cells
1036 if (is_unary_cell(cell->type)) {
1037 f << cell->type.substr(1);
1038 if (is_extending_cell(cell->type))
1039 f << '_' << (cell->getParam(ID::A_SIGNED).as_bool() ? 's' : 'u');
1040 f << "<" << cell->getParam(ID::Y_WIDTH).as_int() << ">(";
1041 dump_sigspec_rhs(cell->getPort(ID::A), for_debug);
1042 f << ")";
1043 // Binary cells
1044 } else if (is_binary_cell(cell->type)) {
1045 f << cell->type.substr(1);
1046 if (is_extending_cell(cell->type))
1047 f << '_' << (cell->getParam(ID::A_SIGNED).as_bool() ? 's' : 'u') <<
1048 (cell->getParam(ID::B_SIGNED).as_bool() ? 's' : 'u');
1049 f << "<" << cell->getParam(ID::Y_WIDTH).as_int() << ">(";
1050 dump_sigspec_rhs(cell->getPort(ID::A), for_debug);
1051 f << ", ";
1052 dump_sigspec_rhs(cell->getPort(ID::B), for_debug);
1053 f << ")";
1054 // Muxes
1055 } else if (cell->type == ID($mux)) {
1056 f << "(";
1057 dump_sigspec_rhs(cell->getPort(ID::S), for_debug);
1058 f << " ? ";
1059 dump_sigspec_rhs(cell->getPort(ID::B), for_debug);
1060 f << " : ";
1061 dump_sigspec_rhs(cell->getPort(ID::A), for_debug);
1062 f << ")";
1063 // Parallel (one-hot) muxes
1064 } else if (cell->type == ID($pmux)) {
1065 int width = cell->getParam(ID::WIDTH).as_int();
1066 int s_width = cell->getParam(ID::S_WIDTH).as_int();
1067 for (int part = 0; part < s_width; part++) {
1068 f << "(";
1069 dump_sigspec_rhs(cell->getPort(ID::S).extract(part), for_debug);
1070 f << " ? ";
1071 dump_sigspec_rhs(cell->getPort(ID::B).extract(part * width, width), for_debug);
1072 f << " : ";
1073 }
1074 dump_sigspec_rhs(cell->getPort(ID::A), for_debug);
1075 for (int part = 0; part < s_width; part++) {
1076 f << ")";
1077 }
1078 // Concats
1079 } else if (cell->type == ID($concat)) {
1080 dump_sigspec_rhs(cell->getPort(ID::B), for_debug);
1081 f << ".concat(";
1082 dump_sigspec_rhs(cell->getPort(ID::A), for_debug);
1083 f << ").val()";
1084 // Slices
1085 } else if (cell->type == ID($slice)) {
1086 dump_sigspec_rhs(cell->getPort(ID::A), for_debug);
1087 f << ".slice<";
1088 f << cell->getParam(ID::OFFSET).as_int() + cell->getParam(ID::Y_WIDTH).as_int() - 1;
1089 f << ",";
1090 f << cell->getParam(ID::OFFSET).as_int();
1091 f << ">().val()";
1092 } else {
1093 log_assert(false);
1094 }
1095 }
1096
1097 void dump_cell_eval(const RTLIL::Cell *cell, bool for_debug = false)
1098 {
1099 std::vector<const RTLIL::Cell*> inlined_cells;
1100 collect_cell_eval(cell, for_debug, inlined_cells);
1101 dump_inlined_cells(inlined_cells);
1102
1103 // Elidable cells
1104 if (is_inlinable_cell(cell->type)) {
1105 f << indent;
1106 dump_sigspec_lhs(cell->getPort(ID::Y), for_debug);
1107 f << " = ";
1108 dump_cell_expr(cell, for_debug);
1109 f << ";\n";
1110 // Flip-flops
1111 } else if (is_ff_cell(cell->type)) {
1112 log_assert(!for_debug);
1113 if (cell->hasPort(ID::CLK) && cell->getPort(ID::CLK).is_wire()) {
1114 // Edge-sensitive logic
1115 RTLIL::SigBit clk_bit = cell->getPort(ID::CLK)[0];
1116 clk_bit = sigmaps[clk_bit.wire->module](clk_bit);
1117 if (clk_bit.wire) {
1118 f << indent << "if (" << (cell->getParam(ID::CLK_POLARITY).as_bool() ? "posedge_" : "negedge_")
1119 << mangle(clk_bit) << ") {\n";
1120 } else {
1121 f << indent << "if (false) {\n";
1122 }
1123 inc_indent();
1124 if (cell->hasPort(ID::EN)) {
1125 f << indent << "if (";
1126 dump_sigspec_rhs(cell->getPort(ID::EN));
1127 f << " == value<1> {" << cell->getParam(ID::EN_POLARITY).as_bool() << "u}) {\n";
1128 inc_indent();
1129 }
1130 f << indent;
1131 dump_sigspec_lhs(cell->getPort(ID::Q));
1132 f << " = ";
1133 dump_sigspec_rhs(cell->getPort(ID::D));
1134 f << ";\n";
1135 if (cell->hasPort(ID::EN) && cell->type != ID($sdffce)) {
1136 dec_indent();
1137 f << indent << "}\n";
1138 }
1139 if (cell->hasPort(ID::SRST)) {
1140 f << indent << "if (";
1141 dump_sigspec_rhs(cell->getPort(ID::SRST));
1142 f << " == value<1> {" << cell->getParam(ID::SRST_POLARITY).as_bool() << "u}) {\n";
1143 inc_indent();
1144 f << indent;
1145 dump_sigspec_lhs(cell->getPort(ID::Q));
1146 f << " = ";
1147 dump_const(cell->getParam(ID::SRST_VALUE));
1148 f << ";\n";
1149 dec_indent();
1150 f << indent << "}\n";
1151 }
1152 if (cell->hasPort(ID::EN) && cell->type == ID($sdffce)) {
1153 dec_indent();
1154 f << indent << "}\n";
1155 }
1156 dec_indent();
1157 f << indent << "}\n";
1158 } else if (cell->hasPort(ID::EN)) {
1159 // Level-sensitive logic
1160 f << indent << "if (";
1161 dump_sigspec_rhs(cell->getPort(ID::EN));
1162 f << " == value<1> {" << cell->getParam(ID::EN_POLARITY).as_bool() << "u}) {\n";
1163 inc_indent();
1164 f << indent;
1165 dump_sigspec_lhs(cell->getPort(ID::Q));
1166 f << " = ";
1167 dump_sigspec_rhs(cell->getPort(ID::D));
1168 f << ";\n";
1169 dec_indent();
1170 f << indent << "}\n";
1171 }
1172 if (cell->hasPort(ID::ARST)) {
1173 // Asynchronous reset (entire coarse cell at once)
1174 f << indent << "if (";
1175 dump_sigspec_rhs(cell->getPort(ID::ARST));
1176 f << " == value<1> {" << cell->getParam(ID::ARST_POLARITY).as_bool() << "u}) {\n";
1177 inc_indent();
1178 f << indent;
1179 dump_sigspec_lhs(cell->getPort(ID::Q));
1180 f << " = ";
1181 dump_const(cell->getParam(ID::ARST_VALUE));
1182 f << ";\n";
1183 dec_indent();
1184 f << indent << "}\n";
1185 }
1186 if (cell->hasPort(ID::SET)) {
1187 // Asynchronous set (for individual bits)
1188 f << indent;
1189 dump_sigspec_lhs(cell->getPort(ID::Q));
1190 f << " = ";
1191 dump_sigspec_lhs(cell->getPort(ID::Q));
1192 f << ".update(";
1193 dump_const(RTLIL::Const(RTLIL::S1, cell->getParam(ID::WIDTH).as_int()));
1194 f << ", ";
1195 dump_sigspec_rhs(cell->getPort(ID::SET));
1196 f << (cell->getParam(ID::SET_POLARITY).as_bool() ? "" : ".bit_not()") << ");\n";
1197 }
1198 if (cell->hasPort(ID::CLR)) {
1199 // Asynchronous clear (for individual bits; priority over set)
1200 f << indent;
1201 dump_sigspec_lhs(cell->getPort(ID::Q));
1202 f << " = ";
1203 dump_sigspec_lhs(cell->getPort(ID::Q));
1204 f << ".update(";
1205 dump_const(RTLIL::Const(RTLIL::S0, cell->getParam(ID::WIDTH).as_int()));
1206 f << ", ";
1207 dump_sigspec_rhs(cell->getPort(ID::CLR));
1208 f << (cell->getParam(ID::CLR_POLARITY).as_bool() ? "" : ".bit_not()") << ");\n";
1209 }
1210 // Memory ports
1211 } else if (cell->type.in(ID($memrd), ID($memwr))) {
1212 if (cell->getParam(ID::CLK_ENABLE).as_bool()) {
1213 log_assert(!for_debug);
1214 RTLIL::SigBit clk_bit = cell->getPort(ID::CLK)[0];
1215 clk_bit = sigmaps[clk_bit.wire->module](clk_bit);
1216 if (clk_bit.wire) {
1217 f << indent << "if (" << (cell->getParam(ID::CLK_POLARITY).as_bool() ? "posedge_" : "negedge_")
1218 << mangle(clk_bit) << ") {\n";
1219 } else {
1220 f << indent << "if (false) {\n";
1221 }
1222 inc_indent();
1223 }
1224 RTLIL::Memory *memory = cell->module->memories[cell->getParam(ID::MEMID).decode_string()];
1225 std::string valid_index_temp = fresh_temporary();
1226 f << indent << "auto " << valid_index_temp << " = memory_index(";
1227 dump_sigspec_rhs(cell->getPort(ID::ADDR));
1228 f << ", " << memory->start_offset << ", " << memory->size << ");\n";
1229 if (cell->type == ID($memrd)) {
1230 bool has_enable = cell->getParam(ID::CLK_ENABLE).as_bool() && !cell->getPort(ID::EN).is_fully_ones();
1231 if (has_enable) {
1232 f << indent << "if (";
1233 dump_sigspec_rhs(cell->getPort(ID::EN));
1234 f << ") {\n";
1235 inc_indent();
1236 }
1237 // The generated code has two bounds checks; one in an assertion, and another that guards the read.
1238 // This is done so that the code does not invoke undefined behavior under any conditions, but nevertheless
1239 // loudly crashes if an illegal condition is encountered. The assert may be turned off with -DCXXRTL_NDEBUG
1240 // not only for release builds, but also to make sure the simulator (which is presumably embedded in some
1241 // larger program) will never crash the code that calls into it.
1242 //
1243 // If assertions are disabled, out of bounds reads are defined to return zero.
1244 f << indent << "CXXRTL_ASSERT(" << valid_index_temp << ".valid && \"out of bounds read\");\n";
1245 f << indent << "if(" << valid_index_temp << ".valid) {\n";
1246 inc_indent();
1247 if (writable_memories[memory]) {
1248 std::string lhs_temp = fresh_temporary();
1249 f << indent << "value<" << memory->width << "> " << lhs_temp << " = "
1250 << mangle(memory) << "[" << valid_index_temp << ".index];\n";
1251 std::vector<const RTLIL::Cell*> memwr_cells(transparent_for[cell].begin(), transparent_for[cell].end());
1252 if (!memwr_cells.empty()) {
1253 std::string addr_temp = fresh_temporary();
1254 f << indent << "const value<" << cell->getPort(ID::ADDR).size() << "> &" << addr_temp << " = ";
1255 dump_sigspec_rhs(cell->getPort(ID::ADDR));
1256 f << ";\n";
1257 std::sort(memwr_cells.begin(), memwr_cells.end(),
1258 [](const RTLIL::Cell *a, const RTLIL::Cell *b) {
1259 return a->getParam(ID::PRIORITY).as_int() < b->getParam(ID::PRIORITY).as_int();
1260 });
1261 for (auto memwr_cell : memwr_cells) {
1262 f << indent << "if (" << addr_temp << " == ";
1263 dump_sigspec_rhs(memwr_cell->getPort(ID::ADDR));
1264 f << ") {\n";
1265 inc_indent();
1266 f << indent << lhs_temp << " = " << lhs_temp;
1267 f << ".update(";
1268 dump_sigspec_rhs(memwr_cell->getPort(ID::DATA));
1269 f << ", ";
1270 dump_sigspec_rhs(memwr_cell->getPort(ID::EN));
1271 f << ");\n";
1272 dec_indent();
1273 f << indent << "}\n";
1274 }
1275 }
1276 f << indent;
1277 dump_sigspec_lhs(cell->getPort(ID::DATA));
1278 f << " = " << lhs_temp << ";\n";
1279 } else {
1280 f << indent;
1281 dump_sigspec_lhs(cell->getPort(ID::DATA));
1282 f << " = " << mangle(memory) << "[" << valid_index_temp << ".index];\n";
1283 }
1284 dec_indent();
1285 f << indent << "} else {\n";
1286 inc_indent();
1287 f << indent;
1288 dump_sigspec_lhs(cell->getPort(ID::DATA));
1289 f << " = value<" << memory->width << "> {};\n";
1290 dec_indent();
1291 f << indent << "}\n";
1292 if (has_enable) {
1293 dec_indent();
1294 f << indent << "}\n";
1295 }
1296 } else /*if (cell->type == ID($memwr))*/ {
1297 log_assert(writable_memories[memory]);
1298 // See above for rationale of having both the assert and the condition.
1299 //
1300 // If assertions are disabled, out of bounds writes are defined to do nothing.
1301 f << indent << "CXXRTL_ASSERT(" << valid_index_temp << ".valid && \"out of bounds write\");\n";
1302 f << indent << "if (" << valid_index_temp << ".valid) {\n";
1303 inc_indent();
1304 f << indent << mangle(memory) << ".update(" << valid_index_temp << ".index, ";
1305 dump_sigspec_rhs(cell->getPort(ID::DATA));
1306 f << ", ";
1307 dump_sigspec_rhs(cell->getPort(ID::EN));
1308 f << ", " << cell->getParam(ID::PRIORITY).as_int() << ");\n";
1309 dec_indent();
1310 f << indent << "}\n";
1311 }
1312 if (cell->getParam(ID::CLK_ENABLE).as_bool()) {
1313 dec_indent();
1314 f << indent << "}\n";
1315 }
1316 // Internal cells
1317 } else if (is_internal_cell(cell->type)) {
1318 log_cmd_error("Unsupported internal cell `%s'.\n", cell->type.c_str());
1319 // User cells
1320 } else {
1321 log_assert(!for_debug);
1322 log_assert(cell->known());
1323 bool buffered_inputs = false;
1324 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
1325 for (auto conn : cell->connections())
1326 if (cell->input(conn.first)) {
1327 RTLIL::Module *cell_module = cell->module->design->module(cell->type);
1328 log_assert(cell_module != nullptr && cell_module->wire(conn.first) && conn.second.is_wire());
1329 RTLIL::Wire *cell_module_wire = cell_module->wire(conn.first);
1330 f << indent << mangle(cell) << access << mangle_wire_name(conn.first);
1331 if (!is_cxxrtl_blackbox_cell(cell) && wire_types[cell_module_wire].is_buffered()) {
1332 buffered_inputs = true;
1333 f << ".next";
1334 }
1335 f << " = ";
1336 dump_sigspec_rhs(conn.second);
1337 f << ";\n";
1338 if (getenv("CXXRTL_VOID_MY_WARRANTY")) {
1339 // Until we have proper clock tree detection, this really awful hack that opportunistically
1340 // propagates prev_* values for clocks can be used to estimate how much faster a design could
1341 // be if only one clock edge was simulated by replacing:
1342 // top.p_clk = value<1>{0u}; top.step();
1343 // top.p_clk = value<1>{1u}; top.step();
1344 // with:
1345 // top.prev_p_clk = value<1>{0u}; top.p_clk = value<1>{1u}; top.step();
1346 // Don't rely on this; it will be removed without warning.
1347 if (edge_wires[conn.second.as_wire()] && edge_wires[cell_module_wire]) {
1348 f << indent << mangle(cell) << access << "prev_" << mangle(cell_module_wire) << " = ";
1349 f << "prev_" << mangle(conn.second.as_wire()) << ";\n";
1350 }
1351 }
1352 }
1353 auto assign_from_outputs = [&](bool cell_converged) {
1354 for (auto conn : cell->connections()) {
1355 if (cell->output(conn.first)) {
1356 if (conn.second.empty())
1357 continue; // ignore disconnected ports
1358 if (is_cxxrtl_sync_port(cell, conn.first))
1359 continue; // fully sync ports are handled in CELL_SYNC nodes
1360 f << indent;
1361 dump_sigspec_lhs(conn.second);
1362 f << " = " << mangle(cell) << access << mangle_wire_name(conn.first);
1363 // Similarly to how there is no purpose to buffering cell inputs, there is also no purpose to buffering
1364 // combinatorial cell outputs in case the cell converges within one cycle. (To convince yourself that
1365 // this optimization is valid, consider that, since the cell converged within one cycle, it would not
1366 // have any buffered wires if they were not output ports. Imagine inlining the cell's eval() function,
1367 // and consider the fate of the localized wires that used to be output ports.)
1368 //
1369 // It is not possible to know apriori whether the cell (which may be late bound) will converge immediately.
1370 // Because of this, the choice between using .curr (appropriate for buffered outputs) and .next (appropriate
1371 // for unbuffered outputs) is made at runtime.
1372 if (cell_converged && is_cxxrtl_comb_port(cell, conn.first))
1373 f << ".next;\n";
1374 else
1375 f << ".curr;\n";
1376 }
1377 }
1378 };
1379 if (buffered_inputs) {
1380 // If we have any buffered inputs, there's no chance of converging immediately.
1381 f << indent << mangle(cell) << access << "eval();\n";
1382 f << indent << "converged = false;\n";
1383 assign_from_outputs(/*cell_converged=*/false);
1384 } else {
1385 f << indent << "if (" << mangle(cell) << access << "eval()) {\n";
1386 inc_indent();
1387 assign_from_outputs(/*cell_converged=*/true);
1388 dec_indent();
1389 f << indent << "} else {\n";
1390 inc_indent();
1391 f << indent << "converged = false;\n";
1392 assign_from_outputs(/*cell_converged=*/false);
1393 dec_indent();
1394 f << indent << "}\n";
1395 }
1396 }
1397 }
1398
1399 void collect_cell_eval(const RTLIL::Cell *cell, bool for_debug, std::vector<const RTLIL::Cell*> &cells)
1400 {
1401 cells.push_back(cell);
1402 for (auto port : cell->connections())
1403 if (cell->input(port.first))
1404 collect_sigspec_rhs(port.second, for_debug, cells);
1405 }
1406
1407 void dump_assign(const RTLIL::SigSig &sigsig)
1408 {
1409 f << indent;
1410 dump_sigspec_lhs(sigsig.first);
1411 f << " = ";
1412 dump_sigspec_rhs(sigsig.second);
1413 f << ";\n";
1414 }
1415
1416 void dump_case_rule(const RTLIL::CaseRule *rule)
1417 {
1418 for (auto action : rule->actions)
1419 dump_assign(action);
1420 for (auto switch_ : rule->switches)
1421 dump_switch_rule(switch_);
1422 }
1423
1424 void dump_switch_rule(const RTLIL::SwitchRule *rule)
1425 {
1426 // The switch attributes are printed before the switch condition is captured.
1427 dump_attrs(rule);
1428 std::string signal_temp = fresh_temporary();
1429 f << indent << "const value<" << rule->signal.size() << "> &" << signal_temp << " = ";
1430 dump_sigspec(rule->signal, /*is_lhs=*/false);
1431 f << ";\n";
1432
1433 bool first = true;
1434 for (auto case_ : rule->cases) {
1435 // The case attributes (for nested cases) are printed before the if/else if/else statement.
1436 dump_attrs(rule);
1437 f << indent;
1438 if (!first)
1439 f << "} else ";
1440 first = false;
1441 if (!case_->compare.empty()) {
1442 f << "if (";
1443 bool first = true;
1444 for (auto &compare : case_->compare) {
1445 if (!first)
1446 f << " || ";
1447 first = false;
1448 if (compare.is_fully_def()) {
1449 f << signal_temp << " == ";
1450 dump_sigspec(compare, /*is_lhs=*/false);
1451 } else if (compare.is_fully_const()) {
1452 RTLIL::Const compare_mask, compare_value;
1453 for (auto bit : compare.as_const()) {
1454 switch (bit) {
1455 case RTLIL::S0:
1456 case RTLIL::S1:
1457 compare_mask.bits.push_back(RTLIL::S1);
1458 compare_value.bits.push_back(bit);
1459 break;
1460
1461 case RTLIL::Sx:
1462 case RTLIL::Sz:
1463 case RTLIL::Sa:
1464 compare_mask.bits.push_back(RTLIL::S0);
1465 compare_value.bits.push_back(RTLIL::S0);
1466 break;
1467
1468 default:
1469 log_assert(false);
1470 }
1471 }
1472 f << "and_uu<" << compare.size() << ">(" << signal_temp << ", ";
1473 dump_const(compare_mask);
1474 f << ") == ";
1475 dump_const(compare_value);
1476 } else {
1477 log_assert(false);
1478 }
1479 }
1480 f << ") ";
1481 }
1482 f << "{\n";
1483 inc_indent();
1484 dump_case_rule(case_);
1485 dec_indent();
1486 }
1487 f << indent << "}\n";
1488 }
1489
1490 void dump_process_case(const RTLIL::Process *proc)
1491 {
1492 dump_attrs(proc);
1493 f << indent << "// process " << proc->name.str() << " case\n";
1494 // The case attributes (for root case) are always empty.
1495 log_assert(proc->root_case.attributes.empty());
1496 dump_case_rule(&proc->root_case);
1497 }
1498
1499 void dump_process_syncs(const RTLIL::Process *proc)
1500 {
1501 dump_attrs(proc);
1502 f << indent << "// process " << proc->name.str() << " syncs\n";
1503 for (auto sync : proc->syncs) {
1504 RTLIL::SigBit sync_bit;
1505 if (!sync->signal.empty()) {
1506 sync_bit = sync->signal[0];
1507 sync_bit = sigmaps[sync_bit.wire->module](sync_bit);
1508 }
1509
1510 pool<std::string> events;
1511 switch (sync->type) {
1512 case RTLIL::STp:
1513 log_assert(sync_bit.wire != nullptr);
1514 events.insert("posedge_" + mangle(sync_bit));
1515 break;
1516 case RTLIL::STn:
1517 log_assert(sync_bit.wire != nullptr);
1518 events.insert("negedge_" + mangle(sync_bit));
1519 break;
1520 case RTLIL::STe:
1521 log_assert(sync_bit.wire != nullptr);
1522 events.insert("posedge_" + mangle(sync_bit));
1523 events.insert("negedge_" + mangle(sync_bit));
1524 break;
1525
1526 case RTLIL::STa:
1527 events.insert("true");
1528 break;
1529
1530 case RTLIL::ST0:
1531 case RTLIL::ST1:
1532 case RTLIL::STg:
1533 case RTLIL::STi:
1534 log_assert(false);
1535 }
1536 if (!events.empty()) {
1537 f << indent << "if (";
1538 bool first = true;
1539 for (auto &event : events) {
1540 if (!first)
1541 f << " || ";
1542 first = false;
1543 f << event;
1544 }
1545 f << ") {\n";
1546 inc_indent();
1547 for (auto action : sync->actions)
1548 dump_assign(action);
1549 dec_indent();
1550 f << indent << "}\n";
1551 }
1552 }
1553 }
1554
1555 void dump_wire(const RTLIL::Wire *wire, bool is_local)
1556 {
1557 const auto &wire_type = wire_types[wire];
1558 if (!wire_type.is_named() || wire_type.is_local() != is_local)
1559 return;
1560
1561 dump_attrs(wire);
1562 f << indent;
1563 if (wire->port_input && wire->port_output)
1564 f << "/*inout*/ ";
1565 else if (wire->port_input)
1566 f << "/*input*/ ";
1567 else if (wire->port_output)
1568 f << "/*output*/ ";
1569 f << (wire_type.is_buffered() ? "wire" : "value");
1570 if (wire->module->has_attribute(ID(cxxrtl_blackbox)) && wire->has_attribute(ID(cxxrtl_width))) {
1571 f << "<" << wire->get_string_attribute(ID(cxxrtl_width)) << ">";
1572 } else {
1573 f << "<" << wire->width << ">";
1574 }
1575 f << " " << mangle(wire);
1576 if (wire->has_attribute(ID::init)) {
1577 f << " ";
1578 dump_const_init(wire->attributes.at(ID::init));
1579 }
1580 f << ";\n";
1581 if (edge_wires[wire]) {
1582 if (!wire_type.is_buffered()) {
1583 f << indent << "value<" << wire->width << "> prev_" << mangle(wire);
1584 if (wire->has_attribute(ID::init)) {
1585 f << " ";
1586 dump_const_init(wire->attributes.at(ID::init));
1587 }
1588 f << ";\n";
1589 }
1590 for (auto edge_type : edge_types) {
1591 if (edge_type.first.wire == wire) {
1592 std::string prev, next;
1593 if (!wire_type.is_buffered()) {
1594 prev = "prev_" + mangle(edge_type.first.wire);
1595 next = mangle(edge_type.first.wire);
1596 } else {
1597 prev = mangle(edge_type.first.wire) + ".curr";
1598 next = mangle(edge_type.first.wire) + ".next";
1599 }
1600 prev += ".slice<" + std::to_string(edge_type.first.offset) + ">().val()";
1601 next += ".slice<" + std::to_string(edge_type.first.offset) + ">().val()";
1602 if (edge_type.second != RTLIL::STn) {
1603 f << indent << "bool posedge_" << mangle(edge_type.first) << "() const {\n";
1604 inc_indent();
1605 f << indent << "return !" << prev << " && " << next << ";\n";
1606 dec_indent();
1607 f << indent << "}\n";
1608 }
1609 if (edge_type.second != RTLIL::STp) {
1610 f << indent << "bool negedge_" << mangle(edge_type.first) << "() const {\n";
1611 inc_indent();
1612 f << indent << "return " << prev << " && !" << next << ";\n";
1613 dec_indent();
1614 f << indent << "}\n";
1615 }
1616 }
1617 }
1618 }
1619 }
1620
1621 void dump_debug_wire(const RTLIL::Wire *wire, bool is_local)
1622 {
1623 const auto &wire_type = wire_types[wire];
1624 if (wire_type.is_member())
1625 return;
1626
1627 const auto &debug_wire_type = debug_wire_types[wire];
1628 if (!debug_wire_type.is_named() || debug_wire_type.is_local() != is_local)
1629 return;
1630
1631 dump_attrs(wire);
1632 f << indent;
1633 if (debug_wire_type.is_outline())
1634 f << "/*outline*/ ";
1635 f << "value<" << wire->width << "> " << mangle(wire) << ";\n";
1636 }
1637
1638 void dump_memory(RTLIL::Module *module, const RTLIL::Memory *memory)
1639 {
1640 vector<const RTLIL::Cell*> init_cells;
1641 for (auto cell : module->cells())
1642 if (cell->type == ID($meminit) && cell->getParam(ID::MEMID).decode_string() == memory->name.str())
1643 init_cells.push_back(cell);
1644
1645 std::sort(init_cells.begin(), init_cells.end(), [](const RTLIL::Cell *a, const RTLIL::Cell *b) {
1646 int a_addr = a->getPort(ID::ADDR).as_int(), b_addr = b->getPort(ID::ADDR).as_int();
1647 int a_prio = a->getParam(ID::PRIORITY).as_int(), b_prio = b->getParam(ID::PRIORITY).as_int();
1648 return a_prio > b_prio || (a_prio == b_prio && a_addr < b_addr);
1649 });
1650
1651 dump_attrs(memory);
1652 f << indent << "memory<" << memory->width << "> " << mangle(memory)
1653 << " { " << memory->size << "u";
1654 if (init_cells.empty()) {
1655 f << " };\n";
1656 } else {
1657 f << ",\n";
1658 inc_indent();
1659 for (auto cell : init_cells) {
1660 dump_attrs(cell);
1661 RTLIL::Const data = cell->getPort(ID::DATA).as_const();
1662 size_t width = cell->getParam(ID::WIDTH).as_int();
1663 size_t words = cell->getParam(ID::WORDS).as_int();
1664 f << indent << "memory<" << memory->width << ">::init<" << words << "> { "
1665 << stringf("%#x", cell->getPort(ID::ADDR).as_int()) << ", {";
1666 inc_indent();
1667 for (size_t n = 0; n < words; n++) {
1668 if (n % 4 == 0)
1669 f << "\n" << indent;
1670 else
1671 f << " ";
1672 dump_const(data, width, n * width, /*fixed_width=*/true);
1673 f << ",";
1674 }
1675 dec_indent();
1676 f << "\n" << indent << "}},\n";
1677 }
1678 dec_indent();
1679 f << indent << "};\n";
1680 }
1681 }
1682
1683 void dump_eval_method(RTLIL::Module *module)
1684 {
1685 inc_indent();
1686 f << indent << "bool converged = " << (eval_converges.at(module) ? "true" : "false") << ";\n";
1687 if (!module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1688 for (auto wire : module->wires()) {
1689 if (edge_wires[wire]) {
1690 for (auto edge_type : edge_types) {
1691 if (edge_type.first.wire == wire) {
1692 if (edge_type.second != RTLIL::STn) {
1693 f << indent << "bool posedge_" << mangle(edge_type.first) << " = ";
1694 f << "this->posedge_" << mangle(edge_type.first) << "();\n";
1695 }
1696 if (edge_type.second != RTLIL::STp) {
1697 f << indent << "bool negedge_" << mangle(edge_type.first) << " = ";
1698 f << "this->negedge_" << mangle(edge_type.first) << "();\n";
1699 }
1700 }
1701 }
1702 }
1703 }
1704 for (auto wire : module->wires())
1705 dump_wire(wire, /*is_local=*/true);
1706 for (auto node : schedule[module]) {
1707 switch (node.type) {
1708 case FlowGraph::Node::Type::CONNECT:
1709 dump_connect(node.connect);
1710 break;
1711 case FlowGraph::Node::Type::CELL_SYNC:
1712 dump_cell_sync(node.cell);
1713 break;
1714 case FlowGraph::Node::Type::CELL_EVAL:
1715 dump_cell_eval(node.cell);
1716 break;
1717 case FlowGraph::Node::Type::PROCESS_SYNC:
1718 dump_process_syncs(node.process);
1719 break;
1720 case FlowGraph::Node::Type::PROCESS_CASE:
1721 dump_process_case(node.process);
1722 break;
1723 }
1724 }
1725 }
1726 f << indent << "return converged;\n";
1727 dec_indent();
1728 }
1729
1730 void dump_debug_eval_method(RTLIL::Module *module)
1731 {
1732 inc_indent();
1733 for (auto wire : module->wires())
1734 dump_debug_wire(wire, /*is_local=*/true);
1735 for (auto node : debug_schedule[module]) {
1736 switch (node.type) {
1737 case FlowGraph::Node::Type::CONNECT:
1738 dump_connect(node.connect, /*for_debug=*/true);
1739 break;
1740 case FlowGraph::Node::Type::CELL_SYNC:
1741 dump_cell_sync(node.cell, /*for_debug=*/true);
1742 break;
1743 case FlowGraph::Node::Type::CELL_EVAL:
1744 dump_cell_eval(node.cell, /*for_debug=*/true);
1745 break;
1746 default:
1747 log_abort();
1748 }
1749 }
1750 dec_indent();
1751 }
1752
1753 void dump_commit_method(RTLIL::Module *module)
1754 {
1755 inc_indent();
1756 f << indent << "bool changed = false;\n";
1757 for (auto wire : module->wires()) {
1758 const auto &wire_type = wire_types[wire];
1759 if (wire_type.type == WireType::MEMBER && edge_wires[wire])
1760 f << indent << "prev_" << mangle(wire) << " = " << mangle(wire) << ";\n";
1761 if (wire_type.is_buffered())
1762 f << indent << "if (" << mangle(wire) << ".commit()) changed = true;\n";
1763 }
1764 if (!module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1765 for (auto memory : module->memories) {
1766 if (!writable_memories[memory.second])
1767 continue;
1768 f << indent << "if (" << mangle(memory.second) << ".commit()) changed = true;\n";
1769 }
1770 for (auto cell : module->cells()) {
1771 if (is_internal_cell(cell->type))
1772 continue;
1773 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
1774 f << indent << "if (" << mangle(cell) << access << "commit()) changed = true;\n";
1775 }
1776 }
1777 f << indent << "return changed;\n";
1778 dec_indent();
1779 }
1780
1781 void dump_debug_info_method(RTLIL::Module *module)
1782 {
1783 size_t count_public_wires = 0;
1784 size_t count_member_wires = 0;
1785 size_t count_undriven = 0;
1786 size_t count_driven_sync = 0;
1787 size_t count_driven_comb = 0;
1788 size_t count_mixed_driver = 0;
1789 size_t count_alias_wires = 0;
1790 size_t count_const_wires = 0;
1791 size_t count_inline_wires = 0;
1792 size_t count_skipped_wires = 0;
1793 inc_indent();
1794 f << indent << "assert(path.empty() || path[path.size() - 1] == ' ');\n";
1795 for (auto wire : module->wires()) {
1796 const auto &debug_wire_type = debug_wire_types[wire];
1797 if (!wire->name.isPublic())
1798 continue;
1799 count_public_wires++;
1800 switch (debug_wire_type.type) {
1801 case WireType::BUFFERED:
1802 case WireType::MEMBER: {
1803 // Member wire
1804 std::vector<std::string> flags;
1805
1806 if (wire->port_input && wire->port_output)
1807 flags.push_back("INOUT");
1808 else if (wire->port_output)
1809 flags.push_back("OUTPUT");
1810 else if (wire->port_input)
1811 flags.push_back("INPUT");
1812
1813 bool has_driven_sync = false;
1814 bool has_driven_comb = false;
1815 bool has_undriven = false;
1816 if (!module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1817 for (auto bit : SigSpec(wire))
1818 if (!bit_has_state.count(bit))
1819 has_undriven = true;
1820 else if (bit_has_state[bit])
1821 has_driven_sync = true;
1822 else
1823 has_driven_comb = true;
1824 } else if (wire->port_output) {
1825 switch (cxxrtl_port_type(module, wire->name)) {
1826 case CxxrtlPortType::SYNC:
1827 has_driven_sync = true;
1828 break;
1829 case CxxrtlPortType::COMB:
1830 has_driven_comb = true;
1831 break;
1832 case CxxrtlPortType::UNKNOWN:
1833 has_driven_sync = has_driven_comb = true;
1834 break;
1835 }
1836 } else {
1837 has_undriven = true;
1838 }
1839 if (has_undriven)
1840 flags.push_back("UNDRIVEN");
1841 if (!has_driven_sync && !has_driven_comb && has_undriven)
1842 count_undriven++;
1843 if (has_driven_sync)
1844 flags.push_back("DRIVEN_SYNC");
1845 if (has_driven_sync && !has_driven_comb && !has_undriven)
1846 count_driven_sync++;
1847 if (has_driven_comb)
1848 flags.push_back("DRIVEN_COMB");
1849 if (!has_driven_sync && has_driven_comb && !has_undriven)
1850 count_driven_comb++;
1851 if (has_driven_sync + has_driven_comb + has_undriven > 1)
1852 count_mixed_driver++;
1853
1854 f << indent << "items.add(path + " << escape_cxx_string(get_hdl_name(wire));
1855 f << ", debug_item(" << mangle(wire) << ", " << wire->start_offset;
1856 bool first = true;
1857 for (auto flag : flags) {
1858 if (first) {
1859 first = false;
1860 f << ", ";
1861 } else {
1862 f << "|";
1863 }
1864 f << "debug_item::" << flag;
1865 }
1866 f << "));\n";
1867 count_member_wires++;
1868 break;
1869 }
1870 case WireType::ALIAS: {
1871 // Alias of a member wire
1872 const RTLIL::Wire *aliasee = debug_wire_type.sig_subst.as_wire();
1873 f << indent << "items.add(path + " << escape_cxx_string(get_hdl_name(wire));
1874 f << ", debug_item(";
1875 // If the aliasee is an outline, then the alias must be an outline, too; otherwise downstream
1876 // tooling has no way to find out about the outline.
1877 if (debug_wire_types[aliasee].is_outline())
1878 f << "debug_eval_outline";
1879 else
1880 f << "debug_alias()";
1881 f << ", " << mangle(aliasee) << ", " << wire->start_offset << "));\n";
1882 count_alias_wires++;
1883 break;
1884 }
1885 case WireType::CONST: {
1886 // Wire tied to a constant
1887 f << indent << "static const value<" << wire->width << "> const_" << mangle(wire) << " = ";
1888 dump_const(debug_wire_type.sig_subst.as_const());
1889 f << ";\n";
1890 f << indent << "items.add(path + " << escape_cxx_string(get_hdl_name(wire));
1891 f << ", debug_item(const_" << mangle(wire) << ", " << wire->start_offset << "));\n";
1892 count_const_wires++;
1893 break;
1894 }
1895 case WireType::OUTLINE: {
1896 // Localized or inlined, but rematerializable wire
1897 f << indent << "items.add(path + " << escape_cxx_string(get_hdl_name(wire));
1898 f << ", debug_item(debug_eval_outline, " << mangle(wire) << ", " << wire->start_offset << "));\n";
1899 count_inline_wires++;
1900 break;
1901 }
1902 default: {
1903 // Localized or inlined wire with no debug information
1904 count_skipped_wires++;
1905 break;
1906 }
1907 }
1908 }
1909 if (!module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1910 for (auto &memory_it : module->memories) {
1911 if (!memory_it.first.isPublic())
1912 continue;
1913 f << indent << "items.add(path + " << escape_cxx_string(get_hdl_name(memory_it.second));
1914 f << ", debug_item(" << mangle(memory_it.second) << ", ";
1915 f << memory_it.second->start_offset << "));\n";
1916 }
1917 for (auto cell : module->cells()) {
1918 if (is_internal_cell(cell->type))
1919 continue;
1920 const char *access = is_cxxrtl_blackbox_cell(cell) ? "->" : ".";
1921 f << indent << mangle(cell) << access << "debug_info(items, ";
1922 f << "path + " << escape_cxx_string(get_hdl_name(cell) + ' ') << ");\n";
1923 }
1924 }
1925 dec_indent();
1926
1927 log_debug("Debug information statistics for module `%s':\n", log_id(module));
1928 log_debug(" Public wires: %zu, of which:\n", count_public_wires);
1929 log_debug(" Member wires: %zu, of which:\n", count_member_wires);
1930 log_debug(" Undriven: %zu (incl. inputs)\n", count_undriven);
1931 log_debug(" Driven sync: %zu\n", count_driven_sync);
1932 log_debug(" Driven comb: %zu\n", count_driven_comb);
1933 log_debug(" Mixed driver: %zu\n", count_mixed_driver);
1934 if (!module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1935 log_debug(" Inline wires: %zu\n", count_inline_wires);
1936 log_debug(" Alias wires: %zu\n", count_alias_wires);
1937 log_debug(" Const wires: %zu\n", count_const_wires);
1938 log_debug(" Other wires: %zu%s\n", count_skipped_wires,
1939 count_skipped_wires > 0 ? " (debug unavailable)" : "");
1940 }
1941 }
1942
1943 void dump_metadata_map(const dict<RTLIL::IdString, RTLIL::Const> &metadata_map)
1944 {
1945 if (metadata_map.empty()) {
1946 f << "metadata_map()";
1947 return;
1948 }
1949 f << "metadata_map({\n";
1950 inc_indent();
1951 for (auto metadata_item : metadata_map) {
1952 if (!metadata_item.first.begins_with("\\"))
1953 continue;
1954 f << indent << "{ " << escape_cxx_string(metadata_item.first.str().substr(1)) << ", ";
1955 if (metadata_item.second.flags & RTLIL::CONST_FLAG_REAL) {
1956 f << std::showpoint << std::stod(metadata_item.second.decode_string()) << std::noshowpoint;
1957 } else if (metadata_item.second.flags & RTLIL::CONST_FLAG_STRING) {
1958 f << escape_cxx_string(metadata_item.second.decode_string());
1959 } else {
1960 f << metadata_item.second.as_int(/*is_signed=*/metadata_item.second.flags & RTLIL::CONST_FLAG_SIGNED);
1961 if (!(metadata_item.second.flags & RTLIL::CONST_FLAG_SIGNED))
1962 f << "u";
1963 }
1964 f << " },\n";
1965 }
1966 dec_indent();
1967 f << indent << "})";
1968 }
1969
1970 void dump_module_intf(RTLIL::Module *module)
1971 {
1972 dump_attrs(module);
1973 if (module->get_bool_attribute(ID(cxxrtl_blackbox))) {
1974 if (module->has_attribute(ID(cxxrtl_template)))
1975 f << indent << "template" << template_params(module, /*is_decl=*/true) << "\n";
1976 f << indent << "struct " << mangle(module) << " : public module {\n";
1977 inc_indent();
1978 for (auto wire : module->wires()) {
1979 if (wire->port_id != 0)
1980 dump_wire(wire, /*is_local=*/false);
1981 }
1982 f << "\n";
1983 f << indent << "bool eval() override {\n";
1984 dump_eval_method(module);
1985 f << indent << "}\n";
1986 f << "\n";
1987 f << indent << "bool commit() override {\n";
1988 dump_commit_method(module);
1989 f << indent << "}\n";
1990 f << "\n";
1991 if (debug_info) {
1992 f << indent << "void debug_info(debug_items &items, std::string path = \"\") override {\n";
1993 dump_debug_info_method(module);
1994 f << indent << "}\n";
1995 f << "\n";
1996 }
1997 f << indent << "static std::unique_ptr<" << mangle(module);
1998 f << template_params(module, /*is_decl=*/false) << "> ";
1999 f << "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
2000 dec_indent();
2001 f << indent << "}; // struct " << mangle(module) << "\n";
2002 f << "\n";
2003 if (blackbox_specializations.count(module)) {
2004 // If templated black boxes are used, the constructor of any module which includes the black box cell
2005 // (which calls the declared but not defined in the generated code `create` function) may only be used
2006 // if (a) the create function is defined in the same translation unit, or (b) the create function has
2007 // a forward-declared explicit specialization.
2008 //
2009 // Option (b) makes it possible to have the generated code and the black box implementation in different
2010 // translation units, which is convenient. Of course, its downside is that black boxes must predefine
2011 // a specialization for every combination of parameters the generated code may use; but since the main
2012 // purpose of templated black boxes is abstracting over datapath width, it is expected that there would
2013 // be very few such combinations anyway.
2014 for (auto specialization : blackbox_specializations[module]) {
2015 f << indent << "template<>\n";
2016 f << indent << "std::unique_ptr<" << mangle(module) << specialization << "> ";
2017 f << mangle(module) << specialization << "::";
2018 f << "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
2019 f << "\n";
2020 }
2021 }
2022 } else {
2023 f << indent << "struct " << mangle(module) << " : public module {\n";
2024 inc_indent();
2025 for (auto wire : module->wires())
2026 dump_wire(wire, /*is_local=*/false);
2027 for (auto wire : module->wires())
2028 dump_debug_wire(wire, /*is_local=*/false);
2029 bool has_memories = false;
2030 for (auto memory : module->memories) {
2031 dump_memory(module, memory.second);
2032 has_memories = true;
2033 }
2034 if (has_memories)
2035 f << "\n";
2036 bool has_cells = false;
2037 for (auto cell : module->cells()) {
2038 if (is_internal_cell(cell->type))
2039 continue;
2040 dump_attrs(cell);
2041 RTLIL::Module *cell_module = module->design->module(cell->type);
2042 log_assert(cell_module != nullptr);
2043 if (cell_module->get_bool_attribute(ID(cxxrtl_blackbox))) {
2044 f << indent << "std::unique_ptr<" << mangle(cell_module) << template_args(cell) << "> ";
2045 f << mangle(cell) << " = " << mangle(cell_module) << template_args(cell);
2046 f << "::create(" << escape_cxx_string(get_hdl_name(cell)) << ", ";
2047 dump_metadata_map(cell->parameters);
2048 f << ", ";
2049 dump_metadata_map(cell->attributes);
2050 f << ");\n";
2051 } else {
2052 f << indent << mangle(cell_module) << " " << mangle(cell) << ";\n";
2053 }
2054 has_cells = true;
2055 }
2056 if (has_cells)
2057 f << "\n";
2058 f << indent << mangle(module) << "() {}\n";
2059 if (has_cells) {
2060 f << indent << mangle(module) << "(adopt, " << mangle(module) << " other) :\n";
2061 bool first = true;
2062 for (auto cell : module->cells()) {
2063 if (is_internal_cell(cell->type))
2064 continue;
2065 if (first) {
2066 first = false;
2067 } else {
2068 f << ",\n";
2069 }
2070 RTLIL::Module *cell_module = module->design->module(cell->type);
2071 if (cell_module->get_bool_attribute(ID(cxxrtl_blackbox))) {
2072 f << indent << " " << mangle(cell) << "(std::move(other." << mangle(cell) << "))";
2073 } else {
2074 f << indent << " " << mangle(cell) << "(adopt {}, std::move(other." << mangle(cell) << "))";
2075 }
2076 }
2077 f << " {\n";
2078 inc_indent();
2079 for (auto cell : module->cells()) {
2080 if (is_internal_cell(cell->type))
2081 continue;
2082 RTLIL::Module *cell_module = module->design->module(cell->type);
2083 if (cell_module->get_bool_attribute(ID(cxxrtl_blackbox)))
2084 f << indent << mangle(cell) << "->reset();\n";
2085 }
2086 dec_indent();
2087 f << indent << "}\n";
2088 } else {
2089 f << indent << mangle(module) << "(adopt, " << mangle(module) << " other) {}\n";
2090 }
2091 f << "\n";
2092 f << indent << "void reset() override {\n";
2093 inc_indent();
2094 f << indent << "*this = " << mangle(module) << "(adopt {}, std::move(*this));\n";
2095 dec_indent();
2096 f << indent << "}\n";
2097 f << "\n";
2098 f << indent << "bool eval() override;\n";
2099 f << indent << "bool commit() override;\n";
2100 if (debug_info) {
2101 if (debug_eval) {
2102 f << "\n";
2103 f << indent << "void debug_eval();\n";
2104 for (auto wire : module->wires())
2105 if (debug_wire_types[wire].is_outline()) {
2106 f << indent << "debug_outline debug_eval_outline { std::bind(&"
2107 << mangle(module) << "::debug_eval, this) };\n";
2108 break;
2109 }
2110 }
2111 f << "\n";
2112 f << indent << "void debug_info(debug_items &items, std::string path = \"\") override;\n";
2113 }
2114 dec_indent();
2115 f << indent << "}; // struct " << mangle(module) << "\n";
2116 f << "\n";
2117 }
2118 }
2119
2120 void dump_module_impl(RTLIL::Module *module)
2121 {
2122 if (module->get_bool_attribute(ID(cxxrtl_blackbox)))
2123 return;
2124 f << indent << "bool " << mangle(module) << "::eval() {\n";
2125 dump_eval_method(module);
2126 f << indent << "}\n";
2127 f << "\n";
2128 f << indent << "bool " << mangle(module) << "::commit() {\n";
2129 dump_commit_method(module);
2130 f << indent << "}\n";
2131 f << "\n";
2132 if (debug_info) {
2133 if (debug_eval) {
2134 f << indent << "void " << mangle(module) << "::debug_eval() {\n";
2135 dump_debug_eval_method(module);
2136 f << indent << "}\n";
2137 f << "\n";
2138 }
2139 f << indent << "CXXRTL_EXTREMELY_COLD\n";
2140 f << indent << "void " << mangle(module) << "::debug_info(debug_items &items, std::string path) {\n";
2141 dump_debug_info_method(module);
2142 f << indent << "}\n";
2143 f << "\n";
2144 }
2145 }
2146
2147 void dump_design(RTLIL::Design *design)
2148 {
2149 RTLIL::Module *top_module = nullptr;
2150 std::vector<RTLIL::Module*> modules;
2151 TopoSort<RTLIL::Module*> topo_design;
2152 for (auto module : design->modules()) {
2153 if (!design->selected_module(module))
2154 continue;
2155 if (module->get_bool_attribute(ID(cxxrtl_blackbox)))
2156 modules.push_back(module); // cxxrtl blackboxes first
2157 if (module->get_blackbox_attribute() || module->get_bool_attribute(ID(cxxrtl_blackbox)))
2158 continue;
2159 if (module->get_bool_attribute(ID::top))
2160 top_module = module;
2161
2162 topo_design.node(module);
2163 for (auto cell : module->cells()) {
2164 if (is_internal_cell(cell->type) || is_cxxrtl_blackbox_cell(cell))
2165 continue;
2166 RTLIL::Module *cell_module = design->module(cell->type);
2167 log_assert(cell_module != nullptr);
2168 topo_design.edge(cell_module, module);
2169 }
2170 }
2171 bool no_loops = topo_design.sort();
2172 log_assert(no_loops);
2173 modules.insert(modules.end(), topo_design.sorted.begin(), topo_design.sorted.end());
2174
2175 if (split_intf) {
2176 // The only thing more depraved than include guards, is mangling filenames to turn them into include guards.
2177 std::string include_guard = design_ns + "_header";
2178 std::transform(include_guard.begin(), include_guard.end(), include_guard.begin(), ::toupper);
2179
2180 f << "#ifndef " << include_guard << "\n";
2181 f << "#define " << include_guard << "\n";
2182 f << "\n";
2183 if (top_module != nullptr && debug_info) {
2184 f << "#include <backends/cxxrtl/cxxrtl_capi.h>\n";
2185 f << "\n";
2186 f << "#ifdef __cplusplus\n";
2187 f << "extern \"C\" {\n";
2188 f << "#endif\n";
2189 f << "\n";
2190 f << "cxxrtl_toplevel " << design_ns << "_create();\n";
2191 f << "\n";
2192 f << "#ifdef __cplusplus\n";
2193 f << "}\n";
2194 f << "#endif\n";
2195 f << "\n";
2196 } else {
2197 f << "// The CXXRTL C API is not available because the design is built without debug information.\n";
2198 f << "\n";
2199 }
2200 f << "#ifdef __cplusplus\n";
2201 f << "\n";
2202 f << "#include <backends/cxxrtl/cxxrtl.h>\n";
2203 f << "\n";
2204 f << "using namespace cxxrtl;\n";
2205 f << "\n";
2206 f << "namespace " << design_ns << " {\n";
2207 f << "\n";
2208 for (auto module : modules)
2209 dump_module_intf(module);
2210 f << "} // namespace " << design_ns << "\n";
2211 f << "\n";
2212 f << "#endif // __cplusplus\n";
2213 f << "\n";
2214 f << "#endif\n";
2215 *intf_f << f.str(); f.str("");
2216 }
2217
2218 if (split_intf)
2219 f << "#include \"" << intf_filename << "\"\n";
2220 else
2221 f << "#include <backends/cxxrtl/cxxrtl.h>\n";
2222 f << "\n";
2223 f << "#if defined(CXXRTL_INCLUDE_CAPI_IMPL) || \\\n";
2224 f << " defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
2225 f << "#include <backends/cxxrtl/cxxrtl_capi.cc>\n";
2226 f << "#endif\n";
2227 f << "\n";
2228 f << "#if defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
2229 f << "#include <backends/cxxrtl/cxxrtl_vcd_capi.cc>\n";
2230 f << "#endif\n";
2231 f << "\n";
2232 f << "using namespace cxxrtl_yosys;\n";
2233 f << "\n";
2234 f << "namespace " << design_ns << " {\n";
2235 f << "\n";
2236 for (auto module : modules) {
2237 if (!split_intf)
2238 dump_module_intf(module);
2239 dump_module_impl(module);
2240 }
2241 f << "} // namespace " << design_ns << "\n";
2242 f << "\n";
2243 if (top_module != nullptr && debug_info) {
2244 f << "extern \"C\"\n";
2245 f << "cxxrtl_toplevel " << design_ns << "_create() {\n";
2246 inc_indent();
2247 std::string top_type = design_ns + "::" + mangle(top_module);
2248 f << indent << "return new _cxxrtl_toplevel { ";
2249 f << "std::unique_ptr<" << top_type << ">(new " + top_type + ")";
2250 f << " };\n";
2251 dec_indent();
2252 f << "}\n";
2253 }
2254
2255 *impl_f << f.str(); f.str("");
2256 }
2257
2258 // Edge-type sync rules require us to emit edge detectors, which require coordination between
2259 // eval and commit phases. To do this we need to collect them upfront.
2260 //
2261 // Note that the simulator commit phase operates at wire granularity but edge-type sync rules
2262 // operate at wire bit granularity; it is possible to have code similar to:
2263 // wire [3:0] clocks;
2264 // always @(posedge clocks[0]) ...
2265 // To handle this we track edge sensitivity both for wires and wire bits.
2266 void register_edge_signal(SigMap &sigmap, RTLIL::SigSpec signal, RTLIL::SyncType type)
2267 {
2268 signal = sigmap(signal);
2269 log_assert(signal.is_wire() && signal.is_bit());
2270 log_assert(type == RTLIL::STp || type == RTLIL::STn || type == RTLIL::STe);
2271
2272 RTLIL::SigBit sigbit = signal[0];
2273 if (!edge_types.count(sigbit))
2274 edge_types[sigbit] = type;
2275 else if (edge_types[sigbit] != type)
2276 edge_types[sigbit] = RTLIL::STe;
2277 edge_wires.insert(signal.as_wire());
2278 }
2279
2280 void analyze_design(RTLIL::Design *design)
2281 {
2282 bool has_feedback_arcs = false;
2283 bool has_buffered_comb_wires = false;
2284
2285 for (auto module : design->modules()) {
2286 if (!design->selected_module(module))
2287 continue;
2288
2289 SigMap &sigmap = sigmaps[module];
2290 sigmap.set(module);
2291
2292 if (module->get_bool_attribute(ID(cxxrtl_blackbox))) {
2293 for (auto port : module->ports) {
2294 RTLIL::Wire *wire = module->wire(port);
2295 if (wire->port_input && !wire->port_output) {
2296 wire_types[wire] = debug_wire_types[wire] = {WireType::MEMBER};
2297 } else if (wire->port_input || wire->port_output) {
2298 wire_types[wire] = debug_wire_types[wire] = {WireType::BUFFERED};
2299 }
2300 if (wire->has_attribute(ID(cxxrtl_edge))) {
2301 RTLIL::Const edge_attr = wire->attributes[ID(cxxrtl_edge)];
2302 if (!(edge_attr.flags & RTLIL::CONST_FLAG_STRING) || (int)edge_attr.decode_string().size() != GetSize(wire))
2303 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' is not a string with one character per bit.\n",
2304 log_id(module), log_signal(wire));
2305
2306 std::string edges = wire->get_string_attribute(ID(cxxrtl_edge));
2307 for (int i = 0; i < GetSize(wire); i++) {
2308 RTLIL::SigSpec wire_sig = wire;
2309 switch (edges[i]) {
2310 case '-': break;
2311 case 'p': register_edge_signal(sigmap, wire_sig[i], RTLIL::STp); break;
2312 case 'n': register_edge_signal(sigmap, wire_sig[i], RTLIL::STn); break;
2313 case 'a': register_edge_signal(sigmap, wire_sig[i], RTLIL::STe); break;
2314 default:
2315 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' contains specifiers "
2316 "other than '-', 'p', 'n', or 'a'.\n",
2317 log_id(module), log_signal(wire));
2318 }
2319 }
2320 }
2321 }
2322
2323 // Black boxes converge by default, since their implementations are quite unlikely to require
2324 // internal propagation of comb signals.
2325 eval_converges[module] = true;
2326 continue;
2327 }
2328
2329 // Construct a flow graph where each node is a basic computational operation generally corresponding
2330 // to a fragment of the RTLIL netlist.
2331 FlowGraph flow;
2332
2333 for (auto conn : module->connections())
2334 flow.add_node(conn);
2335
2336 dict<const RTLIL::Cell*, FlowGraph::Node*> memrw_cell_nodes;
2337 dict<std::pair<RTLIL::SigBit, const RTLIL::Memory*>,
2338 pool<const RTLIL::Cell*>> memwr_per_domain;
2339 for (auto cell : module->cells()) {
2340 if (!cell->known())
2341 log_cmd_error("Unknown cell `%s'.\n", log_id(cell->type));
2342
2343 RTLIL::Module *cell_module = design->module(cell->type);
2344 if (cell_module &&
2345 cell_module->get_blackbox_attribute() &&
2346 !cell_module->get_bool_attribute(ID(cxxrtl_blackbox)))
2347 log_cmd_error("External blackbox cell `%s' is not marked as a CXXRTL blackbox.\n", log_id(cell->type));
2348
2349 if (cell_module &&
2350 cell_module->get_bool_attribute(ID(cxxrtl_blackbox)) &&
2351 cell_module->get_bool_attribute(ID(cxxrtl_template)))
2352 blackbox_specializations[cell_module].insert(template_args(cell));
2353
2354 FlowGraph::Node *node = flow.add_node(cell);
2355
2356 // Various DFF cells are treated like posedge/negedge processes, see above for details.
2357 if (cell->type.in(ID($dff), ID($dffe), ID($adff), ID($adffe), ID($dffsr), ID($dffsre), ID($sdff), ID($sdffe), ID($sdffce))) {
2358 if (sigmap(cell->getPort(ID::CLK)).is_wire())
2359 register_edge_signal(sigmap, cell->getPort(ID::CLK),
2360 cell->parameters[ID::CLK_POLARITY].as_bool() ? RTLIL::STp : RTLIL::STn);
2361 }
2362 // Similar for memory port cells.
2363 if (cell->type.in(ID($memrd), ID($memwr))) {
2364 if (cell->getParam(ID::CLK_ENABLE).as_bool()) {
2365 if (sigmap(cell->getPort(ID::CLK)).is_wire())
2366 register_edge_signal(sigmap, cell->getPort(ID::CLK),
2367 cell->parameters[ID::CLK_POLARITY].as_bool() ? RTLIL::STp : RTLIL::STn);
2368 }
2369 memrw_cell_nodes[cell] = node;
2370 }
2371 // Optimize access to read-only memories.
2372 if (cell->type == ID($memwr))
2373 writable_memories.insert(module->memories[cell->getParam(ID::MEMID).decode_string()]);
2374 // Collect groups of memory write ports in the same domain.
2375 if (cell->type == ID($memwr) && cell->getParam(ID::CLK_ENABLE).as_bool() && cell->getPort(ID::CLK).is_wire()) {
2376 RTLIL::SigBit clk_bit = sigmap(cell->getPort(ID::CLK))[0];
2377 const RTLIL::Memory *memory = module->memories[cell->getParam(ID::MEMID).decode_string()];
2378 memwr_per_domain[{clk_bit, memory}].insert(cell);
2379 }
2380 // Handling of packed memories is delegated to the `memory_unpack` pass, so we can rely on the presence
2381 // of RTLIL memory objects and $memrd/$memwr/$meminit cells.
2382 if (cell->type.in(ID($mem)))
2383 log_assert(false);
2384 }
2385 for (auto cell : module->cells()) {
2386 // Collect groups of memory write ports read by every transparent read port.
2387 if (cell->type == ID($memrd) && cell->getParam(ID::CLK_ENABLE).as_bool() && cell->getPort(ID::CLK).is_wire() &&
2388 cell->getParam(ID::TRANSPARENT).as_bool()) {
2389 RTLIL::SigBit clk_bit = sigmap(cell->getPort(ID::CLK))[0];
2390 const RTLIL::Memory *memory = module->memories[cell->getParam(ID::MEMID).decode_string()];
2391 for (auto memwr_cell : memwr_per_domain[{clk_bit, memory}]) {
2392 transparent_for[cell].insert(memwr_cell);
2393 // Our implementation of transparent $memrd cells reads \EN, \ADDR and \DATA from every $memwr cell
2394 // in the same domain, which isn't directly visible in the netlist. Add these uses explicitly.
2395 flow.add_uses(memrw_cell_nodes[cell], memwr_cell->getPort(ID::EN));
2396 flow.add_uses(memrw_cell_nodes[cell], memwr_cell->getPort(ID::ADDR));
2397 flow.add_uses(memrw_cell_nodes[cell], memwr_cell->getPort(ID::DATA));
2398 }
2399 }
2400 }
2401
2402 for (auto proc : module->processes) {
2403 flow.add_node(proc.second);
2404
2405 for (auto sync : proc.second->syncs)
2406 switch (sync->type) {
2407 // Edge-type sync rules require pre-registration.
2408 case RTLIL::STp:
2409 case RTLIL::STn:
2410 case RTLIL::STe:
2411 register_edge_signal(sigmap, sync->signal, sync->type);
2412 break;
2413
2414 // Level-type sync rules require no special handling.
2415 case RTLIL::ST0:
2416 case RTLIL::ST1:
2417 case RTLIL::STa:
2418 break;
2419
2420 case RTLIL::STg:
2421 log_cmd_error("Global clock is not supported.\n");
2422
2423 // Handling of init-type sync rules is delegated to the `proc_init` pass, so we can use the wire
2424 // attribute regardless of input.
2425 case RTLIL::STi:
2426 log_assert(false);
2427 }
2428 }
2429
2430 // Construct a linear order of the flow graph that minimizes the amount of feedback arcs. A flow graph
2431 // without feedback arcs can generally be evaluated in a single pass, i.e. it always requires only
2432 // a single delta cycle.
2433 Scheduler<FlowGraph::Node> scheduler;
2434 dict<FlowGraph::Node*, Scheduler<FlowGraph::Node>::Vertex*, hash_ptr_ops> node_vertex_map;
2435 for (auto node : flow.nodes)
2436 node_vertex_map[node] = scheduler.add(node);
2437 for (auto node_comb_def : flow.node_comb_defs) {
2438 auto vertex = node_vertex_map[node_comb_def.first];
2439 for (auto wire : node_comb_def.second)
2440 for (auto succ_node : flow.wire_uses[wire]) {
2441 auto succ_vertex = node_vertex_map[succ_node];
2442 vertex->succs.insert(succ_vertex);
2443 succ_vertex->preds.insert(vertex);
2444 }
2445 }
2446
2447 // Find out whether the order includes any feedback arcs.
2448 std::vector<FlowGraph::Node*> node_order;
2449 pool<FlowGraph::Node*, hash_ptr_ops> evaluated_nodes;
2450 pool<const RTLIL::Wire*> feedback_wires;
2451 for (auto vertex : scheduler.schedule()) {
2452 auto node = vertex->data;
2453 node_order.push_back(node);
2454 // Any wire that is an output of node vo and input of node vi where vo is scheduled later than vi
2455 // is a feedback wire. Feedback wires indicate apparent logic loops in the design, which may be
2456 // caused by a true logic loop, but usually are a benign result of dependency tracking that works
2457 // on wire, not bit, level. Nevertheless, feedback wires cannot be unbuffered.
2458 evaluated_nodes.insert(node);
2459 for (auto wire : flow.node_comb_defs[node])
2460 for (auto succ_node : flow.wire_uses[wire])
2461 if (evaluated_nodes[succ_node])
2462 feedback_wires.insert(wire);
2463 }
2464 if (!feedback_wires.empty()) {
2465 has_feedback_arcs = true;
2466 log("Module `%s' contains feedback arcs through wires:\n", log_id(module));
2467 for (auto wire : feedback_wires)
2468 log(" %s\n", log_id(wire));
2469 }
2470
2471 // Conservatively assign wire types. Assignment of types BUFFERED and MEMBER is final, but assignment
2472 // of type LOCAL may be further refined to UNUSED or INLINE.
2473 for (auto wire : module->wires()) {
2474 auto &wire_type = wire_types[wire];
2475 wire_type = {WireType::BUFFERED};
2476
2477 if (feedback_wires[wire]) continue;
2478 if (wire->port_output && !module->get_bool_attribute(ID::top)) continue;
2479 if (!wire->name.isPublic() && !unbuffer_internal) continue;
2480 if (wire->name.isPublic() && !unbuffer_public) continue;
2481 if (flow.wire_sync_defs.count(wire) > 0) continue;
2482 wire_type = {WireType::MEMBER};
2483
2484 if (edge_wires[wire]) continue;
2485 if (wire->get_bool_attribute(ID::keep)) continue;
2486 if (wire->port_input || wire->port_output) continue;
2487 if (!wire->name.isPublic() && !localize_internal) continue;
2488 if (wire->name.isPublic() && !localize_public) continue;
2489 wire_type = {WireType::LOCAL};
2490 }
2491
2492 // Discover nodes reachable from primary outputs (i.e. members) and collect reachable wire users.
2493 pool<FlowGraph::Node*, hash_ptr_ops> worklist;
2494 for (auto node : flow.nodes) {
2495 if (node->type == FlowGraph::Node::Type::CELL_EVAL && is_effectful_cell(node->cell->type))
2496 worklist.insert(node); // node has effects
2497 else if (flow.node_sync_defs.count(node))
2498 worklist.insert(node); // node is a flip-flop
2499 else if (flow.node_comb_defs.count(node)) {
2500 for (auto wire : flow.node_comb_defs[node])
2501 if (wire_types[wire].is_member())
2502 worklist.insert(node); // node drives public wires
2503 }
2504 }
2505 dict<const RTLIL::Wire*, pool<FlowGraph::Node*, hash_ptr_ops>> live_wires;
2506 pool<FlowGraph::Node*, hash_ptr_ops> live_nodes;
2507 while (!worklist.empty()) {
2508 auto node = worklist.pop();
2509 live_nodes.insert(node);
2510 for (auto wire : flow.node_uses[node]) {
2511 live_wires[wire].insert(node);
2512 for (auto pred_node : flow.wire_comb_defs[wire])
2513 if (!live_nodes[pred_node])
2514 worklist.insert(pred_node);
2515 }
2516 }
2517
2518 // Refine wire types taking into account the amount of uses from reachable nodes only.
2519 for (auto wire : module->wires()) {
2520 auto &wire_type = wire_types[wire];
2521 if (!wire_type.is_local()) continue;
2522 if (!wire->name.isPublic() && !inline_internal) continue;
2523 if (wire->name.isPublic() && !inline_public) continue;
2524
2525 if (live_wires[wire].empty()) {
2526 wire_type = {WireType::UNUSED}; // wire never used
2527 } else if (flow.is_inlinable(wire, live_wires[wire])) {
2528 if (flow.wire_comb_defs[wire].size() > 1)
2529 log_cmd_error("Wire %s.%s has multiple drivers!\n", log_id(module), log_id(wire));
2530 log_assert(flow.wire_comb_defs[wire].size() == 1);
2531 FlowGraph::Node *node = *flow.wire_comb_defs[wire].begin();
2532 switch (node->type) {
2533 case FlowGraph::Node::Type::CELL_EVAL:
2534 if (!is_inlinable_cell(node->cell->type)) continue;
2535 wire_type = {WireType::INLINE, node->cell}; // wire replaced with cell
2536 break;
2537 case FlowGraph::Node::Type::CONNECT:
2538 wire_type = {WireType::INLINE, node->connect.second}; // wire replaced with sig
2539 break;
2540 default: continue;
2541 }
2542 live_nodes.erase(node);
2543 }
2544 }
2545
2546 // Emit reachable nodes in eval().
2547 for (auto node : node_order)
2548 if (live_nodes[node])
2549 schedule[module].push_back(*node);
2550
2551 // For maximum performance, the state of the simulation (which is the same as the set of its double buffered
2552 // wires, since using a singly buffered wire for any kind of state introduces a race condition) should contain
2553 // no wires attached to combinatorial outputs. Feedback wires, by definition, make that impossible. However,
2554 // it is possible that a design with no feedback arcs would end up with doubly buffered wires in such cases
2555 // as a wire with multiple drivers where one of them is combinatorial and the other is synchronous. Such designs
2556 // also require more than one delta cycle to converge.
2557 pool<const RTLIL::Wire*> buffered_comb_wires;
2558 for (auto wire : module->wires())
2559 if (wire_types[wire].is_buffered() && !feedback_wires[wire] && flow.wire_comb_defs[wire].size() > 0)
2560 buffered_comb_wires.insert(wire);
2561 if (!buffered_comb_wires.empty()) {
2562 has_buffered_comb_wires = true;
2563 log("Module `%s' contains buffered combinatorial wires:\n", log_id(module));
2564 for (auto wire : buffered_comb_wires)
2565 log(" %s\n", log_id(wire));
2566 }
2567
2568 // Record whether eval() requires only one delta cycle in this module.
2569 eval_converges[module] = feedback_wires.empty() && buffered_comb_wires.empty();
2570
2571 if (debug_info) {
2572 // Annotate wire bits with the type of their driver; this is exposed in the debug metadata.
2573 for (auto item : flow.bit_has_state)
2574 bit_has_state.insert(item);
2575
2576 // Assign debug information wire types to public wires according to the chosen debug level.
2577 // Unlike with optimized wire types, all assignments here are final.
2578 for (auto wire : module->wires()) {
2579 const auto &wire_type = wire_types[wire];
2580 auto &debug_wire_type = debug_wire_types[wire];
2581 if (wire_type.type == WireType::UNUSED) continue;
2582 if (!wire->name.isPublic()) continue;
2583
2584 if (!debug_info) continue;
2585 if (wire->port_input || wire_type.is_buffered())
2586 debug_wire_type = wire_type; // wire contains state
2587
2588 if (!debug_member) continue;
2589 if (wire_type.is_member())
2590 debug_wire_type = wire_type; // wire is a member
2591
2592 if (!debug_alias) continue;
2593 const RTLIL::Wire *it = wire;
2594 while (flow.is_inlinable(it)) {
2595 log_assert(flow.wire_comb_defs[it].size() == 1);
2596 FlowGraph::Node *node = *flow.wire_comb_defs[it].begin();
2597 if (node->type != FlowGraph::Node::Type::CONNECT) break; // not an alias
2598 RTLIL::SigSpec rhs = node->connect.second;
2599 if (rhs.is_fully_const()) {
2600 debug_wire_type = {WireType::CONST, rhs}; // wire replaced with const
2601 } else if (rhs.is_wire()) {
2602 if (wire_types[rhs.as_wire()].is_member())
2603 debug_wire_type = {WireType::ALIAS, rhs}; // wire replaced with wire
2604 else if (debug_eval && rhs.as_wire()->name.isPublic())
2605 debug_wire_type = {WireType::ALIAS, rhs}; // wire replaced with outline
2606 it = rhs.as_wire(); // and keep looking
2607 continue;
2608 }
2609 break;
2610 }
2611
2612 if (!debug_eval) continue;
2613 if (!debug_wire_type.is_exact() && !wire_type.is_member())
2614 debug_wire_type = {WireType::OUTLINE}; // wire is local or inlined
2615 }
2616
2617 // Discover nodes reachable from primary outputs (i.e. outlines) up until primary inputs (i.e. members)
2618 // and collect reachable wire users.
2619 pool<FlowGraph::Node*, hash_ptr_ops> worklist;
2620 for (auto node : flow.nodes) {
2621 if (flow.node_comb_defs.count(node))
2622 for (auto wire : flow.node_comb_defs[node])
2623 if (debug_wire_types[wire].is_outline())
2624 worklist.insert(node); // node drives outline
2625 }
2626 dict<const RTLIL::Wire*, pool<FlowGraph::Node*, hash_ptr_ops>> debug_live_wires;
2627 pool<FlowGraph::Node*, hash_ptr_ops> debug_live_nodes;
2628 while (!worklist.empty()) {
2629 auto node = worklist.pop();
2630 debug_live_nodes.insert(node);
2631 for (auto wire : flow.node_uses[node]) {
2632 if (debug_wire_types[wire].is_member())
2633 continue; // node uses member
2634 if (debug_wire_types[wire].is_exact())
2635 continue; // node uses alias or const
2636 debug_live_wires[wire].insert(node);
2637 for (auto pred_node : flow.wire_comb_defs[wire])
2638 if (!debug_live_nodes[pred_node])
2639 worklist.insert(pred_node);
2640 }
2641 }
2642
2643 // Assign debug information wire types to internal wires used by reachable nodes. This is similar
2644 // to refining optimized wire types with the exception that the assignments here are first and final.
2645 for (auto wire : module->wires()) {
2646 const auto &wire_type = wire_types[wire];
2647 auto &debug_wire_type = debug_wire_types[wire];
2648 if (wire->name.isPublic()) continue;
2649
2650 if (live_wires[wire].empty() || debug_live_wires[wire].empty()) {
2651 continue; // wire never used
2652 } else if (flow.is_inlinable(wire, debug_live_wires[wire])) {
2653 log_assert(flow.wire_comb_defs[wire].size() == 1);
2654 FlowGraph::Node *node = *flow.wire_comb_defs[wire].begin();
2655 switch (node->type) {
2656 case FlowGraph::Node::Type::CELL_EVAL:
2657 if (!is_inlinable_cell(node->cell->type)) continue;
2658 debug_wire_type = {WireType::INLINE, node->cell}; // wire replaced with cell
2659 break;
2660 case FlowGraph::Node::Type::CONNECT:
2661 debug_wire_type = {WireType::INLINE, node->connect.second}; // wire replaced with sig
2662 break;
2663 default: continue;
2664 }
2665 debug_live_nodes.erase(node);
2666 } else if (wire_type.is_local()) {
2667 debug_wire_type = {WireType::LOCAL}; // wire not inlinable
2668 } else {
2669 log_assert(wire_type.is_member());
2670 debug_wire_type = wire_type; // wire is a member
2671 }
2672 }
2673
2674 // Emit reachable nodes in debug_eval().
2675 for (auto node : node_order)
2676 if (debug_live_nodes[node])
2677 debug_schedule[module].push_back(*node);
2678 }
2679 }
2680 if (has_feedback_arcs || has_buffered_comb_wires) {
2681 // Although both non-feedback buffered combinatorial wires and apparent feedback wires may be eliminated
2682 // by optimizing the design, if after `proc; flatten` there are any feedback wires remaining, it is very
2683 // likely that these feedback wires are indicative of a true logic loop, so they get emphasized in the message.
2684 const char *why_pessimistic = nullptr;
2685 if (has_feedback_arcs)
2686 why_pessimistic = "feedback wires";
2687 else if (has_buffered_comb_wires)
2688 why_pessimistic = "buffered combinatorial wires";
2689 log_warning("Design contains %s, which require delta cycles during evaluation.\n", why_pessimistic);
2690 if (!run_flatten)
2691 log("Flattening may eliminate %s from the design.\n", why_pessimistic);
2692 if (!run_proc)
2693 log("Converting processes to netlists may eliminate %s from the design.\n", why_pessimistic);
2694 }
2695 }
2696
2697 void check_design(RTLIL::Design *design, bool &has_top, bool &has_sync_init, bool &has_packed_mem)
2698 {
2699 has_sync_init = has_packed_mem = has_top = false;
2700
2701 for (auto module : design->modules()) {
2702 if (module->get_blackbox_attribute() && !module->has_attribute(ID(cxxrtl_blackbox)))
2703 continue;
2704
2705 if (!design->selected_whole_module(module))
2706 if (design->selected_module(module))
2707 log_cmd_error("Can't handle partially selected module `%s'!\n", id2cstr(module->name));
2708 if (!design->selected_module(module))
2709 continue;
2710
2711 if (module->get_bool_attribute(ID::top))
2712 has_top = true;
2713
2714 for (auto proc : module->processes)
2715 for (auto sync : proc.second->syncs)
2716 if (sync->type == RTLIL::STi)
2717 has_sync_init = true;
2718
2719 // The Mem constructor also checks for well-formedness of $meminit cells, if any.
2720 for (auto &mem : Mem::get_all_memories(module))
2721 if (mem.packed)
2722 has_packed_mem = true;
2723 }
2724 }
2725
2726 void prepare_design(RTLIL::Design *design)
2727 {
2728 bool did_anything = false;
2729 bool has_top, has_sync_init, has_packed_mem;
2730 log_push();
2731 check_design(design, has_top, has_sync_init, has_packed_mem);
2732 if (run_hierarchy && !has_top) {
2733 Pass::call(design, "hierarchy -auto-top");
2734 did_anything = true;
2735 }
2736 if (run_flatten) {
2737 Pass::call(design, "flatten");
2738 did_anything = true;
2739 }
2740 if (run_proc) {
2741 Pass::call(design, "proc");
2742 did_anything = true;
2743 } else if (has_sync_init) {
2744 // We're only interested in proc_init, but it depends on proc_prune and proc_clean, so call those
2745 // in case they weren't already. (This allows `yosys foo.v -o foo.cc` to work.)
2746 Pass::call(design, "proc_prune");
2747 Pass::call(design, "proc_clean");
2748 Pass::call(design, "proc_init");
2749 did_anything = true;
2750 }
2751 if (has_packed_mem) {
2752 Pass::call(design, "memory_unpack");
2753 did_anything = true;
2754 }
2755 // Recheck the design if it was modified.
2756 if (did_anything)
2757 check_design(design, has_top, has_sync_init, has_packed_mem);
2758 log_assert(has_top && !has_sync_init && !has_packed_mem);
2759 log_pop();
2760 if (did_anything)
2761 log_spacer();
2762 analyze_design(design);
2763 }
2764 };
2765
2766 struct CxxrtlBackend : public Backend {
2767 static const int DEFAULT_OPT_LEVEL = 6;
2768 static const int DEFAULT_DEBUG_LEVEL = 4;
2769
2770 CxxrtlBackend() : Backend("cxxrtl", "convert design to C++ RTL simulation") { }
2771 void help() override
2772 {
2773 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
2774 log("\n");
2775 log(" write_cxxrtl [options] [filename]\n");
2776 log("\n");
2777 log("Write C++ code that simulates the design. The generated code requires a driver\n");
2778 log("that instantiates the design, toggles its clock, and interacts with its ports.\n");
2779 log("\n");
2780 log("The following driver may be used as an example for a design with a single clock\n");
2781 log("driving rising edge triggered flip-flops:\n");
2782 log("\n");
2783 log(" #include \"top.cc\"\n");
2784 log("\n");
2785 log(" int main() {\n");
2786 log(" cxxrtl_design::p_top top;\n");
2787 log(" top.step();\n");
2788 log(" while (1) {\n");
2789 log(" /* user logic */\n");
2790 log(" top.p_clk.set(false);\n");
2791 log(" top.step();\n");
2792 log(" top.p_clk.set(true);\n");
2793 log(" top.step();\n");
2794 log(" }\n");
2795 log(" }\n");
2796 log("\n");
2797 log("Note that CXXRTL simulations, just like the hardware they are simulating, are\n");
2798 log("subject to race conditions. If, in the example above, the user logic would run\n");
2799 log("simultaneously with the rising edge of the clock, the design would malfunction.\n");
2800 log("\n");
2801 log("This backend supports replacing parts of the design with black boxes implemented\n");
2802 log("in C++. If a module marked as a CXXRTL black box, its implementation is ignored,\n");
2803 log("and the generated code consists only of an interface and a factory function.\n");
2804 log("The driver must implement the factory function that creates an implementation of\n");
2805 log("the black box, taking into account the parameters it is instantiated with.\n");
2806 log("\n");
2807 log("For example, the following Verilog code defines a CXXRTL black box interface for\n");
2808 log("a synchronous debug sink:\n");
2809 log("\n");
2810 log(" (* cxxrtl_blackbox *)\n");
2811 log(" module debug(...);\n");
2812 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2813 log(" input en;\n");
2814 log(" input [7:0] i_data;\n");
2815 log(" (* cxxrtl_sync *) output [7:0] o_data;\n");
2816 log(" endmodule\n");
2817 log("\n");
2818 log("For this HDL interface, this backend will generate the following C++ interface:\n");
2819 log("\n");
2820 log(" struct bb_p_debug : public module {\n");
2821 log(" value<1> p_clk;\n");
2822 log(" bool posedge_p_clk() const { /* ... */ }\n");
2823 log(" value<1> p_en;\n");
2824 log(" value<8> p_i_data;\n");
2825 log(" wire<8> p_o_data;\n");
2826 log("\n");
2827 log(" bool eval() override;\n");
2828 log(" bool commit() override;\n");
2829 log("\n");
2830 log(" static std::unique_ptr<bb_p_debug>\n");
2831 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2832 log(" };\n");
2833 log("\n");
2834 log("The `create' function must be implemented by the driver. For example, it could\n");
2835 log("always provide an implementation logging the values to standard error stream:\n");
2836 log("\n");
2837 log(" namespace cxxrtl_design {\n");
2838 log("\n");
2839 log(" struct stderr_debug : public bb_p_debug {\n");
2840 log(" bool eval() override {\n");
2841 log(" if (posedge_p_clk() && p_en)\n");
2842 log(" fprintf(stderr, \"debug: %%02x\\n\", p_i_data.data[0]);\n");
2843 log(" p_o_data.next = p_i_data;\n");
2844 log(" return bb_p_debug::eval();\n");
2845 log(" }\n");
2846 log(" };\n");
2847 log("\n");
2848 log(" std::unique_ptr<bb_p_debug>\n");
2849 log(" bb_p_debug::create(std::string name, cxxrtl::metadata_map parameters,\n");
2850 log(" cxxrtl::metadata_map attributes) {\n");
2851 log(" return std::make_unique<stderr_debug>();\n");
2852 log(" }\n");
2853 log("\n");
2854 log(" }\n");
2855 log("\n");
2856 log("For complex applications of black boxes, it is possible to parameterize their\n");
2857 log("port widths. For example, the following Verilog code defines a CXXRTL black box\n");
2858 log("interface for a configurable width debug sink:\n");
2859 log("\n");
2860 log(" (* cxxrtl_blackbox, cxxrtl_template = \"WIDTH\" *)\n");
2861 log(" module debug(...);\n");
2862 log(" parameter WIDTH = 8;\n");
2863 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2864 log(" input en;\n");
2865 log(" (* cxxrtl_width = \"WIDTH\" *) input [WIDTH - 1:0] i_data;\n");
2866 log(" (* cxxrtl_width = \"WIDTH\" *) output [WIDTH - 1:0] o_data;\n");
2867 log(" endmodule\n");
2868 log("\n");
2869 log("For this parametric HDL interface, this backend will generate the following C++\n");
2870 log("interface (only the differences are shown):\n");
2871 log("\n");
2872 log(" template<size_t WIDTH>\n");
2873 log(" struct bb_p_debug : public module {\n");
2874 log(" // ...\n");
2875 log(" value<WIDTH> p_i_data;\n");
2876 log(" wire<WIDTH> p_o_data;\n");
2877 log(" // ...\n");
2878 log(" static std::unique_ptr<bb_p_debug<WIDTH>>\n");
2879 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2880 log(" };\n");
2881 log("\n");
2882 log("The `create' function must be implemented by the driver, specialized for every\n");
2883 log("possible combination of template parameters. (Specialization is necessary to\n");
2884 log("enable separate compilation of generated code and black box implementations.)\n");
2885 log("\n");
2886 log(" template<size_t SIZE>\n");
2887 log(" struct stderr_debug : public bb_p_debug<SIZE> {\n");
2888 log(" // ...\n");
2889 log(" };\n");
2890 log("\n");
2891 log(" template<>\n");
2892 log(" std::unique_ptr<bb_p_debug<8>>\n");
2893 log(" bb_p_debug<8>::create(std::string name, cxxrtl::metadata_map parameters,\n");
2894 log(" cxxrtl::metadata_map attributes) {\n");
2895 log(" return std::make_unique<stderr_debug<8>>();\n");
2896 log(" }\n");
2897 log("\n");
2898 log("The following attributes are recognized by this backend:\n");
2899 log("\n");
2900 log(" cxxrtl_blackbox\n");
2901 log(" only valid on modules. if specified, the module contents are ignored,\n");
2902 log(" and the generated code includes only the module interface and a factory\n");
2903 log(" function, which will be called to instantiate the module.\n");
2904 log("\n");
2905 log(" cxxrtl_edge\n");
2906 log(" only valid on inputs of black boxes. must be one of \"p\", \"n\", \"a\".\n");
2907 log(" if specified on signal `clk`, the generated code includes edge detectors\n");
2908 log(" `posedge_p_clk()` (if \"p\"), `negedge_p_clk()` (if \"n\"), or both (if\n");
2909 log(" \"a\"), simplifying implementation of clocked black boxes.\n");
2910 log("\n");
2911 log(" cxxrtl_template\n");
2912 log(" only valid on black boxes. must contain a space separated sequence of\n");
2913 log(" identifiers that have a corresponding black box parameters. for each\n");
2914 log(" of them, the generated code includes a `size_t` template parameter.\n");
2915 log("\n");
2916 log(" cxxrtl_width\n");
2917 log(" only valid on ports of black boxes. must be a constant expression, which\n");
2918 log(" is directly inserted into generated code.\n");
2919 log("\n");
2920 log(" cxxrtl_comb, cxxrtl_sync\n");
2921 log(" only valid on outputs of black boxes. if specified, indicates that every\n");
2922 log(" bit of the output port is driven, correspondingly, by combinatorial or\n");
2923 log(" synchronous logic. this knowledge is used for scheduling optimizations.\n");
2924 log(" if neither is specified, the output will be pessimistically treated as\n");
2925 log(" driven by both combinatorial and synchronous logic.\n");
2926 log("\n");
2927 log("The following options are supported by this backend:\n");
2928 log("\n");
2929 log(" -header\n");
2930 log(" generate separate interface (.h) and implementation (.cc) files.\n");
2931 log(" if specified, the backend must be called with a filename, and filename\n");
2932 log(" of the interface is derived from filename of the implementation.\n");
2933 log(" otherwise, interface and implementation are generated together.\n");
2934 log("\n");
2935 log(" -namespace <ns-name>\n");
2936 log(" place the generated code into namespace <ns-name>. if not specified,\n");
2937 log(" \"cxxrtl_design\" is used.\n");
2938 log("\n");
2939 log(" -nohierarchy\n");
2940 log(" use design hierarchy as-is. in most designs, a top module should be\n");
2941 log(" present as it is exposed through the C API and has unbuffered outputs\n");
2942 log(" for improved performance; it will be determined automatically if absent.\n");
2943 log("\n");
2944 log(" -noflatten\n");
2945 log(" don't flatten the design. fully flattened designs can evaluate within\n");
2946 log(" one delta cycle if they have no combinatorial feedback.\n");
2947 log(" note that the debug interface and waveform dumps use full hierarchical\n");
2948 log(" names for all wires even in flattened designs.\n");
2949 log("\n");
2950 log(" -noproc\n");
2951 log(" don't convert processes to netlists. in most designs, converting\n");
2952 log(" processes significantly improves evaluation performance at the cost of\n");
2953 log(" slight increase in compilation time.\n");
2954 log("\n");
2955 log(" -O <level>\n");
2956 log(" set the optimization level. the default is -O%d. higher optimization\n", DEFAULT_OPT_LEVEL);
2957 log(" levels dramatically decrease compile and run time, and highest level\n");
2958 log(" possible for a design should be used.\n");
2959 log("\n");
2960 log(" -O0\n");
2961 log(" no optimization.\n");
2962 log("\n");
2963 log(" -O1\n");
2964 log(" unbuffer internal wires if possible.\n");
2965 log("\n");
2966 log(" -O2\n");
2967 log(" like -O1, and localize internal wires if possible.\n");
2968 log("\n");
2969 log(" -O3\n");
2970 log(" like -O2, and inline internal wires if possible.\n");
2971 log("\n");
2972 log(" -O4\n");
2973 log(" like -O3, and unbuffer public wires not marked (*keep*) if possible.\n");
2974 log("\n");
2975 log(" -O5\n");
2976 log(" like -O4, and localize public wires not marked (*keep*) if possible.\n");
2977 log("\n");
2978 log(" -O6\n");
2979 log(" like -O5, and inline public wires not marked (*keep*) if possible.\n");
2980 log("\n");
2981 log(" -g <level>\n");
2982 log(" set the debug level. the default is -g%d. higher debug levels provide\n", DEFAULT_DEBUG_LEVEL);
2983 log(" more visibility and generate more code, but do not pessimize evaluation.\n");
2984 log("\n");
2985 log(" -g0\n");
2986 log(" no debug information. the C API is disabled.\n");
2987 log("\n");
2988 log(" -g1\n");
2989 log(" include bare minimum of debug information necessary to access all design\n");
2990 log(" state. the C API is enabled.\n");
2991 log("\n");
2992 log(" -g2\n");
2993 log(" like -g1, but include debug information for all public wires that are\n");
2994 log(" directly accessible through the C++ interface.\n");
2995 log("\n");
2996 log(" -g3\n");
2997 log(" like -g2, and include debug information for public wires that are tied\n");
2998 log(" to a constant or another public wire.\n");
2999 log("\n");
3000 log(" -g4\n");
3001 log(" like -g3, and compute debug information on demand for all public wires\n");
3002 log(" that were optimized out.\n");
3003 log("\n");
3004 }
3005
3006 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) override
3007 {
3008 bool nohierarchy = false;
3009 bool noflatten = false;
3010 bool noproc = false;
3011 int opt_level = DEFAULT_OPT_LEVEL;
3012 int debug_level = DEFAULT_DEBUG_LEVEL;
3013 CxxrtlWorker worker;
3014
3015 log_header(design, "Executing CXXRTL backend.\n");
3016
3017 size_t argidx;
3018 for (argidx = 1; argidx < args.size(); argidx++)
3019 {
3020 if (args[argidx] == "-nohierarchy") {
3021 nohierarchy = true;
3022 continue;
3023 }
3024 if (args[argidx] == "-noflatten") {
3025 noflatten = true;
3026 continue;
3027 }
3028 if (args[argidx] == "-noproc") {
3029 noproc = true;
3030 continue;
3031 }
3032 if (args[argidx] == "-Og") {
3033 log_warning("The `-Og` option has been removed. Use `-g3` instead for complete "
3034 "design coverage regardless of optimization level.\n");
3035 continue;
3036 }
3037 if (args[argidx] == "-O" && argidx+1 < args.size() && args[argidx+1] == "g") {
3038 argidx++;
3039 log_warning("The `-Og` option has been removed. Use `-g3` instead for complete "
3040 "design coverage regardless of optimization level.\n");
3041 continue;
3042 }
3043 if (args[argidx] == "-O" && argidx+1 < args.size()) {
3044 opt_level = std::stoi(args[++argidx]);
3045 continue;
3046 }
3047 if (args[argidx].substr(0, 2) == "-O" && args[argidx].size() == 3 && isdigit(args[argidx][2])) {
3048 opt_level = std::stoi(args[argidx].substr(2));
3049 continue;
3050 }
3051 if (args[argidx] == "-g" && argidx+1 < args.size()) {
3052 debug_level = std::stoi(args[++argidx]);
3053 continue;
3054 }
3055 if (args[argidx].substr(0, 2) == "-g" && args[argidx].size() == 3 && isdigit(args[argidx][2])) {
3056 debug_level = std::stoi(args[argidx].substr(2));
3057 continue;
3058 }
3059 if (args[argidx] == "-header") {
3060 worker.split_intf = true;
3061 continue;
3062 }
3063 if (args[argidx] == "-namespace" && argidx+1 < args.size()) {
3064 worker.design_ns = args[++argidx];
3065 continue;
3066 }
3067 break;
3068 }
3069 extra_args(f, filename, args, argidx);
3070
3071 worker.run_hierarchy = !nohierarchy;
3072 worker.run_flatten = !noflatten;
3073 worker.run_proc = !noproc;
3074 switch (opt_level) {
3075 // the highest level here must match DEFAULT_OPT_LEVEL
3076 case 6:
3077 worker.inline_public = true;
3078 YS_FALLTHROUGH
3079 case 5:
3080 worker.localize_public = true;
3081 YS_FALLTHROUGH
3082 case 4:
3083 worker.unbuffer_public = true;
3084 YS_FALLTHROUGH
3085 case 3:
3086 worker.inline_internal = true;
3087 YS_FALLTHROUGH
3088 case 2:
3089 worker.localize_internal = true;
3090 YS_FALLTHROUGH
3091 case 1:
3092 worker.unbuffer_internal = true;
3093 YS_FALLTHROUGH
3094 case 0:
3095 break;
3096 default:
3097 log_cmd_error("Invalid optimization level %d.\n", opt_level);
3098 }
3099 switch (debug_level) {
3100 // the highest level here must match DEFAULT_DEBUG_LEVEL
3101 case 4:
3102 worker.debug_eval = true;
3103 YS_FALLTHROUGH
3104 case 3:
3105 worker.debug_alias = true;
3106 YS_FALLTHROUGH
3107 case 2:
3108 worker.debug_member = true;
3109 YS_FALLTHROUGH
3110 case 1:
3111 worker.debug_info = true;
3112 YS_FALLTHROUGH
3113 case 0:
3114 break;
3115 default:
3116 log_cmd_error("Invalid debug information level %d.\n", debug_level);
3117 }
3118
3119 std::ofstream intf_f;
3120 if (worker.split_intf) {
3121 if (filename == "<stdout>")
3122 log_cmd_error("Option -header must be used with a filename.\n");
3123
3124 worker.intf_filename = filename.substr(0, filename.rfind('.')) + ".h";
3125 intf_f.open(worker.intf_filename, std::ofstream::trunc);
3126 if (intf_f.fail())
3127 log_cmd_error("Can't open file `%s' for writing: %s\n",
3128 worker.intf_filename.c_str(), strerror(errno));
3129
3130 worker.intf_f = &intf_f;
3131 }
3132 worker.impl_f = f;
3133
3134 worker.prepare_design(design);
3135 worker.dump_design(design);
3136 }
3137 } CxxrtlBackend;
3138
3139 PRIVATE_NAMESPACE_END