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