aboutsummaryrefslogtreecommitdiffstats
path: root/passes/techmap/extract.cc
blob: 137d22170640fa99ad4a9616f02f2890a2fe58f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
pre { line-height: 125%; margin: 0; }
td.linenos pre { color: #000000; background-color: #f0f0f0; padding: 0 5px 0 5px; }
span.linenos { color: #000000; background-color: #f0f0f0; padding: 0 5px 0 5px; }
td.linenos pre.special { color: #000000; background-color: #ffffc0; padding: 0 5px 0 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding: 0 5px 0 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight { background: #ffffff; }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2017 Robert Ou <rqou@robertou.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthCoolrunner2Pass : public ScriptPass
{
	SynthCoolrunner2Pass() : ScriptPass("synth_coolrunner2", "synthesis for Xilinx Coolrunner-II CPLDs") { }

	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    synth_coolrunner2 [options]\n");
		log("\n");
		log("This command runs synthesis for Coolrunner-II CPLDs. This work is experimental.\n");
		log("It is intended to be used with https://github.com/azonenberg/openfpga as the\n");
		log("place-and-route.\n");
		log("\n");
		log("    -top <module>\n");
		log("        use the specified module as top module (default='top')\n");
		log("\n");
		log("    -json <file>\n");
		log("        write the design to the specified JSON file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -run <from_label>:<to_label>\n");
		log("        only run the commands between the labels (see below). an empty\n");
		log("        from label is synonymous to 'begin', and empty to label is\n");
		log("        synonymous to the end of the command list.\n");
		log("\n");
		log("    -noflatten\n");
		log("        do not flatten design before synthesis\n");
		log("\n");
		log("    -retime\n");
		log("        run 'abc' with -dff option\n");
		log("\n");
		log("\n");
		log("The following commands are executed by this synthesis command:\n");
		help_script();
		log("\n");
	}

	string top_opt, json_file;
	bool flatten, retime;

	void clear_flags() YS_OVERRIDE
	{
		top_opt = "-auto-top";
		json_file = "";
		flatten = true;
		retime = false;
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		string run_from, run_to;
		clear_flags();

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				top_opt = "-top " + args[++argidx];
				continue;
			}
			if (args[argidx] == "-json" && argidx+1 < args.size()) {
				json_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-run" && argidx+1 < args.size()) {
				size_t pos = args[argidx+1].find(':');
				if (pos == std::string::npos)
					break;
				run_from = args[++argidx].substr(0, pos);
				run_to = args[argidx].substr(pos+1);
				continue;
			}
			if (args[argidx] == "-noflatten") {
				flatten = false;
				continue;
			}
			if (args[argidx] == "-retime") {
				retime = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (!design->full_selection())
			log_cmd_error("This command only operates on fully selected designs!\n");

		log_header(design, "Executing SYNTH_COOLRUNNER2 pass.\n");
		log_push();

		run_script(design, run_from, run_to);

		log_pop();
	}

	void script() YS_OVERRIDE
	{
		if (check_label("begin"))
		{
			run("read_verilog -lib +/coolrunner2/cells_sim.v");
			run(stringf("hierarchy -check %s", help_mode ? "-top <top>" : top_opt.c_str()));
		}

		if (flatten && check_label("flatten", "(unless -noflatten)"))
		{
			run("proc");
			run("flatten");
			run("tribuf -logic");
		}

		if (check_label("coarse"))
		{
			run("synth -run coarse");
		}

		if (check_label("fine"))
		{
			run("opt -fast -full");
			run("techmap");
			run("techmap -map +/coolrunner2/cells_latch.v");
			run("dfflibmap -prepare -liberty +/coolrunner2/xc2_dff.lib");
		}

		if (check_label("map_tff"))
		{
			// This is quite hacky. By telling abc that it can only use AND and XOR gates, abc will try and use XOR
			// gates "whenever possible." This will hopefully cause toggle flip-flop structures to turn into an XOR
			// connected to a D flip-flop. We then match on these and convert them into XC2 TFF cells.
			run("abc -g AND,XOR");
			run("clean");
			run("extract -map +/coolrunner2/tff_extract.v");
		}

		if (check_label("map_pla"))
		{
			run("abc -sop -I 40 -P 56");
			run("clean");
		}

		if (check_label("map_cells"))
		{
			run("dfflibmap -liberty +/coolrunner2/xc2_dff.lib");
			run("dffinit -ff FDCP Q INIT");
			run("dffinit -ff FDCP_N Q INIT");
			run("dffinit -ff FTCP Q INIT");
			run("dffinit -ff FTCP_N Q INIT");
			run("dffinit -ff LDCP Q INIT");
			run("dffinit -ff LDCP_N Q INIT");
			run("co	std::set<RTLIL::IdString> cell_attr, wire_attr;

	SubCircuitSolver() : ignore_parameters(false)
	{
	}

	bool compareAttributes(const std::set<RTLIL::IdString> &attr, const dict<RTLIL::IdString, RTLIL::Const> &needleAttr, const dict<RTLIL::IdString, RTLIL::Const> &haystackAttr)
	{
		for (auto &it : attr) {
			size_t nc = needleAttr.count(it), hc = haystackAttr.count(it);
			if (nc
pan class="n">at(it) != haystackAttr.at(it))) return false; } return true; } RTLIL::Const unified_param(RTLIL::IdString cell_type, RTLIL::IdString param, RTLIL::Const value) { if (!cell_type.begins_with("$") || cell_type.begins_with("$_")) return value; #define param_bool(_n) if (param == _n) return value.as_bool(); param_bool(ID::ARST_POLARITY); param_bool(ID::A_SIGNED); param_bool(ID::B_SIGNED); param_bool(ID::CLK_ENABLE); param_bool(ID::CLK_POLARITY); param_bool(ID::CLR_POLARITY); param_bool(ID::EN_POLARITY); param_bool(ID::SET_POLARITY); param_bool(ID::TRANSPARENT); #undef param_bool #define param_int(_n) if (param == _n) return value.as_int(); param_int(ID::ABITS) param_int(ID::A_WIDTH) param_int(ID::B_WIDTH) param_int(ID::CTRL_IN_WIDTH) param_int(ID::CTRL_OUT_WIDTH) param_int(ID::OFFSET) param_int(ID::PORTID) param_int(ID::PRIORITY) param_int(ID::RD_PORTS) param_int(ID::SIZE) param_int(ID::STATE_BITS) param_int(ID::STATE_NUM) param_int(ID::STATE_NUM_LOG2) param_int(ID::STATE_RST) param_int(ID::S_WIDTH) param_int(ID::TRANS_NUM) param_int(ID::WIDTH) param_int(ID::WR_PORTS) param_int(ID::Y_WIDTH) #undef param_int return value; } virtual bool userCompareNodes(const std::string &, const std::string &, void *needleUserData, const std::string &, const std::string &, void *haystackUserData, const std::map<std::string, std::string> &portMapping) { RTLIL::Cell *needleCell = (RTLIL::Cell*) needleUserData; RTLIL::Cell *haystackCell = (RTLIL::Cell*) haystackUserData; if (!needleCell || !haystackCell) { log_assert(!needleCell && !haystackCell); return true; } if (!ignore_parameters) { std::map<RTLIL::IdString, RTLIL::Const> needle_param, haystack_param; for (auto &it : needleCell->parameters) if (!ignored_parameters.count(std::pair<RTLIL::IdString, RTLIL::IdString>(needleCell->type, it.first))) needle_param[it.first] = unified_param(needleCell->type, it.first, it.second); for (auto &it : haystackCell->parameters) if (!ignored_parameters.count(std::pair<RTLIL::IdString, RTLIL::IdString>(haystackCell->type, it.first))) haystack_param[it.first] = unified_param(haystackCell->type, it.first, it.second); if (needle_param != haystack_param) return false; } if (cell_attr.size() > 0 && !compareAttributes(cell_attr, needleCell->attributes, haystackCell->attributes)) return false; if (wire_attr.size() > 0) { RTLIL::Wire *lastNeedleWire = nullptr; RTLIL::Wire *lastHaystackWire = nullptr; dict<RTLIL::IdString, RTLIL::Const> emptyAttr; for (auto &conn : needleCell->connections()) { RTLIL::SigSpec needleSig = conn.second; RTLIL::SigSpec haystackSig = haystackCell->getPort(portMapping.at(conn.first.str())); for (int i = 0; i < min(needleSig.size(), haystackSig.size()); i++) { RTLIL::Wire *needleWire = needleSig[i].wire, *haystackWire = haystackSig[i].wire; if (needleWire != lastNeedleWire || haystackWire != lastHaystackWire) if (!compareAttributes(wire_attr, needleWire ? needleWire->attributes : emptyAttr, haystackWire ? haystackWire->attributes : emptyAttr)) return false; lastNeedleWire = needleWire, lastHaystackWire = haystackWire; } } } return true; } }; struct bit_ref_t { std::string cell, port; int bit; }; bool module2graph(SubCircuit::Graph &graph, RTLIL::Module *mod, bool constports, RTLIL::Design *sel = nullptr, int max_fanout = -1, std::set<std::pair<RTLIL::IdString, RTLIL::IdString>> *split = nullptr) { SigMap sigmap(mod); std::map<RTLIL::SigBit, bit_ref_t> sig_bit_ref; if (sel && !sel->selected(mod)) { log(" Skipping module %s as it is not selected.\n", log_id(mod->name)); return false; } if (mod->processes.size() > 0) { log(" Skipping module %s as it contains unprocessed processes.\n", log_id(mod->name)); return false; } if (constports) { graph.createNode("$const$0", "$const$0", nullptr, true); graph.createNode("$const$1", "$const$1", nullptr, true); graph.createNode("$const$x", "$const$x", nullptr, true); graph.createNode("$const$z", "$const$z", nullptr, true); graph.createPort("$const$0", "\\Y", 1); graph.createPort("$const$1", "\\Y", 1); graph.createPort("$const$x", "\\Y", 1); graph.createPort("$const$z", "\\Y", 1); graph.markExtern("$const$0", "\\Y", 0); graph.markExtern("$const$1", "\\Y", 0); graph.markExtern("$const$x", "\\Y", 0); graph.markExtern("$const$z", "\\Y", 0); } std::map<std::pair<RTLIL::Wire*, int>, int> sig_use_count; if (max_fanout > 0) for (auto cell : mod->cells()) { if (!sel || sel->selected(mod, cell)) for (auto &conn : cell->connections()) { RTLIL::SigSpec conn_sig = conn.second; sigmap.apply(conn_sig); for (auto &bit : conn_sig) if (bit.wire != nullptr) sig_use_count[std::pair<RTLIL::Wire*, int>(bit.wire, bit.offset)]++; } } // create graph nodes from cells for (auto cell : mod->cells()) { if (sel && !sel->selected(mod, cell)) continue; std::string type = cell->type.str(); if (sel == nullptr && type.compare(0, 2, "\\$") == 0) type = type.substr(1); graph.createNode(cell->name.str(), type, (void*)cell); for (auto &conn : cell->connections()) { graph.createPort(cell->name.str(), conn.first.str(), conn.second.size()); if (split && split->count(std::pair<RTLIL::IdString, RTLIL::IdString>(cell->type, conn.first)) > 0) continue; RTLIL::SigSpec conn_sig = conn.second; sigmap.apply(conn_sig); for (int i = 0; i < conn_sig.size(); i++) { auto &bit = conn_sig[i]; if (bit.wire == nullptr) { if (constports) { std::string node = "$const$x"; if (bit == RTLIL::State::S0) node = "$const$0"; if (bit == RTLIL::State::S1) node = "$const$1"; if (bit == RTLIL::State::Sz) node = "$const$z"; graph.createConnection(cell->name.str(), conn.first.str(), i, node, "\\Y", 0); } else graph.createConstant(cell->name.str(), conn.first.str(), i, int(bit.data)); continue; } if (max_fanout > 0 && sig_use_count[std::pair<RTLIL::Wire*, int>(bit.wire, bit.offset)] > max_fanout) continue; if (sel && !sel->selected(mod, bit.wire)) continue; if (sig_bit_ref.count(bit) == 0) { bit_ref_t &bit_ref = sig_bit_ref[bit]; bit_ref.cell = cell->name.str(); bit_ref.port = conn.first.str(); bit_ref.bit = i; } bit_ref_t &bit_ref = sig_bit_ref[bit]; graph.createConnection(bit_ref.cell, bit_ref.port, bit_ref.bit, cell->name.str(), conn.first.str(), i); } } } // mark external signals (used in non-selected cells) for (auto cell : mod->cells()) { if (sel && !sel->selected(mod, cell)) for (auto &conn : cell->connections()) { RTLIL::SigSpec conn_sig = conn.second; sigmap.apply(conn_sig); for (auto &bit : conn_sig) if (sig_bit_ref.count(bit) != 0) { bit_ref_t &bit_ref = sig_bit_ref[bit]; graph.markExtern(bit_ref.cell, bit_ref.port, bit_ref.bit); } } } // mark external signals (used in module ports) for (auto wire : mod->wires()) { if (wire->port_id > 0) { RTLIL::SigSpec conn_sig(wire); sigmap.apply(conn_sig); for (auto &bit : conn_sig) if (sig_bit_ref.count(bit) != 0) { bit_ref_t &bit_ref = sig_bit_ref[bit]; graph.markExtern(bit_ref.cell, bit_ref.port, bit_ref.bit); } } } // graph.print(); return true; } RTLIL::Cell *replace(RTLIL::Module *needle, RTLIL::Module *haystack, SubCircuit::Solver::Result &match) { SigMap sigmap(needle); SigSet<std::pair<RTLIL::IdString, int>> sig2port; // create new cell RTLIL::Cell *cell = haystack->addCell(stringf("$extract$%s$%d", needle->name.c_str(), autoidx++), needle->name); // create cell ports for (auto wire : needle->wires()) { if (wire->port_id > 0) { for (int i = 0; i < wire->width; i++) sig2port.insert(sigmap(RTLIL::SigSpec(wire, i)), std::pair<RTLIL::IdString, int>(wire->name, i)); cell->setPort(wire->name, RTLIL::SigSpec(RTLIL::State::Sz, wire->width)); } } // delete replaced cells and connect new ports for (auto &it : match.mappings) { auto &mapping = it.second; RTLIL::Cell *needle_cell = (RTLIL::Cell*)mapping.needleUserData; RTLIL::Cell *haystack_cell = (RTLIL::Cell*)mapping.haystackUserData; if (needle_cell == nullptr) continue; for (auto &conn : needle_cell->connections()) { RTLIL::SigSpec sig = sigmap(conn.second); if (mapping.portMapping.count(conn.first.str()) > 0 && sig2port.has(sigmap(sig))) { for (int i = 0; i < sig.size(); i++) for (auto &port : sig2port.find(sig[i])) { RTLIL::SigSpec bitsig = haystack_cell->getPort(mapping.portMapping[conn.first.str()]).extract(i, 1); RTLIL::SigSpec new_sig = cell->getPort(port.first); new_sig.replace(port.second, bitsig); cell->setPort(port.first, new_sig); } } } haystack->remove(haystack_cell); } return cell; } bool compareSortNeedleList(RTLIL::Module *left, RTLIL::Module *right) { int left_idx = 0, right_idx = 0; if (left->attributes.count(ID::extract_order) > 0) left_idx = left->attributes.at(ID::extract_order).as_int(); if (right->attributes.count(ID::extract_order) > 0) right_idx = right->attributes.at(ID::extract_order).as_int(); if (left_idx != right_idx) return left_idx < right_idx; return left->name < right->name; } struct ExtractPass : public Pass { ExtractPass() : Pass("extract", "find subcircuits and replace them with cells") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" extract -map <map_file> [options] [selection]\n"); log(" extract -mine <out_file> [options] [selection]\n"); log("\n"); log("This pass looks for subcircuits that are isomorphic to any of the modules\n"); log("in the given map file and replaces them with instances of this modules. The\n"); log("map file can be a Verilog source file (*.v) or an RTLIL source file (*.il).\n"); log("\n"); log(" -map <map_file>\n"); log(" use the modules in this file as reference. This option can be used\n"); log(" multiple times.\n"); log("\n"); log(" -map %%<design-name>\n"); log(" use the modules in this in-memory design as reference. This option can\n"); log(" be used multiple times.\n"); log("\n"); log(" -verbose\n"); log(" print debug output while analyzing\n"); log("\n"); log(" -constports\n"); log(" also find instances with constant drivers. this may be much\n"); log(" slower than the normal operation.\n"); log("\n"); log(" -nodefaultswaps\n"); log(" normally builtin port swapping rules for internal cells are used per\n"); log(" default. This turns that off, so e.g. 'a^b' does not match 'b^a'\n"); log(" when this option is used.\n"); log("\n"); log(" -compat <needle_type> <haystack_type>\n"); log(" Per default, the cells in the map file (needle) must have the\n"); log(" type as the cells in the active design (haystack). This option\n"); log(" can be used to register additional pairs of types that should\n"); log(" match. This option can be used multiple times.\n"); log("\n"); log(" -swap <needle_type> <port1>,<port2>[,...]\n"); log(" Register a set of swappable ports for a needle cell type.\n"); log(" This option can be used multiple times.\n"); log("\n"); log(" -perm <needle_type> <port1>,<port2>[,...] <portA>,<portB>[,...]\n"); log(" Register a valid permutation of swappable ports for a needle\n"); log(" cell type. This option can be used multiple times.\n"); log("\n"); log(" -cell_attr <attribute_name>\n"); log(" Attributes on cells with the given name must match.\n"); log("\n"); log(" -wire_attr <attribute_name>\n"); log(" Attributes on wires with the given name must match.\n"); log("\n"); log(" -ignore_parameters\n"); log(" Do not use parameters when matching cells.\n"); log("\n"); log(" -ignore_param <cell_type> <parameter_name>\n"); log(" Do not use this parameter when matching cells.\n"); log("\n"); log("This pass does not operate on modules with unprocessed processes in it.\n"); log("(I.e. the 'proc' pass should be used first to convert processes to netlists.)\n"); log("\n"); log("This pass can also be used for mining for frequent subcircuits. In this mode\n"); log("the following options are to be used instead of the -map option.\n"); log("\n"); log(" -mine <out_file>\n"); log(" mine for frequent subcircuits and write them to the given RTLIL file\n"); log("\n"); log(" -mine_cells_span <min> <max>\n"); log(" only mine for subcircuits with the specified number of cells\n"); log(" default value: 3 5\n"); log("\n"); log(" -mine_min_freq <num>\n"); log(" only mine for subcircuits with at least the specified number of matches\n"); log(" default value: 10\n"); log("\n"); log(" -mine_limit_matches_per_module <num>\n"); log(" when calculating the number of matches for a subcircuit, don't count\n"); log(" more than the specified number of matches per module\n"); log("\n"); log(" -mine_max_fanout <num>\n"); log(" don't consider internal signals with more than <num> connections\n"); log("\n"); log("The modules in the map file may have the attribute 'extract_order' set to an\n"); log("integer value. Then this value is used to determine the order in which the pass\n"); log("tries to map the modules to the design (ascending, default value is 0).\n"); log("\n"); log("See 'help techmap' for a pass that does the opposite thing.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { log_header(design, "Executing EXTRACT pass (map subcircuits to cells).\n"); log_push(); SubCircuitSolver solver; std::vector<std::string> map_filenames; std::string mine_outfile; bool constports = false; bool nodefaultswaps = false; bool mine_mode = false; int mine_cells_min = 3; int mine_cells_max = 5; int mine_min_freq = 10; int mine_limit_mod = -1; int mine_max_fanout = -1; std::set<std::pair<RTLIL::IdString, RTLIL::IdString>> mine_split; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-map" && argidx+1 < args.size()) { if (mine_mode) log_cmd_error("You cannot mix -map and -mine.\n"); map_filenames.push_back(args[++argidx]); continue; } if (args[argidx] == "-mine" && argidx+1 < args.size()) { if (!map_filenames.empty()) log_cmd_error("You cannot mix -map and -mine.\n"); mine_outfile = args[++argidx]; mine_mode = true; continue; } if (args[argidx] == "-mine_cells_span" && argidx+2 < args.size()) { mine_cells_min = atoi(args[++argidx].c_str()); mine_cells_max = atoi(args[++argidx].c_str()); continue; } if (args[argidx] == "-mine_min_freq" && argidx+1 < args.size()) { mine_min_freq = atoi(args[++argidx].c_str()); continue; } if (args[argidx] == "-mine_limit_matches_per_module" && argidx+1 < args.size()) { mine_limit_mod = atoi(args[++argidx].c_str()); continue; } if (args[argidx] == "-mine_split" && argidx+2 < args.size()) { mine_split.insert(std::pair<RTLIL::IdString, RTLIL::IdString>(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2]))); argidx += 2; continue; } if (args[argidx] == "-mine_max_fanout" && argidx+1 < args.size()) { mine_max_fanout = atoi(args[++argidx].c_str()); continue; } if (args[argidx] == "-verbose") { solver.setVerbose(); continue; } if (args[argidx] == "-constports") { constports = true; continue; } if (args[argidx] == "-nodefaultswaps") { nodefaultswaps = true; continue; } if (args[argidx] == "-compat" && argidx+2 < args.size()) { std::string needle_type = RTLIL::escape_id(args[++argidx]); std::string haystack_type = RTLIL::escape_id(args[++argidx]); solver.addCompatibleTypes(needle_type, haystack_type); continue; } if (args[argidx] == "-swap" && argidx+2 < args.size()) { std::string type = RTLIL::escape_id(args[++argidx]); std::set<std::string> ports; std::string ports_str = args[++argidx], p; while (!(p = next_token(ports_str, ",\t\r\n ")).empty()) ports.insert(RTLIL::escape_id(p)); solver.addSwappablePorts(type, ports); continue; } if (args[argidx] == "-perm" && argidx+3 < args.size()) { std::string type = RTLIL::escape_id(args[++argidx]); std::vector<std::string> map_left, map_right; std::string left_str = args[++argidx]; std::string right_str = args[++argidx], p; while (!(p = next_token(left_str, ",\t\r\n ")).empty()) map_left.push_back(RTLIL::escape_id(p)); while (!(p = next_token(right_str, ",\t\r\n ")).empty()) map_right.push_back(RTLIL::escape_id(p)); if (map_left.size() != map_right.size()) log_cmd_error("Arguments to -perm are not a valid permutation!\n"); std::map<std::string, std::string> map; for (size_t i = 0; i < map_left.size(); i++) map[map_left[i]] = map_right[i]; std::sort(map_left.begin(), map_left.end()); std::sort(map_right.begin(), map_right.end()); if (map_left != map_right) log_cmd_error("Arguments to -perm are not a valid permutation!\n"); solver.addSwappablePortsPermutation(type, map); continue; } if (args[argidx] == "-cell_attr" && argidx+1 < args.size()) { solver.cell_attr.insert(RTLIL::escape_id(args[++argidx])); continue; } if (args[argidx] == "-wire_attr" && argidx+1 < args.size()) { solver.wire_attr.insert(RTLIL::escape_id(args[++argidx])); continue; } if (args[argidx] == "-ignore_parameters") { solver.ignore_parameters = true; continue; } if (args[argidx] == "-ignore_param" && argidx+2 < args.size()) { solver.ignored_parameters.insert(std::pair<RTLIL::IdString, RTLIL::IdString>(RTLIL::escape_id(args[argidx+1]), RTLIL::escape_id(args[argidx+2]))); argidx += 2; continue; } break; } extra_args(args, argidx, design); if (!nodefaultswaps) { solver.addSwappablePorts("$and", "\\A", "\\B"); solver.addSwappablePorts("$or", "\\A", "\\B"); solver.addSwappablePorts("$xor", "\\A", "\\B"); solver.addSwappablePorts("$xnor", "\\A", "\\B"); solver.addSwappablePorts("$eq", "\\A", "\\B"); solver.addSwappablePorts("$ne", "\\A", "\\B"); solver.addSwappablePorts("$eqx", "\\A", "\\B"); solver.addSwappablePorts("$nex", "\\A", "\\B"); solver.addSwappablePorts("$add", "\\A", "\\B"); solver.addSwappablePorts("$mul", "\\A", "\\B"); solver.addSwappablePorts("$logic_and", "\\A", "\\B"); solver.addSwappablePorts("$logic_or", "\\A", "\\B"); solver.addSwappablePorts("$_AND_", "\\A", "\\B"); solver.addSwappablePorts("$_OR_", "\\A", "\\B"); solver.addSwappablePorts("$_XOR_", "\\A", "\\B"); } if (map_filenames.empty() && mine_outfile.empty()) log_cmd_error("Missing option -map <verilog_or_rtlil_file> or -mine <output_rtlil_file>.\n"); RTLIL::Design *map = nullptr; if (!mine_mode) { map = new RTLIL::Design; for (auto &filename : map_filenames) { if (filename.compare(0, 1, "%") == 0) { if (!saved_designs.count(filename.substr(1))) { delete map; log_cmd_error("Can't saved design `%s'.\n", filename.c_str()+1); } for (auto mod : saved_designs.at(filename.substr(1))->modules()) if (!map->has(mod->name)) map->add(mod->clone()); } else { std::ifstream f; rewrite_filename(filename); f.open(filename.c_str()); if (f.fail()) { delete map; log_cmd_error("Can't open map file `%s'.\n", filename.c_str()); } Frontend::frontend_call(map, &f, filename, (filename.size() > 3 && filename.compare(filename.size()-3, std::string::npos, ".il") == 0 ? "rtlil" : "verilog")); f.close(); if (filename.size() <= 3 || filename.compare(filename.size()-3, std::string::npos, ".il") != 0) { Pass::call(map, "proc"); Pass::call(map, "opt_clean"); } } } } std::map<std::string, RTLIL::Module*> needle_map, haystack_map; std::vector<RTLIL::Module*> needle_list; log_header(design, "Creating graphs for SubCircuit library.\n"); if (!mine_mode) for (auto module : map->modules()) { SubCircuit::Graph mod_graph; std::string graph_name = "needle_" + RTLIL::unescape_id(module->name); log("Creating needle graph %s.\n", graph_name.c_str()); if (module2graph(mod_graph, module, constports)) { solver.addGraph(graph_name, mod_graph); needle_map[graph_name] = module; needle_list.push_back(module); } } for (auto module : design->modules()) { SubCircuit::Graph mod_graph; std::string graph_name = "haystack_" + RTLIL::unescape_id(module->name); log("Creating haystack graph %s.\n", graph_name.c_str()); if (module2graph(mod_graph, module, constports, design, mine_mode ? mine_max_fanout : -1, mine_mode ? &mine_split : nullptr)) { solver.addGraph(graph_name, mod_graph); haystack_map[graph_name] = module; } } if (!mine_mode) { std::vector<SubCircuit::Solver::Result> results; log_header(design, "Running solver from SubCircuit library.\n"); std::sort(needle_list.begin(), needle_list.end(), compareSortNeedleList); for (auto needle : needle_list) for (auto &haystack_it : haystack_map) { log("Solving for %s in %s.\n", ("needle_" + RTLIL::unescape_id(needle->name)).c_str(), haystack_it.first.c_str()); solver.solve(results, "needle_" + RTLIL::unescape_id(needle->name), haystack_it.first, false); } log("Found %d matches.\n", GetSize(results)); if (results.size() > 0) { log_header(design, "Substitute SubCircuits with cells.\n"); for (int i = 0; i < int(results.size()); i++) { auto &result = results[i]; log("\nMatch #%d: (%s in %s)\n", i, result.needleGraphId.c_str(), result.haystackGraphId.c_str()); for (const auto &it : result.mappings) { log(" %s -> %s", it.first.c_str(), it.second.haystackNodeId.c_str()); for (const auto & it2 : it.second.portMapping) log(" %s:%s", it2.first.c_str(), it2.second.c_str()); log("\n"); } RTLIL::Cell *new_cell = replace(needle_map.at(result.needleGraphId), haystack_map.at(result.haystackGraphId), result); design->select(haystack_map.at(result.haystackGraphId), new_cell); log(" new cell: %s\n", log_id(new_cell->name)); } } } else { std::vector<SubCircuit::Solver::MineResult> results; log_header(design, "Running miner from SubCircuit library.\n"); solver.mine(results, mine_cells_min, mine_cells_max, mine_min_freq, mine_limit_mod); map = new RTLIL::Design; int needleCounter = 0; for (auto &result: results) { log("\nFrequent SubCircuit with %d nodes and %d matches:\n", int(result.nodes.size()), result.totalMatchesAfterLimits); log(" primary match in %s:", log_id(haystack_map.at(result.graphId)->name)); for (auto &node : result.nodes) log(" %s", RTLIL::unescape_id(node.nodeId).c_str()); log("\n"); for (auto &it : result.matchesPerGraph) log(" matches in %s: %d\n", log_id(haystack_map.at(it.first)->name), it.second); RTLIL::Module *mod = haystack_map.at(result.graphId); std::set<RTLIL::Cell*> cells; std::set<RTLIL::Wire*> wires; SigMap sigmap(mod); for (auto &node : result.nodes) cells.insert((RTLIL::Cell*)node.userData); for (auto cell : cells) for (auto &conn : cell->connections()) { RTLIL::SigSpec sig = sigmap(conn.second); for (auto &chunk : sig.chunks()) if (chunk.wire != nullptr) wires.insert(chunk.wire); } RTLIL::Module *newMod = new RTLIL::Module; newMod->name = stringf("\\needle%05d_%s_%dx", needleCounter++, log_id(haystack_map.at(result.graphId)->name), result.totalMatchesAfterLimits); map->add(newMod); for (auto wire : wires) { RTLIL::Wire *newWire = newMod->addWire(wire->name, wire->width); newWire->port_input = true; newWire->port_output = true; } newMod->fixup_ports(); for (auto cell : cells) { RTLIL::Cell *newCell = newMod->addCell(cell->name, cell->type); newCell->parameters = cell->parameters; for (auto &conn : cell->connections()) { std::vector<SigChunk> chunks = sigmap(conn.second); for (auto &chunk : chunks) if (chunk.wire != nullptr) chunk.wire = newMod->wire(chunk.wire->name); newCell->setPort(conn.first, chunks); } } } std::ofstream f; rewrite_filename(mine_outfile); f.open(mine_outfile.c_str(), std::ofstream::trunc); if (f.fail()) log_error("Can't open output file `%s'.\n", mine_outfile.c_str()); Backend::backend_call(map, &f, mine_outfile, "rtlil"); f.close(); } delete map; log_pop(); } } ExtractPass; PRIVATE_NAMESPACE_END