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