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