2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2019-2020 whitequark <whitequark@whitequark.org>
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.
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.
20 #include "kernel/rtlil.h"
21 #include "kernel/register.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/utils.h"
24 #include "kernel/celltypes.h"
25 #include "kernel/mem.h"
26 #include "kernel/log.h"
29 PRIVATE_NAMESPACE_BEGIN
32 // Peter Eades; Xuemin Lin; W. F. Smyth, "A Fast Effective Heuristic For The Feedback Arc Set Problem"
33 // Information Processing Letters, Vol. 47, pp 319-323, 1993
34 // https://pdfs.semanticscholar.org/c7ed/d9acce96ca357876540e19664eb9d976637f.pdf
36 // A topological sort (on a cell/wire graph) is always possible in a fully flattened RTLIL design without
37 // processes or logic loops where every wire has a single driver. Logic loops are illegal in RTLIL and wires
38 // with multiple drivers can be split by the `splitnets` pass; however, interdependencies between processes
39 // or module instances can create strongly connected components without introducing evaluation nondeterminism.
40 // We wish to support designs with such benign SCCs (as well as designs with multiple drivers per wire), so
41 // we sort the graph in a way that minimizes feedback arcs. If there are no feedback arcs in the sorted graph,
42 // then a more efficient evaluation method is possible, since eval() will always immediately converge.
48 pool
<Vertex
*, hash_ptr_ops
> preds
, succs
;
50 Vertex() : data(NULL
), prev(this), next(this) {}
51 Vertex(T
*data
) : data(data
), prev(NULL
), next(NULL
) {}
55 log_assert(data
== NULL
);
57 log_assert(prev
== next
);
63 void link(Vertex
*list
)
65 log_assert(prev
== NULL
&& next
== NULL
);
68 list
->prev
->next
= this;
74 log_assert(prev
->next
== this && next
->prev
== this);
82 return succs
.size() - preds
.size();
86 std::vector
<Vertex
*> vertices
;
87 Vertex
*sources
= new Vertex
;
88 Vertex
*sinks
= new Vertex
;
89 dict
<int, Vertex
*> bins
;
97 for (auto vertex
: vertices
)
103 Vertex
*vertex
= new Vertex(data
);
104 vertices
.push_back(vertex
);
108 void relink(Vertex
*vertex
)
110 if (vertex
->succs
.empty())
112 else if (vertex
->preds
.empty())
113 vertex
->link(sources
);
115 int delta
= vertex
->delta();
116 if (!bins
.count(delta
))
117 bins
[delta
] = new Vertex
;
118 vertex
->link(bins
[delta
]);
122 Vertex
*remove(Vertex
*vertex
)
125 for (auto pred
: vertex
->preds
) {
128 log_assert(pred
->succs
[vertex
]);
130 pred
->succs
.erase(vertex
);
133 for (auto succ
: vertex
->succs
) {
136 log_assert(succ
->preds
[vertex
]);
138 succ
->preds
.erase(vertex
);
141 vertex
->preds
.clear();
142 vertex
->succs
.clear();
146 std::vector
<Vertex
*> schedule()
148 std::vector
<Vertex
*> s1
, s2r
;
149 for (auto vertex
: vertices
)
151 bool bins_empty
= false;
152 while (!(sinks
->empty() && sources
->empty() && bins_empty
)) {
153 while (!sinks
->empty())
154 s2r
.push_back(remove(sinks
->next
));
155 while (!sources
->empty())
156 s1
.push_back(remove(sources
->next
));
157 // Choosing u in this implementation isn't O(1), but the paper handwaves which data structure they suggest
158 // using to get O(1) relinking *and* find-max-key ("it is clear"... no it isn't), so this code uses a very
159 // naive implementation of find-max-key.
161 bins
.template sort
<std::greater
<int>>();
162 for (auto bin
: bins
) {
163 if (!bin
.second
->empty()) {
165 s1
.push_back(remove(bin
.second
->next
));
170 s1
.insert(s1
.end(), s2r
.rbegin(), s2r
.rend());
175 bool is_unary_cell(RTLIL::IdString type
)
178 ID($
not), ID($logic_not
), ID($reduce_and
), ID($reduce_or
), ID($reduce_xor
), ID($reduce_xnor
), ID($reduce_bool
),
182 bool is_binary_cell(RTLIL::IdString type
)
185 ID($
and), ID($
or), ID($
xor), ID($xnor
), ID($logic_and
), ID($logic_or
),
186 ID($shl
), ID($sshl
), ID($shr
), ID($sshr
), ID($shift
), ID($shiftx
),
187 ID($eq
), ID($ne
), ID($eqx
), ID($nex
), ID($gt
), ID($ge
), ID($lt
), ID($le
),
188 ID($add
), ID($sub
), ID($mul
), ID($div
), ID($mod
));
191 bool is_extending_cell(RTLIL::IdString type
)
194 ID($logic_not
), ID($logic_and
), ID($logic_or
),
195 ID($reduce_and
), ID($reduce_or
), ID($reduce_xor
), ID($reduce_xnor
), ID($reduce_bool
));
198 bool is_inlinable_cell(RTLIL::IdString type
)
200 return is_unary_cell(type
) || is_binary_cell(type
) || type
.in(
201 ID($mux
), ID($concat
), ID($slice
), ID($pmux
));
204 bool is_ff_cell(RTLIL::IdString type
)
207 ID($dff
), ID($dffe
), ID($sdff
), ID($sdffe
), ID($sdffce
),
208 ID($adff
), ID($adffe
), ID($dffsr
), ID($dffsre
),
209 ID($dlatch
), ID($adlatch
), ID($dlatchsr
), ID($sr
));
212 bool is_internal_cell(RTLIL::IdString type
)
214 return !type
.isPublic() && !type
.begins_with("$paramod");
217 bool is_cxxrtl_blackbox_cell(const RTLIL::Cell
*cell
)
219 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
220 log_assert(cell_module
!= nullptr);
221 return cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
));
224 enum class CxxrtlPortType
{
225 UNKNOWN
= 0, // or mixed comb/sync
230 CxxrtlPortType
cxxrtl_port_type(const RTLIL::Cell
*cell
, RTLIL::IdString port
)
232 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
233 if (cell_module
== nullptr || !cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
234 return CxxrtlPortType::UNKNOWN
;
235 RTLIL::Wire
*cell_output_wire
= cell_module
->wire(port
);
236 log_assert(cell_output_wire
!= nullptr);
237 bool is_comb
= cell_output_wire
->get_bool_attribute(ID(cxxrtl_comb
));
238 bool is_sync
= cell_output_wire
->get_bool_attribute(ID(cxxrtl_sync
));
239 if (is_comb
&& is_sync
)
240 log_cmd_error("Port `%s.%s' is marked as both `cxxrtl_comb` and `cxxrtl_sync`.\n",
241 log_id(cell_module
), log_signal(cell_output_wire
));
243 return CxxrtlPortType::COMB
;
245 return CxxrtlPortType::SYNC
;
246 return CxxrtlPortType::UNKNOWN
;
249 bool is_cxxrtl_comb_port(const RTLIL::Cell
*cell
, RTLIL::IdString port
)
251 return cxxrtl_port_type(cell
, port
) == CxxrtlPortType::COMB
;
254 bool is_cxxrtl_sync_port(const RTLIL::Cell
*cell
, RTLIL::IdString port
)
256 return cxxrtl_port_type(cell
, port
) == CxxrtlPortType::SYNC
;
269 RTLIL::SigSig connect
= {};
270 const RTLIL::Cell
*cell
= NULL
;
271 const RTLIL::Process
*process
= NULL
;
274 std::vector
<Node
*> nodes
;
275 dict
<const RTLIL::Wire
*, pool
<Node
*, hash_ptr_ops
>> wire_comb_defs
, wire_sync_defs
, wire_uses
;
276 dict
<const RTLIL::Wire
*, bool> wire_def_inlinable
, wire_use_inlinable
;
277 dict
<RTLIL::SigBit
, bool> bit_has_state
;
281 for (auto node
: nodes
)
285 void add_defs(Node
*node
, const RTLIL::SigSpec
&sig
, bool is_ff
, bool inlinable
)
287 for (auto chunk
: sig
.chunks())
290 // A sync def means that a wire holds design state because it is driven directly by
291 // a flip-flop output. Such a wire can never be unbuffered.
292 wire_sync_defs
[chunk
.wire
].insert(node
);
294 // A comb def means that a wire doesn't hold design state. It might still be connected,
295 // indirectly, to a flip-flop output.
296 wire_comb_defs
[chunk
.wire
].insert(node
);
299 for (auto bit
: sig
.bits())
300 bit_has_state
[bit
] |= is_ff
;
301 // Only comb defs of an entire wire in the right order can be inlined.
302 if (!is_ff
&& sig
.is_wire())
303 wire_def_inlinable
[sig
.as_wire()] = inlinable
;
306 void add_uses(Node
*node
, const RTLIL::SigSpec
&sig
)
308 for (auto chunk
: sig
.chunks())
310 wire_uses
[chunk
.wire
].insert(node
);
311 // Only a single use of an entire wire in the right order can be inlined.
312 // (But the use can include other chunks.)
313 if (!wire_use_inlinable
.count(chunk
.wire
))
314 wire_use_inlinable
[chunk
.wire
] = true;
316 wire_use_inlinable
[chunk
.wire
] = false;
320 bool is_inlinable(const RTLIL::Wire
*wire
) const
322 if (wire_def_inlinable
.count(wire
) && wire_use_inlinable
.count(wire
))
323 return wire_def_inlinable
.at(wire
) && wire_use_inlinable
.at(wire
);
328 void add_connect_defs_uses(Node
*node
, const RTLIL::SigSig
&conn
)
330 add_defs(node
, conn
.first
, /*is_ff=*/false, /*inlinable=*/true);
331 add_uses(node
, conn
.second
);
334 Node
*add_node(const RTLIL::SigSig
&conn
)
336 Node
*node
= new Node
;
337 node
->type
= Node::Type::CONNECT
;
338 node
->connect
= conn
;
339 nodes
.push_back(node
);
340 add_connect_defs_uses(node
, conn
);
345 void add_cell_sync_defs(Node
*node
, const RTLIL::Cell
*cell
)
347 // To understand why this node type is necessary and why it produces comb defs, consider a cell
348 // with input \i and sync output \o, used in a design such that \i is connected to \o. This does
349 // not result in a feedback arc because the output is synchronous. However, a naive implementation
350 // of code generation for cells that assigns to inputs, evaluates cells, assigns from outputs
351 // would not be able to immediately converge...
354 // cell->p_i = i_tmp.curr;
356 // i_tmp.next = cell->p_o.curr;
358 // ... since the wire connecting the input and output ports would not be localizable. To solve
359 // this, the cell is split into two scheduling nodes; one exclusively for sync outputs, and
360 // another for inputs and all non-sync outputs. This way the generated code can be rearranged...
363 // i_tmp = cell->p_o.curr;
364 // cell->p_i = i_tmp;
367 // eliminating the unnecessary delta cycle. Conceptually, the CELL_SYNC node type is a series of
368 // connections of the form `connect \lhs \cell.\sync_output`; the right-hand side of these is not
369 // expressible as a wire in RTLIL. If it was expressible, then `\cell.\sync_output` would have
370 // a sync def, and this node would be an ordinary CONNECT node, with `\lhs` having a comb def.
371 // Because it isn't, a special node type is used, the right-hand side does not appear anywhere,
372 // and the left-hand side has a comb def.
373 for (auto conn
: cell
->connections())
374 if (cell
->output(conn
.first
))
375 if (is_cxxrtl_sync_port(cell
, conn
.first
)) {
376 // See note regarding inlinability below.
377 add_defs(node
, conn
.second
, /*is_ff=*/false, /*inlinable=*/false);
381 void add_cell_eval_defs_uses(Node
*node
, const RTLIL::Cell
*cell
)
383 for (auto conn
: cell
->connections()) {
384 if (cell
->output(conn
.first
)) {
385 if (is_inlinable_cell(cell
->type
))
386 add_defs(node
, conn
.second
, /*is_ff=*/false, /*inlinable=*/true);
387 else if (is_ff_cell(cell
->type
) || (cell
->type
== ID($memrd
) && cell
->getParam(ID::CLK_ENABLE
).as_bool()))
388 add_defs(node
, conn
.second
, /*is_ff=*/true, /*inlinable=*/false);
389 else if (is_internal_cell(cell
->type
))
390 add_defs(node
, conn
.second
, /*is_ff=*/false, /*inlinable=*/false);
391 else if (!is_cxxrtl_sync_port(cell
, conn
.first
)) {
392 // Although at first it looks like outputs of user-defined cells may always be inlined, the reality is
393 // more complex. Fully sync outputs produce no defs and so don't participate in inlining. Fully comb
394 // outputs are assigned in a different way depending on whether the cell's eval() immediately converged.
395 // Unknown/mixed outputs could be inlined, but should be rare in practical designs and don't justify
396 // the infrastructure required to inline outputs of cells with many of them.
397 add_defs(node
, conn
.second
, /*is_ff=*/false, /*inlinable=*/false);
400 if (cell
->input(conn
.first
))
401 add_uses(node
, conn
.second
);
405 Node
*add_node(const RTLIL::Cell
*cell
)
407 log_assert(cell
->known());
409 bool has_fully_sync_outputs
= false;
410 for (auto conn
: cell
->connections())
411 if (cell
->output(conn
.first
) && is_cxxrtl_sync_port(cell
, conn
.first
)) {
412 has_fully_sync_outputs
= true;
415 if (has_fully_sync_outputs
) {
416 Node
*node
= new Node
;
417 node
->type
= Node::Type::CELL_SYNC
;
419 nodes
.push_back(node
);
420 add_cell_sync_defs(node
, cell
);
423 Node
*node
= new Node
;
424 node
->type
= Node::Type::CELL_EVAL
;
426 nodes
.push_back(node
);
427 add_cell_eval_defs_uses(node
, cell
);
432 void add_case_defs_uses(Node
*node
, const RTLIL::CaseRule
*case_
)
434 for (auto &action
: case_
->actions
) {
435 add_defs(node
, action
.first
, /*is_ff=*/false, /*inlinable=*/false);
436 add_uses(node
, action
.second
);
438 for (auto sub_switch
: case_
->switches
) {
439 add_uses(node
, sub_switch
->signal
);
440 for (auto sub_case
: sub_switch
->cases
) {
441 for (auto &compare
: sub_case
->compare
)
442 add_uses(node
, compare
);
443 add_case_defs_uses(node
, sub_case
);
448 void add_process_defs_uses(Node
*node
, const RTLIL::Process
*process
)
450 add_case_defs_uses(node
, &process
->root_case
);
451 for (auto sync
: process
->syncs
)
452 for (auto action
: sync
->actions
) {
453 if (sync
->type
== RTLIL::STp
|| sync
->type
== RTLIL::STn
|| sync
->type
== RTLIL::STe
)
454 add_defs(node
, action
.first
, /*is_ff=*/true, /*inlinable=*/false);
456 add_defs(node
, action
.first
, /*is_ff=*/false, /*inlinable=*/false);
457 add_uses(node
, action
.second
);
461 Node
*add_node(const RTLIL::Process
*process
)
463 Node
*node
= new Node
;
464 node
->type
= Node::Type::PROCESS
;
465 node
->process
= process
;
466 nodes
.push_back(node
);
467 add_process_defs_uses(node
, process
);
472 std::vector
<std::string
> split_by(const std::string
&str
, const std::string
&sep
)
474 std::vector
<std::string
> result
;
477 size_t curr
= str
.find_first_of(sep
, prev
);
478 if (curr
== std::string::npos
) {
479 std::string part
= str
.substr(prev
);
480 if (!part
.empty()) result
.push_back(part
);
483 std::string part
= str
.substr(prev
, curr
- prev
);
484 if (!part
.empty()) result
.push_back(part
);
491 std::string
escape_cxx_string(const std::string
&input
)
493 std::string output
= "\"";
494 for (auto c
: input
) {
497 output
.push_back('\\');
500 char l
= c
& 0xf, h
= (c
>> 4) & 0xf;
501 output
.append("\\x");
502 output
.push_back((h
< 10 ? '0' + h
: 'a' + h
- 10));
503 output
.push_back((l
< 10 ? '0' + l
: 'a' + l
- 10));
506 output
.push_back('"');
507 if (output
.find('\0') != std::string::npos
) {
508 output
.insert(0, "std::string {");
509 output
.append(stringf(", %zu}", input
.size()));
515 std::string
get_hdl_name(T
*object
)
517 if (object
->has_attribute(ID::hdlname
))
518 return object
->get_string_attribute(ID::hdlname
);
520 return object
->name
.str().substr(1);
523 struct CxxrtlWorker
{
524 bool split_intf
= false;
525 std::string intf_filename
;
526 std::string design_ns
= "cxxrtl_design";
527 std::ostream
*impl_f
= nullptr;
528 std::ostream
*intf_f
= nullptr;
530 bool run_hierarchy
= false;
531 bool run_flatten
= false;
532 bool run_proc
= false;
534 bool unbuffer_internal
= false;
535 bool unbuffer_public
= false;
536 bool localize_internal
= false;
537 bool localize_public
= false;
538 bool inline_internal
= false;
539 bool inline_public
= false;
541 bool debug_info
= false;
542 bool debug_alias
= false;
543 bool debug_eval
= false;
545 std::ostringstream f
;
549 dict
<const RTLIL::Module
*, SigMap
> sigmaps
;
550 pool
<const RTLIL::Wire
*> edge_wires
;
551 dict
<RTLIL::SigBit
, RTLIL::SyncType
> edge_types
;
552 pool
<const RTLIL::Memory
*> writable_memories
;
553 dict
<const RTLIL::Cell
*, pool
<const RTLIL::Cell
*>> transparent_for
;
554 dict
<const RTLIL::Module
*, std::vector
<FlowGraph::Node
>> schedule
;
555 pool
<const RTLIL::Wire
*> unbuffered_wires
;
556 pool
<const RTLIL::Wire
*> localized_wires
;
557 dict
<const RTLIL::Wire
*, FlowGraph::Node
> inlined_wires
;
558 dict
<const RTLIL::Wire
*, RTLIL::Const
> debug_const_wires
;
559 dict
<const RTLIL::Wire
*, const RTLIL::Wire
*> debug_alias_wires
;
560 pool
<const RTLIL::Wire
*> debug_outlined_wires
;
561 dict
<RTLIL::SigBit
, bool> bit_has_state
;
562 dict
<const RTLIL::Module
*, pool
<std::string
>> blackbox_specializations
;
563 dict
<const RTLIL::Module
*, bool> eval_converges
;
569 indent
.resize(indent
.size() - 1);
572 // RTLIL allows any characters in names other than whitespace. This presents an issue for generating C++ code
573 // because C++ identifiers may be only alphanumeric, cannot clash with C++ keywords, and cannot clash with cxxrtl
574 // identifiers. This issue can be solved with a name mangling scheme. We choose a name mangling scheme that results
575 // in readable identifiers, does not depend on an up-to-date list of C++ keywords, and is easy to apply. Its rules:
576 // 1. All generated identifiers start with `_`.
577 // 1a. Generated identifiers for public names (beginning with `\`) start with `p_`.
578 // 1b. Generated identifiers for internal names (beginning with `$`) start with `i_`.
579 // 2. An underscore is escaped with another underscore, i.e. `__`.
580 // 3. Any other non-alnum character is escaped with underscores around its lowercase hex code, e.g. `@` as `_40_`.
581 std::string
mangle_name(const RTLIL::IdString
&name
)
585 for (char c
: name
.str()) {
597 } else if (c
== '_') {
600 char l
= c
& 0xf, h
= (c
>> 4) & 0xf;
602 mangled
+= (h
< 10 ? '0' + h
: 'a' + h
- 10);
603 mangled
+= (l
< 10 ? '0' + l
: 'a' + l
- 10);
611 std::string
mangle_module_name(const RTLIL::IdString
&name
, bool is_blackbox
= false)
615 return "bb_" + mangle_name(name
);
616 return mangle_name(name
);
619 std::string
mangle_memory_name(const RTLIL::IdString
&name
)
621 // Class member namespace.
622 return "memory_" + mangle_name(name
);
625 std::string
mangle_cell_name(const RTLIL::IdString
&name
)
627 // Class member namespace.
628 return "cell_" + mangle_name(name
);
631 std::string
mangle_wire_name(const RTLIL::IdString
&name
)
633 // Class member namespace.
634 return mangle_name(name
);
637 std::string
mangle(const RTLIL::Module
*module
)
639 return mangle_module_name(module
->name
, /*is_blackbox=*/module
->get_bool_attribute(ID(cxxrtl_blackbox
)));
642 std::string
mangle(const RTLIL::Memory
*memory
)
644 return mangle_memory_name(memory
->name
);
647 std::string
mangle(const RTLIL::Cell
*cell
)
649 return mangle_cell_name(cell
->name
);
652 std::string
mangle(const RTLIL::Wire
*wire
)
654 return mangle_wire_name(wire
->name
);
657 std::string
mangle(RTLIL::SigBit sigbit
)
659 log_assert(sigbit
.wire
!= NULL
);
660 if (sigbit
.wire
->width
== 1)
661 return mangle(sigbit
.wire
);
662 return mangle(sigbit
.wire
) + "_" + std::to_string(sigbit
.offset
);
665 std::vector
<std::string
> template_param_names(const RTLIL::Module
*module
)
667 if (!module
->has_attribute(ID(cxxrtl_template
)))
670 if (module
->attributes
.at(ID(cxxrtl_template
)).flags
!= RTLIL::CONST_FLAG_STRING
)
671 log_cmd_error("Attribute `cxxrtl_template' of module `%s' is not a string.\n", log_id(module
));
673 std::vector
<std::string
> param_names
= split_by(module
->get_string_attribute(ID(cxxrtl_template
)), " \t");
674 for (const auto ¶m_name
: param_names
) {
675 // Various lowercase prefixes (p_, i_, cell_, ...) are used for member variables, so require
676 // parameters to start with an uppercase letter to avoid name conflicts. (This is the convention
677 // in both Verilog and C++, anyway.)
678 if (!isupper(param_name
[0]))
679 log_cmd_error("Attribute `cxxrtl_template' of module `%s' includes a parameter `%s', "
680 "which does not start with an uppercase letter.\n",
681 log_id(module
), param_name
.c_str());
686 std::string
template_params(const RTLIL::Module
*module
, bool is_decl
)
688 std::vector
<std::string
> param_names
= template_param_names(module
);
689 if (param_names
.empty())
692 std::string params
= "<";
694 for (const auto ¶m_name
: param_names
) {
700 params
+= param_name
;
706 std::string
template_args(const RTLIL::Cell
*cell
)
708 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
709 log_assert(cell_module
!= nullptr);
710 if (!cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
713 std::vector
<std::string
> param_names
= template_param_names(cell_module
);
714 if (param_names
.empty())
717 std::string params
= "<";
719 for (const auto ¶m_name
: param_names
) {
723 params
+= "/*" + param_name
+ "=*/";
724 RTLIL::IdString id_param_name
= '\\' + param_name
;
725 if (!cell
->hasParam(id_param_name
))
726 log_cmd_error("Cell `%s.%s' does not have a parameter `%s', which is required by the templated module `%s'.\n",
727 log_id(cell
->module
), log_id(cell
), param_name
.c_str(), log_id(cell_module
));
728 RTLIL::Const param_value
= cell
->getParam(id_param_name
);
729 if (((param_value
.flags
& ~RTLIL::CONST_FLAG_SIGNED
) != 0) || param_value
.as_int() < 0)
730 log_cmd_error("Parameter `%s' of cell `%s.%s', which is required by the templated module `%s', "
731 "is not a positive integer.\n",
732 param_name
.c_str(), log_id(cell
->module
), log_id(cell
), log_id(cell_module
));
733 params
+= std::to_string(cell
->getParam(id_param_name
).as_int());
739 std::string
fresh_temporary()
741 return stringf("tmp_%d", temporary
++);
744 void dump_attrs(const RTLIL::AttrObject
*object
)
746 for (auto attr
: object
->attributes
) {
747 f
<< indent
<< "// " << attr
.first
.str() << ": ";
748 if (attr
.second
.flags
& RTLIL::CONST_FLAG_STRING
) {
749 f
<< attr
.second
.decode_string();
751 f
<< attr
.second
.as_int(/*is_signed=*/attr
.second
.flags
& RTLIL::CONST_FLAG_SIGNED
);
757 void dump_const_init(const RTLIL::Const
&data
, int width
, int offset
= 0, bool fixed_width
= false)
759 const int CHUNK_SIZE
= 32;
762 int chunk_width
= min(width
, CHUNK_SIZE
);
763 uint32_t chunk
= data
.extract(offset
, chunk_width
).as_int();
765 f
<< stringf("0x%.*xu", (3 + chunk_width
) / 4, chunk
);
767 f
<< stringf("%#xu", chunk
);
768 if (width
> CHUNK_SIZE
)
770 offset
+= CHUNK_SIZE
;
776 void dump_const_init(const RTLIL::Const
&data
)
778 dump_const_init(data
, data
.size());
781 void dump_const(const RTLIL::Const
&data
, int width
, int offset
= 0, bool fixed_width
= false)
783 f
<< "value<" << width
<< ">";
784 dump_const_init(data
, width
, offset
, fixed_width
);
787 void dump_const(const RTLIL::Const
&data
)
789 dump_const(data
, data
.size());
792 bool dump_sigchunk(const RTLIL::SigChunk
&chunk
, bool is_lhs
, bool for_debug
= false)
794 if (chunk
.wire
== NULL
) {
795 dump_const(chunk
.data
, chunk
.width
, chunk
.offset
);
798 if (inlined_wires
.count(chunk
.wire
) && (!for_debug
|| !debug_outlined_wires
[chunk
.wire
])) {
800 const FlowGraph::Node
&node
= inlined_wires
[chunk
.wire
];
802 case FlowGraph::Node::Type::CONNECT
:
803 dump_connect_expr(node
.connect
, for_debug
);
805 case FlowGraph::Node::Type::CELL_EVAL
:
806 log_assert(is_inlinable_cell(node
.cell
->type
));
807 dump_cell_expr(node
.cell
, for_debug
);
812 } else if (unbuffered_wires
[chunk
.wire
]) {
813 f
<< mangle(chunk
.wire
);
815 f
<< mangle(chunk
.wire
) << (is_lhs
? ".next" : ".curr");
817 if (chunk
.width
== chunk
.wire
->width
&& chunk
.offset
== 0)
819 else if (chunk
.width
== 1)
820 f
<< ".slice<" << chunk
.offset
<< ">()";
822 f
<< ".slice<" << chunk
.offset
+chunk
.width
-1 << "," << chunk
.offset
<< ">()";
827 bool dump_sigspec(const RTLIL::SigSpec
&sig
, bool is_lhs
, bool for_debug
= false)
832 } else if (sig
.is_chunk()) {
833 return dump_sigchunk(sig
.as_chunk(), is_lhs
, for_debug
);
835 dump_sigchunk(*sig
.chunks().rbegin(), is_lhs
, for_debug
);
836 for (auto it
= sig
.chunks().rbegin() + 1; it
!= sig
.chunks().rend(); ++it
) {
838 dump_sigchunk(*it
, is_lhs
, for_debug
);
845 void dump_sigspec_lhs(const RTLIL::SigSpec
&sig
, bool for_debug
= false)
847 dump_sigspec(sig
, /*is_lhs=*/true, for_debug
);
850 void dump_sigspec_rhs(const RTLIL::SigSpec
&sig
, bool for_debug
= false)
852 // In the contexts where we want template argument deduction to occur for `template<size_t Bits> ... value<Bits>`,
853 // it is necessary to have the argument to already be a `value<N>`, since template argument deduction and implicit
854 // type conversion are mutually exclusive. In these contexts, we use dump_sigspec_rhs() to emit an explicit
855 // type conversion, but only if the expression needs it.
856 bool is_complex
= dump_sigspec(sig
, /*is_lhs=*/false, for_debug
);
861 void collect_sigspec_rhs(const RTLIL::SigSpec
&sig
, std::vector
<RTLIL::IdString
> &cells
)
863 for (auto chunk
: sig
.chunks()) {
864 if (!chunk
.wire
|| !inlined_wires
.count(chunk
.wire
))
867 const FlowGraph::Node
&node
= inlined_wires
[chunk
.wire
];
869 case FlowGraph::Node::Type::CONNECT
:
870 collect_connect(node
.connect
, cells
);
872 case FlowGraph::Node::Type::CELL_EVAL
:
873 collect_cell_eval(node
.cell
, cells
);
881 void dump_connect_expr(const RTLIL::SigSig
&conn
, bool for_debug
= false)
883 dump_sigspec_rhs(conn
.second
, for_debug
);
886 bool is_connect_inlined(const RTLIL::SigSig
&conn
)
888 return conn
.first
.is_wire() && inlined_wires
.count(conn
.first
.as_wire());
891 bool is_connect_outlined(const RTLIL::SigSig
&conn
)
893 for (auto chunk
: conn
.first
.chunks())
894 if (debug_outlined_wires
.count(chunk
.wire
))
899 void collect_connect(const RTLIL::SigSig
&conn
, std::vector
<RTLIL::IdString
> &cells
)
901 if (!is_connect_inlined(conn
))
904 collect_sigspec_rhs(conn
.second
, cells
);
907 void dump_connect(const RTLIL::SigSig
&conn
, bool for_debug
= false)
909 if (!for_debug
&& is_connect_inlined(conn
))
911 if (for_debug
&& !is_connect_outlined(conn
))
914 std::vector
<RTLIL::IdString
> inlined_cells
;
915 collect_sigspec_rhs(conn
.second
, inlined_cells
);
916 if (for_debug
|| inlined_cells
.empty()) {
917 f
<< indent
<< "// connection\n";
919 f
<< indent
<< "// cells";
920 for (auto inlined_cell
: inlined_cells
)
921 f
<< " " << inlined_cell
.str();
925 dump_sigspec_lhs(conn
.first
, for_debug
);
927 dump_connect_expr(conn
, for_debug
);
931 void dump_cell_sync(const RTLIL::Cell
*cell
)
933 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
934 f
<< indent
<< "// cell " << cell
->name
.str() << " syncs\n";
935 for (auto conn
: cell
->connections())
936 if (cell
->output(conn
.first
))
937 if (is_cxxrtl_sync_port(cell
, conn
.first
)) {
939 dump_sigspec_lhs(conn
.second
);
940 f
<< " = " << mangle(cell
) << access
<< mangle_wire_name(conn
.first
) << ".curr;\n";
944 void dump_cell_expr(const RTLIL::Cell
*cell
, bool for_debug
= false)
947 if (is_unary_cell(cell
->type
)) {
948 f
<< cell
->type
.substr(1);
949 if (is_extending_cell(cell
->type
))
950 f
<< '_' << (cell
->getParam(ID::A_SIGNED
).as_bool() ? 's' : 'u');
951 f
<< "<" << cell
->getParam(ID::Y_WIDTH
).as_int() << ">(";
952 dump_sigspec_rhs(cell
->getPort(ID::A
), for_debug
);
955 } else if (is_binary_cell(cell
->type
)) {
956 f
<< cell
->type
.substr(1);
957 if (is_extending_cell(cell
->type
))
958 f
<< '_' << (cell
->getParam(ID::A_SIGNED
).as_bool() ? 's' : 'u') <<
959 (cell
->getParam(ID::B_SIGNED
).as_bool() ? 's' : 'u');
960 f
<< "<" << cell
->getParam(ID::Y_WIDTH
).as_int() << ">(";
961 dump_sigspec_rhs(cell
->getPort(ID::A
), for_debug
);
963 dump_sigspec_rhs(cell
->getPort(ID::B
), for_debug
);
966 } else if (cell
->type
== ID($mux
)) {
968 dump_sigspec_rhs(cell
->getPort(ID::S
), for_debug
);
970 dump_sigspec_rhs(cell
->getPort(ID::B
), for_debug
);
972 dump_sigspec_rhs(cell
->getPort(ID::A
), for_debug
);
974 // Parallel (one-hot) muxes
975 } else if (cell
->type
== ID($pmux
)) {
976 int width
= cell
->getParam(ID::WIDTH
).as_int();
977 int s_width
= cell
->getParam(ID::S_WIDTH
).as_int();
978 for (int part
= 0; part
< s_width
; part
++) {
980 dump_sigspec_rhs(cell
->getPort(ID::S
).extract(part
), for_debug
);
982 dump_sigspec_rhs(cell
->getPort(ID::B
).extract(part
* width
, width
), for_debug
);
985 dump_sigspec_rhs(cell
->getPort(ID::A
), for_debug
);
986 for (int part
= 0; part
< s_width
; part
++) {
990 } else if (cell
->type
== ID($concat
)) {
991 dump_sigspec_rhs(cell
->getPort(ID::B
), for_debug
);
993 dump_sigspec_rhs(cell
->getPort(ID::A
), for_debug
);
996 } else if (cell
->type
== ID($slice
)) {
997 dump_sigspec_rhs(cell
->getPort(ID::A
), for_debug
);
999 f
<< cell
->getParam(ID::OFFSET
).as_int() + cell
->getParam(ID::Y_WIDTH
).as_int() - 1;
1001 f
<< cell
->getParam(ID::OFFSET
).as_int();
1008 bool is_cell_inlined(const RTLIL::Cell
*cell
)
1010 return is_inlinable_cell(cell
->type
) && cell
->hasPort(ID::Y
) && cell
->getPort(ID::Y
).is_wire() &&
1011 inlined_wires
.count(cell
->getPort(ID::Y
).as_wire());
1014 bool is_cell_outlined(const RTLIL::Cell
*cell
)
1016 if (is_internal_cell(cell
->type
))
1017 for (auto conn
: cell
->connections())
1018 if (cell
->output(conn
.first
))
1019 for (auto chunk
: conn
.second
.chunks())
1020 if (debug_outlined_wires
.count(chunk
.wire
))
1025 void collect_cell_eval(const RTLIL::Cell
*cell
, std::vector
<RTLIL::IdString
> &cells
)
1027 if (!is_cell_inlined(cell
))
1030 cells
.push_back(cell
->name
);
1031 for (auto port
: cell
->connections())
1032 if (port
.first
!= ID::Y
)
1033 collect_sigspec_rhs(port
.second
, cells
);
1036 void dump_cell_eval(const RTLIL::Cell
*cell
, bool for_debug
= false)
1038 if (!for_debug
&& is_cell_inlined(cell
))
1040 if (for_debug
&& !is_cell_outlined(cell
))
1042 if (cell
->type
== ID($meminit
))
1043 return; // Handled elsewhere.
1045 std::vector
<RTLIL::IdString
> inlined_cells
;
1046 if (is_inlinable_cell(cell
->type
)) {
1047 for (auto port
: cell
->connections())
1048 if (port
.first
!= ID::Y
)
1049 collect_sigspec_rhs(port
.second
, inlined_cells
);
1051 if (inlined_cells
.empty()) {
1053 f
<< indent
<< "// cell " << cell
->name
.str() << "\n";
1055 f
<< indent
<< "// cells";
1056 for (auto inlined_cell
: inlined_cells
)
1057 f
<< " " << inlined_cell
.str();
1062 if (is_inlinable_cell(cell
->type
)) {
1064 dump_sigspec_lhs(cell
->getPort(ID::Y
), for_debug
);
1066 dump_cell_expr(cell
, for_debug
);
1069 } else if (is_ff_cell(cell
->type
)) {
1070 if (cell
->hasPort(ID::CLK
) && cell
->getPort(ID::CLK
).is_wire()) {
1071 // Edge-sensitive logic
1072 RTLIL::SigBit clk_bit
= cell
->getPort(ID::CLK
)[0];
1073 clk_bit
= sigmaps
[clk_bit
.wire
->module
](clk_bit
);
1075 f
<< indent
<< "if (" << (cell
->getParam(ID::CLK_POLARITY
).as_bool() ? "posedge_" : "negedge_")
1076 << mangle(clk_bit
) << ") {\n";
1078 f
<< indent
<< "if (false) {\n";
1081 if (cell
->hasPort(ID::EN
)) {
1082 f
<< indent
<< "if (";
1083 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1084 f
<< " == value<1> {" << cell
->getParam(ID::EN_POLARITY
).as_bool() << "u}) {\n";
1088 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1090 dump_sigspec_rhs(cell
->getPort(ID::D
));
1092 if (cell
->hasPort(ID::EN
) && cell
->type
!= ID($sdffce
)) {
1094 f
<< indent
<< "}\n";
1096 if (cell
->hasPort(ID::SRST
)) {
1097 f
<< indent
<< "if (";
1098 dump_sigspec_rhs(cell
->getPort(ID::SRST
));
1099 f
<< " == value<1> {" << cell
->getParam(ID::SRST_POLARITY
).as_bool() << "u}) {\n";
1102 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1104 dump_const(cell
->getParam(ID::SRST_VALUE
));
1107 f
<< indent
<< "}\n";
1109 if (cell
->hasPort(ID::EN
) && cell
->type
== ID($sdffce
)) {
1111 f
<< indent
<< "}\n";
1114 f
<< indent
<< "}\n";
1115 } else if (cell
->hasPort(ID::EN
)) {
1116 // Level-sensitive logic
1117 f
<< indent
<< "if (";
1118 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1119 f
<< " == value<1> {" << cell
->getParam(ID::EN_POLARITY
).as_bool() << "u}) {\n";
1122 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1124 dump_sigspec_rhs(cell
->getPort(ID::D
));
1127 f
<< indent
<< "}\n";
1129 if (cell
->hasPort(ID::ARST
)) {
1130 // Asynchronous reset (entire coarse cell at once)
1131 f
<< indent
<< "if (";
1132 dump_sigspec_rhs(cell
->getPort(ID::ARST
));
1133 f
<< " == value<1> {" << cell
->getParam(ID::ARST_POLARITY
).as_bool() << "u}) {\n";
1136 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1138 dump_const(cell
->getParam(ID::ARST_VALUE
));
1141 f
<< indent
<< "}\n";
1143 if (cell
->hasPort(ID::SET
)) {
1144 // Asynchronous set (for individual bits)
1146 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1148 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1150 dump_const(RTLIL::Const(RTLIL::S1
, cell
->getParam(ID::WIDTH
).as_int()));
1152 dump_sigspec_rhs(cell
->getPort(ID::SET
));
1153 f
<< (cell
->getParam(ID::SET_POLARITY
).as_bool() ? "" : ".bit_not()") << ");\n";
1155 if (cell
->hasPort(ID::CLR
)) {
1156 // Asynchronous clear (for individual bits; priority over set)
1158 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1160 dump_sigspec_lhs(cell
->getPort(ID::Q
));
1162 dump_const(RTLIL::Const(RTLIL::S0
, cell
->getParam(ID::WIDTH
).as_int()));
1164 dump_sigspec_rhs(cell
->getPort(ID::CLR
));
1165 f
<< (cell
->getParam(ID::CLR_POLARITY
).as_bool() ? "" : ".bit_not()") << ");\n";
1168 } else if (cell
->type
.in(ID($memrd
), ID($memwr
))) {
1169 if (cell
->getParam(ID::CLK_ENABLE
).as_bool()) {
1170 RTLIL::SigBit clk_bit
= cell
->getPort(ID::CLK
)[0];
1171 clk_bit
= sigmaps
[clk_bit
.wire
->module
](clk_bit
);
1173 f
<< indent
<< "if (" << (cell
->getParam(ID::CLK_POLARITY
).as_bool() ? "posedge_" : "negedge_")
1174 << mangle(clk_bit
) << ") {\n";
1176 f
<< indent
<< "if (false) {\n";
1180 RTLIL::Memory
*memory
= cell
->module
->memories
[cell
->getParam(ID::MEMID
).decode_string()];
1181 std::string valid_index_temp
= fresh_temporary();
1182 f
<< indent
<< "auto " << valid_index_temp
<< " = memory_index(";
1183 dump_sigspec_rhs(cell
->getPort(ID::ADDR
));
1184 f
<< ", " << memory
->start_offset
<< ", " << memory
->size
<< ");\n";
1185 if (cell
->type
== ID($memrd
)) {
1186 bool has_enable
= cell
->getParam(ID::CLK_ENABLE
).as_bool() && !cell
->getPort(ID::EN
).is_fully_ones();
1188 f
<< indent
<< "if (";
1189 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1193 // The generated code has two bounds checks; one in an assertion, and another that guards the read.
1194 // This is done so that the code does not invoke undefined behavior under any conditions, but nevertheless
1195 // loudly crashes if an illegal condition is encountered. The assert may be turned off with -DCXXRTL_NDEBUG
1196 // not only for release builds, but also to make sure the simulator (which is presumably embedded in some
1197 // larger program) will never crash the code that calls into it.
1199 // If assertions are disabled, out of bounds reads are defined to return zero.
1200 f
<< indent
<< "CXXRTL_ASSERT(" << valid_index_temp
<< ".valid && \"out of bounds read\");\n";
1201 f
<< indent
<< "if(" << valid_index_temp
<< ".valid) {\n";
1203 if (writable_memories
[memory
]) {
1204 std::string lhs_temp
= fresh_temporary();
1205 f
<< indent
<< "value<" << memory
->width
<< "> " << lhs_temp
<< " = "
1206 << mangle(memory
) << "[" << valid_index_temp
<< ".index];\n";
1207 std::vector
<const RTLIL::Cell
*> memwr_cells(transparent_for
[cell
].begin(), transparent_for
[cell
].end());
1208 if (!memwr_cells
.empty()) {
1209 std::string addr_temp
= fresh_temporary();
1210 f
<< indent
<< "const value<" << cell
->getPort(ID::ADDR
).size() << "> &" << addr_temp
<< " = ";
1211 dump_sigspec_rhs(cell
->getPort(ID::ADDR
));
1213 std::sort(memwr_cells
.begin(), memwr_cells
.end(),
1214 [](const RTLIL::Cell
*a
, const RTLIL::Cell
*b
) {
1215 return a
->getParam(ID::PRIORITY
).as_int() < b
->getParam(ID::PRIORITY
).as_int();
1217 for (auto memwr_cell
: memwr_cells
) {
1218 f
<< indent
<< "if (" << addr_temp
<< " == ";
1219 dump_sigspec_rhs(memwr_cell
->getPort(ID::ADDR
));
1222 f
<< indent
<< lhs_temp
<< " = " << lhs_temp
;
1224 dump_sigspec_rhs(memwr_cell
->getPort(ID::DATA
));
1226 dump_sigspec_rhs(memwr_cell
->getPort(ID::EN
));
1229 f
<< indent
<< "}\n";
1233 dump_sigspec_lhs(cell
->getPort(ID::DATA
));
1234 f
<< " = " << lhs_temp
<< ";\n";
1237 dump_sigspec_lhs(cell
->getPort(ID::DATA
));
1238 f
<< " = " << mangle(memory
) << "[" << valid_index_temp
<< ".index];\n";
1241 f
<< indent
<< "} else {\n";
1244 dump_sigspec_lhs(cell
->getPort(ID::DATA
));
1245 f
<< " = value<" << memory
->width
<< "> {};\n";
1247 f
<< indent
<< "}\n";
1250 f
<< indent
<< "}\n";
1252 } else /*if (cell->type == ID($memwr))*/ {
1253 log_assert(writable_memories
[memory
]);
1254 // See above for rationale of having both the assert and the condition.
1256 // If assertions are disabled, out of bounds writes are defined to do nothing.
1257 f
<< indent
<< "CXXRTL_ASSERT(" << valid_index_temp
<< ".valid && \"out of bounds write\");\n";
1258 f
<< indent
<< "if (" << valid_index_temp
<< ".valid) {\n";
1260 f
<< indent
<< mangle(memory
) << ".update(" << valid_index_temp
<< ".index, ";
1261 dump_sigspec_rhs(cell
->getPort(ID::DATA
));
1263 dump_sigspec_rhs(cell
->getPort(ID::EN
));
1264 f
<< ", " << cell
->getParam(ID::PRIORITY
).as_int() << ");\n";
1266 f
<< indent
<< "}\n";
1268 if (cell
->getParam(ID::CLK_ENABLE
).as_bool()) {
1270 f
<< indent
<< "}\n";
1273 } else if (is_internal_cell(cell
->type
)) {
1274 log_cmd_error("Unsupported internal cell `%s'.\n", cell
->type
.c_str());
1277 log_assert(cell
->known());
1278 bool buffered_inputs
= false;
1279 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
1280 for (auto conn
: cell
->connections())
1281 if (cell
->input(conn
.first
)) {
1282 RTLIL::Module
*cell_module
= cell
->module
->design
->module(cell
->type
);
1283 log_assert(cell_module
!= nullptr && cell_module
->wire(conn
.first
) && conn
.second
.is_wire());
1284 RTLIL::Wire
*cell_module_wire
= cell_module
->wire(conn
.first
);
1285 f
<< indent
<< mangle(cell
) << access
<< mangle_wire_name(conn
.first
);
1286 if (!is_cxxrtl_blackbox_cell(cell
) && !unbuffered_wires
[cell_module_wire
]) {
1287 buffered_inputs
= true;
1291 dump_sigspec_rhs(conn
.second
);
1293 if (getenv("CXXRTL_VOID_MY_WARRANTY")) {
1294 // Until we have proper clock tree detection, this really awful hack that opportunistically
1295 // propagates prev_* values for clocks can be used to estimate how much faster a design could
1296 // be if only one clock edge was simulated by replacing:
1297 // top.p_clk = value<1>{0u}; top.step();
1298 // top.p_clk = value<1>{1u}; top.step();
1300 // top.prev_p_clk = value<1>{0u}; top.p_clk = value<1>{1u}; top.step();
1301 // Don't rely on this; it will be removed without warning.
1302 if (edge_wires
[conn
.second
.as_wire()] && edge_wires
[cell_module_wire
]) {
1303 f
<< indent
<< mangle(cell
) << access
<< "prev_" << mangle(cell_module_wire
) << " = ";
1304 f
<< "prev_" << mangle(conn
.second
.as_wire()) << ";\n";
1308 auto assign_from_outputs
= [&](bool cell_converged
) {
1309 for (auto conn
: cell
->connections()) {
1310 if (cell
->output(conn
.first
)) {
1311 if (conn
.second
.empty())
1312 continue; // ignore disconnected ports
1313 if (is_cxxrtl_sync_port(cell
, conn
.first
))
1314 continue; // fully sync ports are handled in CELL_SYNC nodes
1316 dump_sigspec_lhs(conn
.second
);
1317 f
<< " = " << mangle(cell
) << access
<< mangle_wire_name(conn
.first
);
1318 // Similarly to how there is no purpose to buffering cell inputs, there is also no purpose to buffering
1319 // combinatorial cell outputs in case the cell converges within one cycle. (To convince yourself that
1320 // this optimization is valid, consider that, since the cell converged within one cycle, it would not
1321 // have any buffered wires if they were not output ports. Imagine inlining the cell's eval() function,
1322 // and consider the fate of the localized wires that used to be output ports.)
1324 // It is not possible to know apriori whether the cell (which may be late bound) will converge immediately.
1325 // Because of this, the choice between using .curr (appropriate for buffered outputs) and .next (appropriate
1326 // for unbuffered outputs) is made at runtime.
1327 if (cell_converged
&& is_cxxrtl_comb_port(cell
, conn
.first
))
1334 if (buffered_inputs
) {
1335 // If we have any buffered inputs, there's no chance of converging immediately.
1336 f
<< indent
<< mangle(cell
) << access
<< "eval();\n";
1337 f
<< indent
<< "converged = false;\n";
1338 assign_from_outputs(/*cell_converged=*/false);
1340 f
<< indent
<< "if (" << mangle(cell
) << access
<< "eval()) {\n";
1342 assign_from_outputs(/*cell_converged=*/true);
1344 f
<< indent
<< "} else {\n";
1346 f
<< indent
<< "converged = false;\n";
1347 assign_from_outputs(/*cell_converged=*/false);
1349 f
<< indent
<< "}\n";
1354 void dump_assign(const RTLIL::SigSig
&sigsig
)
1357 dump_sigspec_lhs(sigsig
.first
);
1359 dump_sigspec_rhs(sigsig
.second
);
1363 void dump_case_rule(const RTLIL::CaseRule
*rule
)
1365 for (auto action
: rule
->actions
)
1366 dump_assign(action
);
1367 for (auto switch_
: rule
->switches
)
1368 dump_switch_rule(switch_
);
1371 void dump_switch_rule(const RTLIL::SwitchRule
*rule
)
1373 // The switch attributes are printed before the switch condition is captured.
1375 std::string signal_temp
= fresh_temporary();
1376 f
<< indent
<< "const value<" << rule
->signal
.size() << "> &" << signal_temp
<< " = ";
1377 dump_sigspec(rule
->signal
, /*is_lhs=*/false);
1381 for (auto case_
: rule
->cases
) {
1382 // The case attributes (for nested cases) are printed before the if/else if/else statement.
1388 if (!case_
->compare
.empty()) {
1391 for (auto &compare
: case_
->compare
) {
1395 if (compare
.is_fully_def()) {
1396 f
<< signal_temp
<< " == ";
1397 dump_sigspec(compare
, /*is_lhs=*/false);
1398 } else if (compare
.is_fully_const()) {
1399 RTLIL::Const compare_mask
, compare_value
;
1400 for (auto bit
: compare
.as_const()) {
1404 compare_mask
.bits
.push_back(RTLIL::S1
);
1405 compare_value
.bits
.push_back(bit
);
1411 compare_mask
.bits
.push_back(RTLIL::S0
);
1412 compare_value
.bits
.push_back(RTLIL::S0
);
1419 f
<< "and_uu<" << compare
.size() << ">(" << signal_temp
<< ", ";
1420 dump_const(compare_mask
);
1422 dump_const(compare_value
);
1431 dump_case_rule(case_
);
1434 f
<< indent
<< "}\n";
1437 void dump_process(const RTLIL::Process
*proc
)
1440 f
<< indent
<< "// process " << proc
->name
.str() << "\n";
1441 // The case attributes (for root case) are always empty.
1442 log_assert(proc
->root_case
.attributes
.empty());
1443 dump_case_rule(&proc
->root_case
);
1444 for (auto sync
: proc
->syncs
) {
1445 RTLIL::SigBit sync_bit
;
1446 if (!sync
->signal
.empty()) {
1447 sync_bit
= sync
->signal
[0];
1448 sync_bit
= sigmaps
[sync_bit
.wire
->module
](sync_bit
);
1451 pool
<std::string
> events
;
1452 switch (sync
->type
) {
1454 log_assert(sync_bit
.wire
!= nullptr);
1455 events
.insert("posedge_" + mangle(sync_bit
));
1458 log_assert(sync_bit
.wire
!= nullptr);
1459 events
.insert("negedge_" + mangle(sync_bit
));
1462 log_assert(sync_bit
.wire
!= nullptr);
1463 events
.insert("posedge_" + mangle(sync_bit
));
1464 events
.insert("negedge_" + mangle(sync_bit
));
1468 events
.insert("true");
1477 if (!events
.empty()) {
1478 f
<< indent
<< "if (";
1480 for (auto &event
: events
) {
1488 for (auto action
: sync
->actions
)
1489 dump_assign(action
);
1491 f
<< indent
<< "}\n";
1496 void dump_wire(const RTLIL::Wire
*wire
, bool is_local
)
1498 if (is_local
&& localized_wires
[wire
] && !inlined_wires
.count(wire
)) {
1500 f
<< indent
<< "value<" << wire
->width
<< "> " << mangle(wire
) << ";\n";
1502 if (!is_local
&& !localized_wires
[wire
]) {
1504 if (wire
->module
->has_attribute(ID(cxxrtl_blackbox
)) && wire
->has_attribute(ID(cxxrtl_width
))) {
1505 width
= wire
->get_string_attribute(ID(cxxrtl_width
));
1507 width
= std::to_string(wire
->width
);
1512 if (wire
->port_input
&& wire
->port_output
)
1514 else if (wire
->port_input
)
1516 else if (wire
->port_output
)
1518 f
<< (unbuffered_wires
[wire
] ? "value" : "wire") << "<" << width
<< "> " << mangle(wire
);
1519 if (wire
->has_attribute(ID::init
)) {
1521 dump_const_init(wire
->attributes
.at(ID::init
));
1524 if (edge_wires
[wire
]) {
1525 if (unbuffered_wires
[wire
]) {
1526 f
<< indent
<< "value<" << width
<< "> prev_" << mangle(wire
);
1527 if (wire
->has_attribute(ID::init
)) {
1529 dump_const_init(wire
->attributes
.at(ID::init
));
1533 for (auto edge_type
: edge_types
) {
1534 if (edge_type
.first
.wire
== wire
) {
1535 std::string prev
, next
;
1536 if (unbuffered_wires
[wire
]) {
1537 prev
= "prev_" + mangle(edge_type
.first
.wire
);
1538 next
= mangle(edge_type
.first
.wire
);
1540 prev
= mangle(edge_type
.first
.wire
) + ".curr";
1541 next
= mangle(edge_type
.first
.wire
) + ".next";
1543 prev
+= ".slice<" + std::to_string(edge_type
.first
.offset
) + ">().val()";
1544 next
+= ".slice<" + std::to_string(edge_type
.first
.offset
) + ">().val()";
1545 if (edge_type
.second
!= RTLIL::STn
) {
1546 f
<< indent
<< "bool posedge_" << mangle(edge_type
.first
) << "() const {\n";
1548 f
<< indent
<< "return !" << prev
<< " && " << next
<< ";\n";
1550 f
<< indent
<< "}\n";
1552 if (edge_type
.second
!= RTLIL::STp
) {
1553 f
<< indent
<< "bool negedge_" << mangle(edge_type
.first
) << "() const {\n";
1555 f
<< indent
<< "return " << prev
<< " && !" << next
<< ";\n";
1557 f
<< indent
<< "}\n";
1565 void dump_debug_wire(const RTLIL::Wire
*wire
, bool is_local
)
1567 if (!debug_outlined_wires
[wire
])
1570 bool is_outlined_member
= wire
->name
.isPublic() &&
1571 !(debug_const_wires
.count(wire
) || debug_alias_wires
.count(wire
));
1572 if (is_local
&& !is_outlined_member
) {
1574 f
<< indent
<< "value<" << wire
->width
<< "> " << mangle(wire
) << ";\n";
1576 if (!is_local
&& is_outlined_member
) {
1578 f
<< indent
<< "/*outline*/ value<" << wire
->width
<< "> " << mangle(wire
) << ";\n";
1582 void dump_memory(RTLIL::Module
*module
, const RTLIL::Memory
*memory
)
1584 vector
<const RTLIL::Cell
*> init_cells
;
1585 for (auto cell
: module
->cells())
1586 if (cell
->type
== ID($meminit
) && cell
->getParam(ID::MEMID
).decode_string() == memory
->name
.str())
1587 init_cells
.push_back(cell
);
1589 std::sort(init_cells
.begin(), init_cells
.end(), [](const RTLIL::Cell
*a
, const RTLIL::Cell
*b
) {
1590 int a_addr
= a
->getPort(ID::ADDR
).as_int(), b_addr
= b
->getPort(ID::ADDR
).as_int();
1591 int a_prio
= a
->getParam(ID::PRIORITY
).as_int(), b_prio
= b
->getParam(ID::PRIORITY
).as_int();
1592 return a_prio
> b_prio
|| (a_prio
== b_prio
&& a_addr
< b_addr
);
1596 f
<< indent
<< "memory<" << memory
->width
<< "> " << mangle(memory
)
1597 << " { " << memory
->size
<< "u";
1598 if (init_cells
.empty()) {
1603 for (auto cell
: init_cells
) {
1605 RTLIL::Const data
= cell
->getPort(ID::DATA
).as_const();
1606 size_t width
= cell
->getParam(ID::WIDTH
).as_int();
1607 size_t words
= cell
->getParam(ID::WORDS
).as_int();
1608 f
<< indent
<< "memory<" << memory
->width
<< ">::init<" << words
<< "> { "
1609 << stringf("%#x", cell
->getPort(ID::ADDR
).as_int()) << ", {";
1611 for (size_t n
= 0; n
< words
; n
++) {
1613 f
<< "\n" << indent
;
1616 dump_const(data
, width
, n
* width
, /*fixed_width=*/true);
1620 f
<< "\n" << indent
<< "}},\n";
1623 f
<< indent
<< "};\n";
1627 void dump_eval_method(RTLIL::Module
*module
)
1630 f
<< indent
<< "bool converged = " << (eval_converges
.at(module
) ? "true" : "false") << ";\n";
1631 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1632 for (auto wire
: module
->wires()) {
1633 if (edge_wires
[wire
]) {
1634 for (auto edge_type
: edge_types
) {
1635 if (edge_type
.first
.wire
== wire
) {
1636 if (edge_type
.second
!= RTLIL::STn
) {
1637 f
<< indent
<< "bool posedge_" << mangle(edge_type
.first
) << " = ";
1638 f
<< "this->posedge_" << mangle(edge_type
.first
) << "();\n";
1640 if (edge_type
.second
!= RTLIL::STp
) {
1641 f
<< indent
<< "bool negedge_" << mangle(edge_type
.first
) << " = ";
1642 f
<< "this->negedge_" << mangle(edge_type
.first
) << "();\n";
1648 for (auto wire
: module
->wires())
1649 dump_wire(wire
, /*is_local=*/true);
1650 for (auto node
: schedule
[module
]) {
1651 switch (node
.type
) {
1652 case FlowGraph::Node::Type::CONNECT
:
1653 dump_connect(node
.connect
);
1655 case FlowGraph::Node::Type::CELL_SYNC
:
1656 dump_cell_sync(node
.cell
);
1658 case FlowGraph::Node::Type::CELL_EVAL
:
1659 dump_cell_eval(node
.cell
);
1661 case FlowGraph::Node::Type::PROCESS
:
1662 dump_process(node
.process
);
1667 f
<< indent
<< "return converged;\n";
1671 void dump_debug_eval_method(RTLIL::Module
*module
)
1674 for (auto wire
: module
->wires())
1675 dump_debug_wire(wire
, /*is_local=*/true);
1676 for (auto node
: schedule
[module
]) {
1677 switch (node
.type
) {
1678 case FlowGraph::Node::Type::CONNECT
:
1679 dump_connect(node
.connect
, /*for_debug=*/true);
1681 case FlowGraph::Node::Type::CELL_EVAL
:
1682 dump_cell_eval(node
.cell
, /*for_debug=*/true);
1684 case FlowGraph::Node::Type::CELL_SYNC
:
1685 case FlowGraph::Node::Type::PROCESS
:
1692 void dump_commit_method(RTLIL::Module
*module
)
1695 f
<< indent
<< "bool changed = false;\n";
1696 for (auto wire
: module
->wires()) {
1697 if (inlined_wires
.count(wire
))
1699 if (unbuffered_wires
[wire
]) {
1700 if (edge_wires
[wire
])
1701 f
<< indent
<< "prev_" << mangle(wire
) << " = " << mangle(wire
) << ";\n";
1704 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
)) || wire
->port_id
!= 0)
1705 f
<< indent
<< "if (" << mangle(wire
) << ".commit()) changed = true;\n";
1707 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1708 for (auto memory
: module
->memories
) {
1709 if (!writable_memories
[memory
.second
])
1711 f
<< indent
<< "if (" << mangle(memory
.second
) << ".commit()) changed = true;\n";
1713 for (auto cell
: module
->cells()) {
1714 if (is_internal_cell(cell
->type
))
1716 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
1717 f
<< indent
<< "if (" << mangle(cell
) << access
<< "commit()) changed = true;\n";
1720 f
<< indent
<< "return changed;\n";
1724 void dump_debug_info_method(RTLIL::Module
*module
)
1726 size_t count_public_wires
= 0;
1727 size_t count_const_wires
= 0;
1728 size_t count_alias_wires
= 0;
1729 size_t count_inline_wires
= 0;
1730 size_t count_member_wires
= 0;
1731 size_t count_skipped_wires
= 0;
1732 size_t count_driven_sync
= 0;
1733 size_t count_driven_comb
= 0;
1734 size_t count_undriven
= 0;
1735 size_t count_mixed_driver
= 0;
1737 f
<< indent
<< "assert(path.empty() || path[path.size() - 1] == ' ');\n";
1738 for (auto wire
: module
->wires()) {
1739 if (!wire
->name
.isPublic())
1741 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
)) && (wire
->port_id
== 0))
1743 count_public_wires
++;
1744 if (debug_const_wires
.count(wire
)) {
1745 // Wire tied to a constant
1746 f
<< indent
<< "static const value<" << wire
->width
<< "> const_" << mangle(wire
) << " = ";
1747 dump_const(debug_const_wires
[wire
]);
1749 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(wire
));
1750 f
<< ", debug_item(const_" << mangle(wire
) << ", ";
1751 f
<< wire
->start_offset
<< "));\n";
1752 count_const_wires
++;
1753 } else if (debug_alias_wires
.count(wire
)) {
1754 // Alias of a member wire
1755 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(wire
));
1756 f
<< ", debug_item(debug_alias(), " << mangle(debug_alias_wires
[wire
]) << ", ";
1757 f
<< wire
->start_offset
<< "));\n";
1758 count_alias_wires
++;
1759 } else if (debug_outlined_wires
.count(wire
)) {
1760 // Inlined but rematerializable wire
1761 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(wire
));
1762 f
<< ", debug_item(debug_eval_outline, " << mangle(wire
) << ", ";
1763 f
<< wire
->start_offset
<< "));\n";
1764 count_inline_wires
++;
1765 } else if (!localized_wires
.count(wire
)) {
1767 std::vector
<std::string
> flags
;
1769 if (wire
->port_input
&& wire
->port_output
)
1770 flags
.push_back("INOUT");
1771 else if (wire
->port_input
)
1772 flags
.push_back("INPUT");
1773 else if (wire
->port_output
)
1774 flags
.push_back("OUTPUT");
1776 bool has_driven_sync
= false;
1777 bool has_driven_comb
= false;
1778 bool has_undriven
= false;
1780 for (auto bit
: sig
.bits())
1781 if (!bit_has_state
.count(bit
))
1782 has_undriven
= true;
1783 else if (bit_has_state
[bit
])
1784 has_driven_sync
= true;
1786 has_driven_comb
= true;
1787 if (has_driven_sync
)
1788 flags
.push_back("DRIVEN_SYNC");
1789 if (has_driven_sync
&& !has_driven_comb
&& !has_undriven
)
1790 count_driven_sync
++;
1791 if (has_driven_comb
)
1792 flags
.push_back("DRIVEN_COMB");
1793 if (!has_driven_sync
&& has_driven_comb
&& !has_undriven
)
1794 count_driven_comb
++;
1796 flags
.push_back("UNDRIVEN");
1797 if (!has_driven_sync
&& !has_driven_comb
&& has_undriven
)
1799 if (has_driven_sync
+ has_driven_comb
+ has_undriven
> 1)
1800 count_mixed_driver
++;
1802 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(wire
));
1803 f
<< ", debug_item(" << mangle(wire
) << ", ";
1804 f
<< wire
->start_offset
;
1806 for (auto flag
: flags
) {
1813 f
<< "debug_item::" << flag
;
1816 count_member_wires
++;
1818 // Localized or inlined wire with no debug information
1819 count_skipped_wires
++;
1822 if (!module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1823 for (auto &memory_it
: module
->memories
) {
1824 if (!memory_it
.first
.isPublic())
1826 f
<< indent
<< "items.add(path + " << escape_cxx_string(get_hdl_name(memory_it
.second
));
1827 f
<< ", debug_item(" << mangle(memory_it
.second
) << ", ";
1828 f
<< memory_it
.second
->start_offset
<< "));\n";
1830 for (auto cell
: module
->cells()) {
1831 if (is_internal_cell(cell
->type
))
1833 const char *access
= is_cxxrtl_blackbox_cell(cell
) ? "->" : ".";
1834 f
<< indent
<< mangle(cell
) << access
<< "debug_info(items, ";
1835 f
<< "path + " << escape_cxx_string(get_hdl_name(cell
) + ' ') << ");\n";
1840 log_debug("Debug information statistics for module `%s':\n", log_id(module
));
1841 log_debug(" Public wires: %zu, of which:\n", count_public_wires
);
1842 log_debug(" Member wires: %zu, of which:\n", count_member_wires
);
1843 log_debug(" Driven sync: %zu\n", count_driven_sync
);
1844 log_debug(" Driven comb: %zu\n", count_driven_comb
);
1845 log_debug(" Mixed driver: %zu\n", count_mixed_driver
);
1846 log_debug(" Undriven: %zu\n", count_undriven
);
1847 log_debug(" Inline wires: %zu\n", count_inline_wires
);
1848 log_debug(" Alias wires: %zu\n", count_alias_wires
);
1849 log_debug(" Const wires: %zu\n", count_const_wires
);
1850 log_debug(" Other wires: %zu%s\n", count_skipped_wires
,
1851 count_skipped_wires
> 0 ? " (debug information unavailable)" : "");
1854 void dump_metadata_map(const dict
<RTLIL::IdString
, RTLIL::Const
> &metadata_map
)
1856 if (metadata_map
.empty()) {
1857 f
<< "metadata_map()";
1860 f
<< "metadata_map({\n";
1862 for (auto metadata_item
: metadata_map
) {
1863 if (!metadata_item
.first
.begins_with("\\"))
1865 f
<< indent
<< "{ " << escape_cxx_string(metadata_item
.first
.str().substr(1)) << ", ";
1866 if (metadata_item
.second
.flags
& RTLIL::CONST_FLAG_REAL
) {
1867 f
<< std::showpoint
<< std::stod(metadata_item
.second
.decode_string()) << std::noshowpoint
;
1868 } else if (metadata_item
.second
.flags
& RTLIL::CONST_FLAG_STRING
) {
1869 f
<< escape_cxx_string(metadata_item
.second
.decode_string());
1871 f
<< metadata_item
.second
.as_int(/*is_signed=*/metadata_item
.second
.flags
& RTLIL::CONST_FLAG_SIGNED
);
1872 if (!(metadata_item
.second
.flags
& RTLIL::CONST_FLAG_SIGNED
))
1878 f
<< indent
<< "})";
1881 void dump_module_intf(RTLIL::Module
*module
)
1884 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1885 if (module
->has_attribute(ID(cxxrtl_template
)))
1886 f
<< indent
<< "template" << template_params(module
, /*is_decl=*/true) << "\n";
1887 f
<< indent
<< "struct " << mangle(module
) << " : public module {\n";
1889 for (auto wire
: module
->wires()) {
1890 if (wire
->port_id
!= 0)
1891 dump_wire(wire
, /*is_local=*/false);
1894 f
<< indent
<< "bool eval() override {\n";
1895 dump_eval_method(module
);
1896 f
<< indent
<< "}\n";
1898 f
<< indent
<< "bool commit() override {\n";
1899 dump_commit_method(module
);
1900 f
<< indent
<< "}\n";
1903 f
<< indent
<< "void debug_info(debug_items &items, std::string path = \"\") override {\n";
1904 dump_debug_info_method(module
);
1905 f
<< indent
<< "}\n";
1908 f
<< indent
<< "static std::unique_ptr<" << mangle(module
);
1909 f
<< template_params(module
, /*is_decl=*/false) << "> ";
1910 f
<< "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
1912 f
<< indent
<< "}; // struct " << mangle(module
) << "\n";
1914 if (blackbox_specializations
.count(module
)) {
1915 // If templated black boxes are used, the constructor of any module which includes the black box cell
1916 // (which calls the declared but not defined in the generated code `create` function) may only be used
1917 // if (a) the create function is defined in the same translation unit, or (b) the create function has
1918 // a forward-declared explicit specialization.
1920 // Option (b) makes it possible to have the generated code and the black box implementation in different
1921 // translation units, which is convenient. Of course, its downside is that black boxes must predefine
1922 // a specialization for every combination of parameters the generated code may use; but since the main
1923 // purpose of templated black boxes is abstracting over datapath width, it is expected that there would
1924 // be very few such combinations anyway.
1925 for (auto specialization
: blackbox_specializations
[module
]) {
1926 f
<< indent
<< "template<>\n";
1927 f
<< indent
<< "std::unique_ptr<" << mangle(module
) << specialization
<< "> ";
1928 f
<< mangle(module
) << specialization
<< "::";
1929 f
<< "create(std::string name, metadata_map parameters, metadata_map attributes);\n";
1934 f
<< indent
<< "struct " << mangle(module
) << " : public module {\n";
1936 for (auto wire
: module
->wires())
1937 dump_wire(wire
, /*is_local=*/false);
1938 for (auto wire
: module
->wires())
1939 dump_debug_wire(wire
, /*is_local=*/false);
1940 bool has_memories
= false;
1941 for (auto memory
: module
->memories
) {
1942 dump_memory(module
, memory
.second
);
1943 has_memories
= true;
1947 bool has_cells
= false;
1948 for (auto cell
: module
->cells()) {
1949 if (is_internal_cell(cell
->type
))
1952 RTLIL::Module
*cell_module
= module
->design
->module(cell
->type
);
1953 log_assert(cell_module
!= nullptr);
1954 if (cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1955 f
<< indent
<< "std::unique_ptr<" << mangle(cell_module
) << template_args(cell
) << "> ";
1956 f
<< mangle(cell
) << " = " << mangle(cell_module
) << template_args(cell
);
1957 f
<< "::create(" << escape_cxx_string(get_hdl_name(cell
)) << ", ";
1958 dump_metadata_map(cell
->parameters
);
1960 dump_metadata_map(cell
->attributes
);
1963 f
<< indent
<< mangle(cell_module
) << " " << mangle(cell
) << ";\n";
1969 f
<< indent
<< mangle(module
) << "() {}\n";
1971 f
<< indent
<< mangle(module
) << "(adopt, " << mangle(module
) << " other) :\n";
1973 for (auto cell
: module
->cells()) {
1974 if (is_internal_cell(cell
->type
))
1981 RTLIL::Module
*cell_module
= module
->design
->module(cell
->type
);
1982 if (cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
1983 f
<< indent
<< " " << mangle(cell
) << "(std::move(other." << mangle(cell
) << "))";
1985 f
<< indent
<< " " << mangle(cell
) << "(adopt {}, std::move(other." << mangle(cell
) << "))";
1990 for (auto cell
: module
->cells()) {
1991 if (is_internal_cell(cell
->type
))
1993 RTLIL::Module
*cell_module
= module
->design
->module(cell
->type
);
1994 if (cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
1995 f
<< indent
<< mangle(cell
) << "->reset();\n";
1998 f
<< indent
<< "}\n";
2000 f
<< indent
<< mangle(module
) << "(adopt, " << mangle(module
) << " other) {}\n";
2003 f
<< indent
<< "void reset() override {\n";
2005 f
<< indent
<< "*this = " << mangle(module
) << "(adopt {}, std::move(*this));\n";
2007 f
<< indent
<< "}\n";
2009 f
<< indent
<< "bool eval() override;\n";
2010 f
<< indent
<< "bool commit() override;\n";
2014 f
<< indent
<< "void debug_eval();\n";
2015 for (auto wire
: module
->wires())
2016 if (debug_outlined_wires
.count(wire
)) {
2017 f
<< indent
<< "debug_outline debug_eval_outline { std::bind(&"
2018 << mangle(module
) << "::debug_eval, this) };\n";
2023 f
<< indent
<< "void debug_info(debug_items &items, std::string path = \"\") override;\n";
2026 f
<< indent
<< "}; // struct " << mangle(module
) << "\n";
2031 void dump_module_impl(RTLIL::Module
*module
)
2033 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
2035 f
<< indent
<< "bool " << mangle(module
) << "::eval() {\n";
2036 dump_eval_method(module
);
2037 f
<< indent
<< "}\n";
2039 f
<< indent
<< "bool " << mangle(module
) << "::commit() {\n";
2040 dump_commit_method(module
);
2041 f
<< indent
<< "}\n";
2045 f
<< indent
<< "void " << mangle(module
) << "::debug_eval() {\n";
2046 dump_debug_eval_method(module
);
2047 f
<< indent
<< "}\n";
2050 f
<< indent
<< "CXXRTL_EXTREMELY_COLD\n";
2051 f
<< indent
<< "void " << mangle(module
) << "::debug_info(debug_items &items, std::string path) {\n";
2052 dump_debug_info_method(module
);
2053 f
<< indent
<< "}\n";
2058 void dump_design(RTLIL::Design
*design
)
2060 RTLIL::Module
*top_module
= nullptr;
2061 std::vector
<RTLIL::Module
*> modules
;
2062 TopoSort
<RTLIL::Module
*> topo_design
;
2063 for (auto module
: design
->modules()) {
2064 if (!design
->selected_module(module
))
2066 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
2067 modules
.push_back(module
); // cxxrtl blackboxes first
2068 if (module
->get_blackbox_attribute() || module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
2070 if (module
->get_bool_attribute(ID::top
))
2071 top_module
= module
;
2073 topo_design
.node(module
);
2074 for (auto cell
: module
->cells()) {
2075 if (is_internal_cell(cell
->type
) || is_cxxrtl_blackbox_cell(cell
))
2077 RTLIL::Module
*cell_module
= design
->module(cell
->type
);
2078 log_assert(cell_module
!= nullptr);
2079 topo_design
.edge(cell_module
, module
);
2082 bool no_loops
= topo_design
.sort();
2083 log_assert(no_loops
);
2084 modules
.insert(modules
.end(), topo_design
.sorted
.begin(), topo_design
.sorted
.end());
2087 // The only thing more depraved than include guards, is mangling filenames to turn them into include guards.
2088 std::string include_guard
= design_ns
+ "_header";
2089 std::transform(include_guard
.begin(), include_guard
.end(), include_guard
.begin(), ::toupper
);
2091 f
<< "#ifndef " << include_guard
<< "\n";
2092 f
<< "#define " << include_guard
<< "\n";
2094 if (top_module
!= nullptr && debug_info
) {
2095 f
<< "#include <backends/cxxrtl/cxxrtl_capi.h>\n";
2097 f
<< "#ifdef __cplusplus\n";
2098 f
<< "extern \"C\" {\n";
2101 f
<< "cxxrtl_toplevel " << design_ns
<< "_create();\n";
2103 f
<< "#ifdef __cplusplus\n";
2108 f
<< "// The CXXRTL C API is not available because the design is built without debug information.\n";
2111 f
<< "#ifdef __cplusplus\n";
2113 f
<< "#include <backends/cxxrtl/cxxrtl.h>\n";
2115 f
<< "using namespace cxxrtl;\n";
2117 f
<< "namespace " << design_ns
<< " {\n";
2119 for (auto module
: modules
)
2120 dump_module_intf(module
);
2121 f
<< "} // namespace " << design_ns
<< "\n";
2123 f
<< "#endif // __cplusplus\n";
2126 *intf_f
<< f
.str(); f
.str("");
2130 f
<< "#include \"" << intf_filename
<< "\"\n";
2132 f
<< "#include <backends/cxxrtl/cxxrtl.h>\n";
2134 f
<< "#if defined(CXXRTL_INCLUDE_CAPI_IMPL) || \\\n";
2135 f
<< " defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
2136 f
<< "#include <backends/cxxrtl/cxxrtl_capi.cc>\n";
2139 f
<< "#if defined(CXXRTL_INCLUDE_VCD_CAPI_IMPL)\n";
2140 f
<< "#include <backends/cxxrtl/cxxrtl_vcd_capi.cc>\n";
2143 f
<< "using namespace cxxrtl_yosys;\n";
2145 f
<< "namespace " << design_ns
<< " {\n";
2147 for (auto module
: modules
) {
2149 dump_module_intf(module
);
2150 dump_module_impl(module
);
2152 f
<< "} // namespace " << design_ns
<< "\n";
2154 if (top_module
!= nullptr && debug_info
) {
2155 f
<< "extern \"C\"\n";
2156 f
<< "cxxrtl_toplevel " << design_ns
<< "_create() {\n";
2158 std::string top_type
= design_ns
+ "::" + mangle(top_module
);
2159 f
<< indent
<< "return new _cxxrtl_toplevel { ";
2160 f
<< "std::unique_ptr<" << top_type
<< ">(new " + top_type
+ ")";
2166 *impl_f
<< f
.str(); f
.str("");
2169 // Edge-type sync rules require us to emit edge detectors, which require coordination between
2170 // eval and commit phases. To do this we need to collect them upfront.
2172 // Note that the simulator commit phase operates at wire granularity but edge-type sync rules
2173 // operate at wire bit granularity; it is possible to have code similar to:
2174 // wire [3:0] clocks;
2175 // always @(posedge clocks[0]) ...
2176 // To handle this we track edge sensitivity both for wires and wire bits.
2177 void register_edge_signal(SigMap
&sigmap
, RTLIL::SigSpec signal
, RTLIL::SyncType type
)
2179 signal
= sigmap(signal
);
2180 log_assert(signal
.is_wire() && signal
.is_bit());
2181 log_assert(type
== RTLIL::STp
|| type
== RTLIL::STn
|| type
== RTLIL::STe
);
2183 RTLIL::SigBit sigbit
= signal
[0];
2184 if (!edge_types
.count(sigbit
))
2185 edge_types
[sigbit
] = type
;
2186 else if (edge_types
[sigbit
] != type
)
2187 edge_types
[sigbit
] = RTLIL::STe
;
2188 edge_wires
.insert(signal
.as_wire());
2191 void analyze_design(RTLIL::Design
*design
)
2193 bool has_feedback_arcs
= false;
2194 bool has_buffered_comb_wires
= false;
2196 for (auto module
: design
->modules()) {
2197 if (!design
->selected_module(module
))
2200 SigMap
&sigmap
= sigmaps
[module
];
2203 if (module
->get_bool_attribute(ID(cxxrtl_blackbox
))) {
2204 for (auto port
: module
->ports
) {
2205 RTLIL::Wire
*wire
= module
->wire(port
);
2206 if (wire
->port_input
&& !wire
->port_output
)
2207 unbuffered_wires
.insert(wire
);
2208 if (wire
->has_attribute(ID(cxxrtl_edge
))) {
2209 RTLIL::Const edge_attr
= wire
->attributes
[ID(cxxrtl_edge
)];
2210 if (!(edge_attr
.flags
& RTLIL::CONST_FLAG_STRING
) || (int)edge_attr
.decode_string().size() != GetSize(wire
))
2211 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' is not a string with one character per bit.\n",
2212 log_id(module
), log_signal(wire
));
2214 std::string edges
= wire
->get_string_attribute(ID(cxxrtl_edge
));
2215 for (int i
= 0; i
< GetSize(wire
); i
++) {
2216 RTLIL::SigSpec wire_sig
= wire
;
2219 case 'p': register_edge_signal(sigmap
, wire_sig
[i
], RTLIL::STp
); break;
2220 case 'n': register_edge_signal(sigmap
, wire_sig
[i
], RTLIL::STn
); break;
2221 case 'a': register_edge_signal(sigmap
, wire_sig
[i
], RTLIL::STe
); break;
2223 log_cmd_error("Attribute `cxxrtl_edge' of port `%s.%s' contains specifiers "
2224 "other than '-', 'p', 'n', or 'a'.\n",
2225 log_id(module
), log_signal(wire
));
2231 // Black boxes converge by default, since their implementations are quite unlikely to require
2232 // internal propagation of comb signals.
2233 eval_converges
[module
] = true;
2239 for (auto conn
: module
->connections())
2240 flow
.add_node(conn
);
2242 dict
<const RTLIL::Cell
*, FlowGraph::Node
*> memrw_cell_nodes
;
2243 dict
<std::pair
<RTLIL::SigBit
, const RTLIL::Memory
*>,
2244 pool
<const RTLIL::Cell
*>> memwr_per_domain
;
2245 for (auto cell
: module
->cells()) {
2247 log_cmd_error("Unknown cell `%s'.\n", log_id(cell
->type
));
2249 RTLIL::Module
*cell_module
= design
->module(cell
->type
);
2251 cell_module
->get_blackbox_attribute() &&
2252 !cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)))
2253 log_cmd_error("External blackbox cell `%s' is not marked as a CXXRTL blackbox.\n", log_id(cell
->type
));
2256 cell_module
->get_bool_attribute(ID(cxxrtl_blackbox
)) &&
2257 cell_module
->get_bool_attribute(ID(cxxrtl_template
)))
2258 blackbox_specializations
[cell_module
].insert(template_args(cell
));
2260 FlowGraph::Node
*node
= flow
.add_node(cell
);
2262 // Various DFF cells are treated like posedge/negedge processes, see above for details.
2263 if (cell
->type
.in(ID($dff
), ID($dffe
), ID($adff
), ID($adffe
), ID($dffsr
), ID($dffsre
), ID($sdff
), ID($sdffe
), ID($sdffce
))) {
2264 if (sigmap(cell
->getPort(ID::CLK
)).is_wire())
2265 register_edge_signal(sigmap
, cell
->getPort(ID::CLK
),
2266 cell
->parameters
[ID::CLK_POLARITY
].as_bool() ? RTLIL::STp
: RTLIL::STn
);
2268 // Similar for memory port cells.
2269 if (cell
->type
.in(ID($memrd
), ID($memwr
))) {
2270 if (cell
->getParam(ID::CLK_ENABLE
).as_bool()) {
2271 if (sigmap(cell
->getPort(ID::CLK
)).is_wire())
2272 register_edge_signal(sigmap
, cell
->getPort(ID::CLK
),
2273 cell
->parameters
[ID::CLK_POLARITY
].as_bool() ? RTLIL::STp
: RTLIL::STn
);
2275 memrw_cell_nodes
[cell
] = node
;
2277 // Optimize access to read-only memories.
2278 if (cell
->type
== ID($memwr
))
2279 writable_memories
.insert(module
->memories
[cell
->getParam(ID::MEMID
).decode_string()]);
2280 // Collect groups of memory write ports in the same domain.
2281 if (cell
->type
== ID($memwr
) && cell
->getParam(ID::CLK_ENABLE
).as_bool() && cell
->getPort(ID::CLK
).is_wire()) {
2282 RTLIL::SigBit clk_bit
= sigmap(cell
->getPort(ID::CLK
))[0];
2283 const RTLIL::Memory
*memory
= module
->memories
[cell
->getParam(ID::MEMID
).decode_string()];
2284 memwr_per_domain
[{clk_bit
, memory
}].insert(cell
);
2286 // Handling of packed memories is delegated to the `memory_unpack` pass, so we can rely on the presence
2287 // of RTLIL memory objects and $memrd/$memwr/$meminit cells.
2288 if (cell
->type
.in(ID($mem
)))
2291 for (auto cell
: module
->cells()) {
2292 // Collect groups of memory write ports read by every transparent read port.
2293 if (cell
->type
== ID($memrd
) && cell
->getParam(ID::CLK_ENABLE
).as_bool() && cell
->getPort(ID::CLK
).is_wire() &&
2294 cell
->getParam(ID::TRANSPARENT
).as_bool()) {
2295 RTLIL::SigBit clk_bit
= sigmap(cell
->getPort(ID::CLK
))[0];
2296 const RTLIL::Memory
*memory
= module
->memories
[cell
->getParam(ID::MEMID
).decode_string()];
2297 for (auto memwr_cell
: memwr_per_domain
[{clk_bit
, memory
}]) {
2298 transparent_for
[cell
].insert(memwr_cell
);
2299 // Our implementation of transparent $memrd cells reads \EN, \ADDR and \DATA from every $memwr cell
2300 // in the same domain, which isn't directly visible in the netlist. Add these uses explicitly.
2301 flow
.add_uses(memrw_cell_nodes
[cell
], memwr_cell
->getPort(ID::EN
));
2302 flow
.add_uses(memrw_cell_nodes
[cell
], memwr_cell
->getPort(ID::ADDR
));
2303 flow
.add_uses(memrw_cell_nodes
[cell
], memwr_cell
->getPort(ID::DATA
));
2308 for (auto proc
: module
->processes
) {
2309 flow
.add_node(proc
.second
);
2311 for (auto sync
: proc
.second
->syncs
)
2312 switch (sync
->type
) {
2313 // Edge-type sync rules require pre-registration.
2317 register_edge_signal(sigmap
, sync
->signal
, sync
->type
);
2320 // Level-type sync rules require no special handling.
2327 log_cmd_error("Global clock is not supported.\n");
2329 // Handling of init-type sync rules is delegated to the `proc_init` pass, so we can use the wire
2330 // attribute regardless of input.
2336 for (auto wire
: module
->wires()) {
2337 if (!flow
.is_inlinable(wire
)) continue;
2338 if (wire
->port_id
!= 0) continue;
2339 if (wire
->get_bool_attribute(ID::keep
)) continue;
2340 if (wire
->name
.begins_with("$") && !inline_internal
) continue;
2341 if (wire
->name
.begins_with("\\") && !inline_public
) continue;
2342 if (edge_wires
[wire
]) continue;
2343 if (flow
.wire_comb_defs
[wire
].size() > 1)
2344 log_cmd_error("Wire %s.%s has multiple drivers.\n", log_id(module
), log_id(wire
));
2345 log_assert(flow
.wire_comb_defs
[wire
].size() == 1);
2346 inlined_wires
[wire
] = **flow
.wire_comb_defs
[wire
].begin();
2349 dict
<FlowGraph::Node
*, pool
<const RTLIL::Wire
*>, hash_ptr_ops
> node_defs
;
2350 for (auto wire_comb_def
: flow
.wire_comb_defs
)
2351 for (auto node
: wire_comb_def
.second
)
2352 node_defs
[node
].insert(wire_comb_def
.first
);
2354 dict
<FlowGraph::Node
*, pool
<const RTLIL::Wire
*>, hash_ptr_ops
> node_uses
;
2355 for (auto wire_use
: flow
.wire_uses
)
2356 for (auto node
: wire_use
.second
)
2357 node_uses
[node
].insert(wire_use
.first
);
2359 Scheduler
<FlowGraph::Node
> scheduler
;
2360 dict
<FlowGraph::Node
*, Scheduler
<FlowGraph::Node
>::Vertex
*, hash_ptr_ops
> node_map
;
2361 for (auto node
: flow
.nodes
)
2362 node_map
[node
] = scheduler
.add(node
);
2363 for (auto node_def
: node_defs
) {
2364 auto vertex
= node_map
[node_def
.first
];
2365 for (auto wire
: node_def
.second
)
2366 for (auto succ_node
: flow
.wire_uses
[wire
]) {
2367 auto succ_vertex
= node_map
[succ_node
];
2368 vertex
->succs
.insert(succ_vertex
);
2369 succ_vertex
->preds
.insert(vertex
);
2373 auto eval_order
= scheduler
.schedule();
2374 pool
<FlowGraph::Node
*, hash_ptr_ops
> evaluated
;
2375 pool
<const RTLIL::Wire
*> feedback_wires
;
2376 for (auto vertex
: eval_order
) {
2377 auto node
= vertex
->data
;
2378 schedule
[module
].push_back(*node
);
2379 // Any wire that is an output of node vo and input of node vi where vo is scheduled later than vi
2380 // is a feedback wire. Feedback wires indicate apparent logic loops in the design, which may be
2381 // caused by a true logic loop, but usually are a benign result of dependency tracking that works
2382 // on wire, not bit, level. Nevertheless, feedback wires cannot be localized.
2383 evaluated
.insert(node
);
2384 for (auto wire
: node_defs
[node
])
2385 for (auto succ_node
: flow
.wire_uses
[wire
])
2386 if (evaluated
[succ_node
]) {
2387 feedback_wires
.insert(wire
);
2388 // Feedback wires may never be inlined because feedback requires state, but the point of
2389 // inlining (and localization) is to eliminate state.
2390 inlined_wires
.erase(wire
);
2394 if (!feedback_wires
.empty()) {
2395 has_feedback_arcs
= true;
2396 log("Module `%s' contains feedback arcs through wires:\n", log_id(module
));
2397 for (auto wire
: feedback_wires
)
2398 log(" %s\n", log_id(wire
));
2401 for (auto wire
: module
->wires()) {
2402 if (feedback_wires
[wire
]) continue;
2403 if (wire
->port_output
&& !module
->get_bool_attribute(ID::top
)) continue;
2404 if (wire
->name
.begins_with("$") && !unbuffer_internal
) continue;
2405 if (wire
->name
.begins_with("\\") && !unbuffer_public
) continue;
2406 if (flow
.wire_sync_defs
.count(wire
) > 0) continue;
2407 unbuffered_wires
.insert(wire
);
2408 if (edge_wires
[wire
]) continue;
2409 if (wire
->get_bool_attribute(ID::keep
)) continue;
2410 if (wire
->port_input
|| wire
->port_output
) continue;
2411 if (wire
->name
.begins_with("$") && !localize_internal
) continue;
2412 if (wire
->name
.begins_with("\\") && !localize_public
) continue;
2413 localized_wires
.insert(wire
);
2416 // For maximum performance, the state of the simulation (which is the same as the set of its double buffered
2417 // wires, since using a singly buffered wire for any kind of state introduces a race condition) should contain
2418 // no wires attached to combinatorial outputs. Feedback wires, by definition, make that impossible. However,
2419 // it is possible that a design with no feedback arcs would end up with doubly buffered wires in such cases
2420 // as a wire with multiple drivers where one of them is combinatorial and the other is synchronous. Such designs
2421 // also require more than one delta cycle to converge.
2422 pool
<const RTLIL::Wire
*> buffered_comb_wires
;
2423 for (auto wire
: module
->wires()) {
2424 if (flow
.wire_comb_defs
[wire
].size() > 0 && !unbuffered_wires
[wire
] && !feedback_wires
[wire
])
2425 buffered_comb_wires
.insert(wire
);
2427 if (!buffered_comb_wires
.empty()) {
2428 has_buffered_comb_wires
= true;
2429 log("Module `%s' contains buffered combinatorial wires:\n", log_id(module
));
2430 for (auto wire
: buffered_comb_wires
)
2431 log(" %s\n", log_id(wire
));
2434 eval_converges
[module
] = feedback_wires
.empty() && buffered_comb_wires
.empty();
2436 for (auto item
: flow
.bit_has_state
)
2437 bit_has_state
.insert(item
);
2439 if (debug_info
&& debug_eval
) {
2440 // Find wires that can be be outlined, i.e. whose values can be always recovered from
2441 // the values of other wires. (This is the inverse of inlining--any wire that can be
2442 // inlined can also be outlined.) Although this may seem strictly less efficient, since
2443 // such values are computed at least twice, second-order effects make outlining useful.
2444 pool
<const RTLIL::Wire
*> worklist
, visited
;
2445 for (auto wire
: module
->wires()) {
2446 if (!wire
->name
.isPublic())
2448 worklist
.insert(wire
);
2450 while (!worklist
.empty()) {
2451 const RTLIL::Wire
*wire
= worklist
.pop();
2452 visited
.insert(wire
);
2453 if (!localized_wires
.count(wire
) && !inlined_wires
.count(wire
))
2454 continue; // member wire, doesn't need outlining
2455 if (wire
->name
.isPublic() || !inlined_wires
.count(wire
))
2456 debug_outlined_wires
.insert(wire
); // allow outlining of internal wires only
2457 for (auto node
: flow
.wire_comb_defs
[wire
])
2458 for (auto node_use
: node_uses
[node
])
2459 if (!visited
.count(node_use
))
2460 worklist
.insert(node_use
);
2463 if (debug_info
&& debug_alias
) {
2464 // Find wires that alias other wires or are tied to a constant. Both of these cases are
2465 // directly expressible in the debug information, improving coverage at zero cost.
2466 for (auto wire
: module
->wires()) {
2467 if (!wire
->name
.isPublic())
2469 const RTLIL::Wire
*cursor
= wire
;
2470 RTLIL::SigSpec alias_of
;
2472 if (!(flow
.wire_def_inlinable
.count(cursor
) && flow
.wire_def_inlinable
[cursor
]))
2473 break; // not an alias: complex def
2474 log_assert(flow
.wire_comb_defs
[cursor
].size() == 1);
2475 FlowGraph::Node
*node
= *flow
.wire_comb_defs
[cursor
].begin();
2476 if (node
->type
!= FlowGraph::Node::Type::CONNECT
)
2477 break; // not an alias: def by cell
2478 RTLIL::SigSpec rhs_sig
= node
->connect
.second
;
2479 if (rhs_sig
.is_fully_const()) {
2480 alias_of
= rhs_sig
; // alias of const
2482 } else if (rhs_sig
.is_wire()) {
2483 RTLIL::Wire
*rhs_wire
= rhs_sig
.as_wire(); // possible alias of wire
2484 if (rhs_wire
->port_input
&& !rhs_wire
->port_output
) {
2485 alias_of
= rhs_wire
; // alias of input
2487 } else if (!localized_wires
.count(rhs_wire
) && !inlined_wires
.count(rhs_wire
)) {
2488 alias_of
= rhs_wire
; // alias of member
2491 if (rhs_wire
->name
.isPublic() && debug_outlined_wires
.count(rhs_wire
))
2492 alias_of
= rhs_wire
; // alias of either outline or another alias
2493 cursor
= rhs_wire
; // keep looking
2496 break; // not an alias: complex rhs
2499 if (alias_of
.empty()) {
2501 } else if (alias_of
.is_fully_const()) {
2502 debug_const_wires
[wire
] = alias_of
.as_const();
2503 } else if (alias_of
.is_wire()) {
2504 debug_alias_wires
[wire
] = alias_of
.as_wire();
2506 if (inlined_wires
.count(wire
))
2507 debug_outlined_wires
.erase(wire
);
2511 if (has_feedback_arcs
|| has_buffered_comb_wires
) {
2512 // Although both non-feedback buffered combinatorial wires and apparent feedback wires may be eliminated
2513 // by optimizing the design, if after `proc; flatten` there are any feedback wires remaining, it is very
2514 // likely that these feedback wires are indicative of a true logic loop, so they get emphasized in the message.
2515 const char *why_pessimistic
= nullptr;
2516 if (has_feedback_arcs
)
2517 why_pessimistic
= "feedback wires";
2518 else if (has_buffered_comb_wires
)
2519 why_pessimistic
= "buffered combinatorial wires";
2520 log_warning("Design contains %s, which require delta cycles during evaluation.\n", why_pessimistic
);
2522 log("Flattening may eliminate %s from the design.\n", why_pessimistic
);
2524 log("Converting processes to netlists may eliminate %s from the design.\n", why_pessimistic
);
2528 void check_design(RTLIL::Design
*design
, bool &has_top
, bool &has_sync_init
, bool &has_packed_mem
)
2530 has_sync_init
= has_packed_mem
= has_top
= false;
2532 for (auto module
: design
->modules()) {
2533 if (module
->get_blackbox_attribute() && !module
->has_attribute(ID(cxxrtl_blackbox
)))
2536 if (!design
->selected_whole_module(module
))
2537 if (design
->selected_module(module
))
2538 log_cmd_error("Can't handle partially selected module `%s'!\n", id2cstr(module
->name
));
2539 if (!design
->selected_module(module
))
2542 if (module
->get_bool_attribute(ID::top
))
2545 for (auto proc
: module
->processes
)
2546 for (auto sync
: proc
.second
->syncs
)
2547 if (sync
->type
== RTLIL::STi
)
2548 has_sync_init
= true;
2550 // The Mem constructor also checks for well-formedness of $meminit cells, if any.
2551 for (auto &mem
: Mem::get_all_memories(module
))
2553 has_packed_mem
= true;
2557 void prepare_design(RTLIL::Design
*design
)
2559 bool did_anything
= false;
2560 bool has_top
, has_sync_init
, has_packed_mem
;
2562 check_design(design
, has_top
, has_sync_init
, has_packed_mem
);
2563 if (run_hierarchy
&& !has_top
) {
2564 Pass::call(design
, "hierarchy -auto-top");
2565 did_anything
= true;
2568 Pass::call(design
, "flatten");
2569 did_anything
= true;
2572 Pass::call(design
, "proc");
2573 did_anything
= true;
2574 } else if (has_sync_init
) {
2575 // We're only interested in proc_init, but it depends on proc_prune and proc_clean, so call those
2576 // in case they weren't already. (This allows `yosys foo.v -o foo.cc` to work.)
2577 Pass::call(design
, "proc_prune");
2578 Pass::call(design
, "proc_clean");
2579 Pass::call(design
, "proc_init");
2580 did_anything
= true;
2582 if (has_packed_mem
) {
2583 Pass::call(design
, "memory_unpack");
2584 did_anything
= true;
2586 // Recheck the design if it was modified.
2588 check_design(design
, has_top
, has_sync_init
, has_packed_mem
);
2589 log_assert(has_top
&& !has_sync_init
&& !has_packed_mem
);
2593 analyze_design(design
);
2597 struct CxxrtlBackend
: public Backend
{
2598 static const int DEFAULT_OPT_LEVEL
= 6;
2599 static const int DEFAULT_DEBUG_LEVEL
= 3;
2601 CxxrtlBackend() : Backend("cxxrtl", "convert design to C++ RTL simulation") { }
2602 void help() override
2604 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
2606 log(" write_cxxrtl [options] [filename]\n");
2608 log("Write C++ code that simulates the design. The generated code requires a driver\n");
2609 log("that instantiates the design, toggles its clock, and interacts with its ports.\n");
2611 log("The following driver may be used as an example for a design with a single clock\n");
2612 log("driving rising edge triggered flip-flops:\n");
2614 log(" #include \"top.cc\"\n");
2616 log(" int main() {\n");
2617 log(" cxxrtl_design::p_top top;\n");
2618 log(" top.step();\n");
2619 log(" while (1) {\n");
2620 log(" /* user logic */\n");
2621 log(" top.p_clk.set(false);\n");
2622 log(" top.step();\n");
2623 log(" top.p_clk.set(true);\n");
2624 log(" top.step();\n");
2628 log("Note that CXXRTL simulations, just like the hardware they are simulating, are\n");
2629 log("subject to race conditions. If, in the example above, the user logic would run\n");
2630 log("simultaneously with the rising edge of the clock, the design would malfunction.\n");
2632 log("This backend supports replacing parts of the design with black boxes implemented\n");
2633 log("in C++. If a module marked as a CXXRTL black box, its implementation is ignored,\n");
2634 log("and the generated code consists only of an interface and a factory function.\n");
2635 log("The driver must implement the factory function that creates an implementation of\n");
2636 log("the black box, taking into account the parameters it is instantiated with.\n");
2638 log("For example, the following Verilog code defines a CXXRTL black box interface for\n");
2639 log("a synchronous debug sink:\n");
2641 log(" (* cxxrtl_blackbox *)\n");
2642 log(" module debug(...);\n");
2643 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2644 log(" input en;\n");
2645 log(" input [7:0] i_data;\n");
2646 log(" (* cxxrtl_sync *) output [7:0] o_data;\n");
2647 log(" endmodule\n");
2649 log("For this HDL interface, this backend will generate the following C++ interface:\n");
2651 log(" struct bb_p_debug : public module {\n");
2652 log(" value<1> p_clk;\n");
2653 log(" bool posedge_p_clk() const { /* ... */ }\n");
2654 log(" value<1> p_en;\n");
2655 log(" value<8> p_i_data;\n");
2656 log(" wire<8> p_o_data;\n");
2658 log(" bool eval() override;\n");
2659 log(" bool commit() override;\n");
2661 log(" static std::unique_ptr<bb_p_debug>\n");
2662 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2665 log("The `create' function must be implemented by the driver. For example, it could\n");
2666 log("always provide an implementation logging the values to standard error stream:\n");
2668 log(" namespace cxxrtl_design {\n");
2670 log(" struct stderr_debug : public bb_p_debug {\n");
2671 log(" bool eval() override {\n");
2672 log(" if (posedge_p_clk() && p_en)\n");
2673 log(" fprintf(stderr, \"debug: %%02x\\n\", p_i_data.data[0]);\n");
2674 log(" p_o_data.next = p_i_data;\n");
2675 log(" return bb_p_debug::eval();\n");
2679 log(" std::unique_ptr<bb_p_debug>\n");
2680 log(" bb_p_debug::create(std::string name, cxxrtl::metadata_map parameters,\n");
2681 log(" cxxrtl::metadata_map attributes) {\n");
2682 log(" return std::make_unique<stderr_debug>();\n");
2687 log("For complex applications of black boxes, it is possible to parameterize their\n");
2688 log("port widths. For example, the following Verilog code defines a CXXRTL black box\n");
2689 log("interface for a configurable width debug sink:\n");
2691 log(" (* cxxrtl_blackbox, cxxrtl_template = \"WIDTH\" *)\n");
2692 log(" module debug(...);\n");
2693 log(" parameter WIDTH = 8;\n");
2694 log(" (* cxxrtl_edge = \"p\" *) input clk;\n");
2695 log(" input en;\n");
2696 log(" (* cxxrtl_width = \"WIDTH\" *) input [WIDTH - 1:0] i_data;\n");
2697 log(" (* cxxrtl_width = \"WIDTH\" *) output [WIDTH - 1:0] o_data;\n");
2698 log(" endmodule\n");
2700 log("For this parametric HDL interface, this backend will generate the following C++\n");
2701 log("interface (only the differences are shown):\n");
2703 log(" template<size_t WIDTH>\n");
2704 log(" struct bb_p_debug : public module {\n");
2706 log(" value<WIDTH> p_i_data;\n");
2707 log(" wire<WIDTH> p_o_data;\n");
2709 log(" static std::unique_ptr<bb_p_debug<WIDTH>>\n");
2710 log(" create(std::string name, metadata_map parameters, metadata_map attributes);\n");
2713 log("The `create' function must be implemented by the driver, specialized for every\n");
2714 log("possible combination of template parameters. (Specialization is necessary to\n");
2715 log("enable separate compilation of generated code and black box implementations.)\n");
2717 log(" template<size_t SIZE>\n");
2718 log(" struct stderr_debug : public bb_p_debug<SIZE> {\n");
2722 log(" template<>\n");
2723 log(" std::unique_ptr<bb_p_debug<8>>\n");
2724 log(" bb_p_debug<8>::create(std::string name, cxxrtl::metadata_map parameters,\n");
2725 log(" cxxrtl::metadata_map attributes) {\n");
2726 log(" return std::make_unique<stderr_debug<8>>();\n");
2729 log("The following attributes are recognized by this backend:\n");
2731 log(" cxxrtl_blackbox\n");
2732 log(" only valid on modules. if specified, the module contents are ignored,\n");
2733 log(" and the generated code includes only the module interface and a factory\n");
2734 log(" function, which will be called to instantiate the module.\n");
2736 log(" cxxrtl_edge\n");
2737 log(" only valid on inputs of black boxes. must be one of \"p\", \"n\", \"a\".\n");
2738 log(" if specified on signal `clk`, the generated code includes edge detectors\n");
2739 log(" `posedge_p_clk()` (if \"p\"), `negedge_p_clk()` (if \"n\"), or both (if\n");
2740 log(" \"a\"), simplifying implementation of clocked black boxes.\n");
2742 log(" cxxrtl_template\n");
2743 log(" only valid on black boxes. must contain a space separated sequence of\n");
2744 log(" identifiers that have a corresponding black box parameters. for each\n");
2745 log(" of them, the generated code includes a `size_t` template parameter.\n");
2747 log(" cxxrtl_width\n");
2748 log(" only valid on ports of black boxes. must be a constant expression, which\n");
2749 log(" is directly inserted into generated code.\n");
2751 log(" cxxrtl_comb, cxxrtl_sync\n");
2752 log(" only valid on outputs of black boxes. if specified, indicates that every\n");
2753 log(" bit of the output port is driven, correspondingly, by combinatorial or\n");
2754 log(" synchronous logic. this knowledge is used for scheduling optimizations.\n");
2755 log(" if neither is specified, the output will be pessimistically treated as\n");
2756 log(" driven by both combinatorial and synchronous logic.\n");
2758 log("The following options are supported by this backend:\n");
2761 log(" generate separate interface (.h) and implementation (.cc) files.\n");
2762 log(" if specified, the backend must be called with a filename, and filename\n");
2763 log(" of the interface is derived from filename of the implementation.\n");
2764 log(" otherwise, interface and implementation are generated together.\n");
2766 log(" -namespace <ns-name>\n");
2767 log(" place the generated code into namespace <ns-name>. if not specified,\n");
2768 log(" \"cxxrtl_design\" is used.\n");
2770 log(" -nohierarchy\n");
2771 log(" use design hierarchy as-is. in most designs, a top module should be\n");
2772 log(" present as it is exposed through the C API and has unbuffered outputs\n");
2773 log(" for improved performance; it will be determined automatically if absent.\n");
2775 log(" -noflatten\n");
2776 log(" don't flatten the design. fully flattened designs can evaluate within\n");
2777 log(" one delta cycle if they have no combinatorial feedback.\n");
2778 log(" note that the debug interface and waveform dumps use full hierarchical\n");
2779 log(" names for all wires even in flattened designs.\n");
2782 log(" don't convert processes to netlists. in most designs, converting\n");
2783 log(" processes significantly improves evaluation performance at the cost of\n");
2784 log(" slight increase in compilation time.\n");
2786 log(" -O <level>\n");
2787 log(" set the optimization level. the default is -O%d. higher optimization\n", DEFAULT_OPT_LEVEL
);
2788 log(" levels dramatically decrease compile and run time, and highest level\n");
2789 log(" possible for a design should be used.\n");
2792 log(" no optimization.\n");
2795 log(" localize internal wires if possible.\n");
2798 log(" like -O1, and unbuffer internal wires if possible.\n");
2801 log(" like -O2, and inline internal wires if possible.\n");
2804 log(" like -O3, and unbuffer public wires not marked (*keep*) if possible.\n");
2807 log(" like -O4, and localize public wires not marked (*keep*) if possible.\n");
2810 log(" like -O5, and inline public wires not marked (*keep*) if possible.\n");
2812 log(" -g <level>\n");
2813 log(" set the debug level. the default is -g%d. higher debug levels provide\n", DEFAULT_DEBUG_LEVEL
);
2814 log(" more visibility and generate more code, but do not pessimize evaluation.\n");
2817 log(" no debug information. the C API is unavailable.\n");
2820 log(" debug information for member public wires only. this is the bare minimum\n");
2821 log(" necessary to access all design state. enables the C API.\n");
2824 log(" like -g1, and include debug information for public wires that are tied\n");
2825 log(" to a constant or another public wire.\n");
2828 log(" like -g2, and compute debug information on demand for all public wires\n");
2829 log(" that were optimized out.\n");
2833 void execute(std::ostream
*&f
, std::string filename
, std::vector
<std::string
> args
, RTLIL::Design
*design
) override
2835 bool nohierarchy
= false;
2836 bool noflatten
= false;
2837 bool noproc
= false;
2838 int opt_level
= DEFAULT_OPT_LEVEL
;
2839 int debug_level
= DEFAULT_DEBUG_LEVEL
;
2840 CxxrtlWorker worker
;
2842 log_header(design
, "Executing CXXRTL backend.\n");
2845 for (argidx
= 1; argidx
< args
.size(); argidx
++)
2847 if (args
[argidx
] == "-nohierarchy") {
2851 if (args
[argidx
] == "-noflatten") {
2855 if (args
[argidx
] == "-noproc") {
2859 if (args
[argidx
] == "-Og") {
2860 log_warning("The `-Og` option has been removed. Use `-g3` instead for complete "
2861 "design coverage regardless of optimization level.\n");
2864 if (args
[argidx
] == "-O" && argidx
+1 < args
.size() && args
[argidx
+1] == "g") {
2866 log_warning("The `-Og` option has been removed. Use `-g3` instead for complete "
2867 "design coverage regardless of optimization level.\n");
2870 if (args
[argidx
] == "-O" && argidx
+1 < args
.size()) {
2871 opt_level
= std::stoi(args
[++argidx
]);
2874 if (args
[argidx
].substr(0, 2) == "-O" && args
[argidx
].size() == 3 && isdigit(args
[argidx
][2])) {
2875 opt_level
= std::stoi(args
[argidx
].substr(2));
2878 if (args
[argidx
] == "-g" && argidx
+1 < args
.size()) {
2879 debug_level
= std::stoi(args
[++argidx
]);
2882 if (args
[argidx
].substr(0, 2) == "-g" && args
[argidx
].size() == 3 && isdigit(args
[argidx
][2])) {
2883 debug_level
= std::stoi(args
[argidx
].substr(2));
2886 if (args
[argidx
] == "-header") {
2887 worker
.split_intf
= true;
2890 if (args
[argidx
] == "-namespace" && argidx
+1 < args
.size()) {
2891 worker
.design_ns
= args
[++argidx
];
2896 extra_args(f
, filename
, args
, argidx
);
2898 worker
.run_hierarchy
= !nohierarchy
;
2899 worker
.run_flatten
= !noflatten
;
2900 worker
.run_proc
= !noproc
;
2901 switch (opt_level
) {
2902 // the highest level here must match DEFAULT_OPT_LEVEL
2904 worker
.inline_public
= true;
2907 worker
.localize_public
= true;
2910 worker
.unbuffer_public
= true;
2913 worker
.inline_internal
= true;
2916 worker
.localize_internal
= true;
2919 worker
.unbuffer_internal
= true;
2924 log_cmd_error("Invalid optimization level %d.\n", opt_level
);
2926 switch (debug_level
) {
2927 // the highest level here must match DEFAULT_DEBUG_LEVEL
2929 worker
.debug_eval
= true;
2932 worker
.debug_alias
= true;
2935 worker
.debug_info
= true;
2940 log_cmd_error("Invalid debug information level %d.\n", debug_level
);
2943 std::ofstream intf_f
;
2944 if (worker
.split_intf
) {
2945 if (filename
== "<stdout>")
2946 log_cmd_error("Option -header must be used with a filename.\n");
2948 worker
.intf_filename
= filename
.substr(0, filename
.rfind('.')) + ".h";
2949 intf_f
.open(worker
.intf_filename
, std::ofstream::trunc
);
2951 log_cmd_error("Can't open file `%s' for writing: %s\n",
2952 worker
.intf_filename
.c_str(), strerror(errno
));
2954 worker
.intf_f
= &intf_f
;
2958 worker
.prepare_design(design
);
2959 worker
.dump_design(design
);
2963 PRIVATE_NAMESPACE_END