Cope with width != 1 when re-mapping cells
[yosys.git] / passes / techmap / abc9.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 // [[CITE]] ABC
21 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
22 // http://www.eecs.berkeley.edu/~alanmi/abc/
23
24 // [[CITE]] Berkeley Logic Interchange Format (BLIF)
25 // University of California. Berkeley. July 28, 1992
26 // http://www.ece.cmu.edu/~ee760/760docs/blif.pdf
27
28 // [[CITE]] Kahn's Topological sorting algorithm
29 // Kahn, Arthur B. (1962), "Topological sorting of large networks", Communications of the ACM 5 (11): 558-562, doi:10.1145/368996.369025
30 // http://en.wikipedia.org/wiki/Topological_sorting
31
32 #define ABC_COMMAND_LIB "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
33 #define ABC_COMMAND_CTR "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p"
34 #define ABC_COMMAND_LUT "&st; &fraig; &scorr; &dc2; &retime; &dch -f; &if;"/*" &mfs"*/
35 #define ABC_COMMAND_SOP "strash; ifraig; scorr; dc2; dretime; strash; dch -f; cover {I} {P}"
36 #define ABC_COMMAND_DFL "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
37
38 #define ABC_FAST_COMMAND_LIB "strash; dretime; map {D}"
39 #define ABC_FAST_COMMAND_CTR "strash; dretime; map {D}; buffer; upsize {D}; dnsize {D}; stime -p"
40 #define ABC_FAST_COMMAND_LUT "strash; dretime; if"
41 #define ABC_FAST_COMMAND_SOP "strash; dretime; cover -I {I} -P {P}"
42 #define ABC_FAST_COMMAND_DFL "strash; dretime; map"
43
44 #include "kernel/register.h"
45 #include "kernel/sigtools.h"
46 #include "kernel/celltypes.h"
47 #include "kernel/cost.h"
48 #include "kernel/log.h"
49 #include <stdlib.h>
50 #include <stdio.h>
51 #include <string.h>
52 #include <cerrno>
53 #include <sstream>
54 #include <climits>
55
56 #ifndef _WIN32
57 # include <unistd.h>
58 # include <dirent.h>
59 #endif
60
61 #include "frontends/aiger/aigerparse.h"
62
63 #ifdef YOSYS_LINK_ABC
64 extern "C" int Abc_RealMain(int argc, char *argv[]);
65 #endif
66
67 USING_YOSYS_NAMESPACE
68 PRIVATE_NAMESPACE_BEGIN
69
70 bool map_mux4;
71 bool map_mux8;
72 bool map_mux16;
73
74 bool markgroups;
75 int map_autoidx;
76 SigMap assign_map;
77 RTLIL::Module *module;
78 std::map<RTLIL::SigBit, int> signal_map;
79 std::map<RTLIL::SigBit, RTLIL::State> signal_init;
80 pool<std::string> enabled_gates;
81 bool recover_init;
82
83 bool clk_polarity, en_polarity;
84 RTLIL::SigSpec clk_sig, en_sig;
85 dict<int, std::string> pi_map, po_map;
86
87 std::string remap_name(RTLIL::IdString abc_name)
88 {
89 std::stringstream sstr;
90 sstr << "$abc$" << map_autoidx << "$" << abc_name.substr(1);
91 return sstr.str();
92 }
93
94 std::string add_echos_to_abc_cmd(std::string str)
95 {
96 std::string new_str, token;
97 for (size_t i = 0; i < str.size(); i++) {
98 token += str[i];
99 if (str[i] == ';') {
100 while (i+1 < str.size() && str[i+1] == ' ')
101 i++;
102 new_str += "echo + " + token + " " + token + " ";
103 token.clear();
104 }
105 }
106
107 if (!token.empty()) {
108 if (!new_str.empty())
109 new_str += "echo + " + token + "; ";
110 new_str += token;
111 }
112
113 return new_str;
114 }
115
116 std::string fold_abc_cmd(std::string str)
117 {
118 std::string token, new_str = " ";
119 int char_counter = 10;
120
121 for (size_t i = 0; i <= str.size(); i++) {
122 if (i < str.size())
123 token += str[i];
124 if (i == str.size() || str[i] == ';') {
125 if (char_counter + token.size() > 75)
126 new_str += "\n ", char_counter = 14;
127 new_str += token, char_counter += token.size();
128 token.clear();
129 }
130 }
131
132 return new_str;
133 }
134
135 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
136 {
137 if (show_tempdir)
138 return text;
139
140 while (1) {
141 size_t pos = text.find(tempdir_name);
142 if (pos == std::string::npos)
143 break;
144 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
145 }
146
147 std::string selfdir_name = proc_self_dirname();
148 if (selfdir_name != "/") {
149 while (1) {
150 size_t pos = text.find(selfdir_name);
151 if (pos == std::string::npos)
152 break;
153 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
154 }
155 }
156
157 return text;
158 }
159
160 struct abc_output_filter
161 {
162 bool got_cr;
163 int escape_seq_state;
164 std::string linebuf;
165 std::string tempdir_name;
166 bool show_tempdir;
167
168 abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
169 {
170 got_cr = false;
171 escape_seq_state = 0;
172 }
173
174 void next_char(char ch)
175 {
176 if (escape_seq_state == 0 && ch == '\033') {
177 escape_seq_state = 1;
178 return;
179 }
180 if (escape_seq_state == 1) {
181 escape_seq_state = ch == '[' ? 2 : 0;
182 return;
183 }
184 if (escape_seq_state == 2) {
185 if ((ch < '0' || '9' < ch) && ch != ';')
186 escape_seq_state = 0;
187 return;
188 }
189 escape_seq_state = 0;
190 if (ch == '\r') {
191 got_cr = true;
192 return;
193 }
194 if (ch == '\n') {
195 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
196 got_cr = false, linebuf.clear();
197 return;
198 }
199 if (got_cr)
200 got_cr = false, linebuf.clear();
201 linebuf += ch;
202 }
203
204 void next_line(const std::string &line)
205 {
206 int pi, po;
207 if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
208 log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
209 pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
210 po, po_map.count(po) ? po_map.at(po).c_str() : "???");
211 return;
212 }
213
214 for (char ch : line)
215 next_char(ch);
216 }
217 };
218
219 void abc9_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
220 std::string liberty_file, std::string constr_file, bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str,
221 bool keepff, std::string delay_target, std::string sop_inputs, std::string sop_products, std::string lutin_shared, bool fast_mode,
222 const std::vector<RTLIL::Cell*> &cells, bool show_tempdir, bool sop_mode)
223 {
224 module = current_module;
225 map_autoidx = autoidx++;
226
227 signal_map.clear();
228 pi_map.clear();
229 po_map.clear();
230 recover_init = false;
231
232 if (clk_str != "$")
233 {
234 clk_polarity = true;
235 clk_sig = RTLIL::SigSpec();
236
237 en_polarity = true;
238 en_sig = RTLIL::SigSpec();
239 }
240
241 if (!clk_str.empty() && clk_str != "$")
242 {
243 if (clk_str.find(',') != std::string::npos) {
244 int pos = clk_str.find(',');
245 std::string en_str = clk_str.substr(pos+1);
246 clk_str = clk_str.substr(0, pos);
247 if (en_str[0] == '!') {
248 en_polarity = false;
249 en_str = en_str.substr(1);
250 }
251 if (module->wires_.count(RTLIL::escape_id(en_str)) != 0)
252 en_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(en_str)), 0));
253 }
254 if (clk_str[0] == '!') {
255 clk_polarity = false;
256 clk_str = clk_str.substr(1);
257 }
258 if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
259 clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
260 }
261
262 if (dff_mode && clk_sig.empty())
263 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
264
265 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
266 if (!cleanup)
267 tempdir_name[0] = tempdir_name[4] = '_';
268 tempdir_name = make_temp_dir(tempdir_name);
269 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
270 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
271
272 std::string abc_script = stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
273
274 if (!liberty_file.empty()) {
275 abc_script += stringf("read_lib -w %s; ", liberty_file.c_str());
276 if (!constr_file.empty())
277 abc_script += stringf("read_constr -v %s; ", constr_file.c_str());
278 } else
279 if (!lut_costs.empty())
280 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
281 else
282 abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str());
283
284 if (!script_file.empty()) {
285 if (script_file[0] == '+') {
286 for (size_t i = 1; i < script_file.size(); i++)
287 if (script_file[i] == '\'')
288 abc_script += "'\\''";
289 else if (script_file[i] == ',')
290 abc_script += " ";
291 else
292 abc_script += script_file[i];
293 } else
294 abc_script += stringf("source %s", script_file.c_str());
295 } else if (!lut_costs.empty()) {
296 bool all_luts_cost_same = true;
297 for (int this_cost : lut_costs)
298 if (this_cost != lut_costs.front())
299 all_luts_cost_same = false;
300 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
301 //if (all_luts_cost_same && !fast_mode)
302 // abc_script += "; lutpack {S}";
303 } else if (!liberty_file.empty())
304 abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
305 else if (sop_mode)
306 abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
307 else
308 abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
309
310 if (script_file.empty() && !delay_target.empty())
311 for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
312 abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
313
314 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
315 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
316
317 for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
318 abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3);
319
320 for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
321 abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3);
322
323 for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
324 abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
325
326 abc_script += stringf("; &ps; &write -v %s/output.xaig", tempdir_name.c_str());
327 abc_script = add_echos_to_abc_cmd(abc_script);
328
329 for (size_t i = 0; i+1 < abc_script.size(); i++)
330 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
331 abc_script[i+1] = '\n';
332
333 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
334 fprintf(f, "%s\n", abc_script.c_str());
335 fclose(f);
336
337 if (dff_mode || !clk_str.empty())
338 {
339 if (clk_sig.size() == 0)
340 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
341 else {
342 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
343 if (en_sig.size() != 0)
344 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
345 log("\n");
346 }
347 }
348
349 Pass::call(design, stringf("aigmap; write_xaiger -map %s/input.symbols %s/input.xaig; ", tempdir_name.c_str(), tempdir_name.c_str()));
350
351 log_push();
352
353 //if (count_output > 0)
354 {
355 log_header(design, "Executing ABC.\n");
356
357 std::string buffer = stringf("%s/stdcells.genlib", tempdir_name.c_str());
358 f = fopen(buffer.c_str(), "wt");
359 if (f == NULL)
360 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
361 fprintf(f, "GATE ZERO 1 Y=CONST0;\n");
362 fprintf(f, "GATE ONE 1 Y=CONST1;\n");
363 fprintf(f, "GATE BUF %d Y=A; PIN * NONINV 1 999 1 0 1 0\n", get_cell_cost("$_BUF_"));
364 fprintf(f, "GATE NOT %d Y=!A; PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_NOT_"));
365 if (enabled_gates.empty() || enabled_gates.count("AND"))
366 fprintf(f, "GATE AND %d Y=A*B; PIN * NONINV 1 999 1 0 1 0\n", get_cell_cost("$_AND_"));
367 if (enabled_gates.empty() || enabled_gates.count("NAND"))
368 fprintf(f, "GATE NAND %d Y=!(A*B); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_NAND_"));
369 if (enabled_gates.empty() || enabled_gates.count("OR"))
370 fprintf(f, "GATE OR %d Y=A+B; PIN * NONINV 1 999 1 0 1 0\n", get_cell_cost("$_OR_"));
371 if (enabled_gates.empty() || enabled_gates.count("NOR"))
372 fprintf(f, "GATE NOR %d Y=!(A+B); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_NOR_"));
373 if (enabled_gates.empty() || enabled_gates.count("XOR"))
374 fprintf(f, "GATE XOR %d Y=(A*!B)+(!A*B); PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_XOR_"));
375 if (enabled_gates.empty() || enabled_gates.count("XNOR"))
376 fprintf(f, "GATE XNOR %d Y=(A*B)+(!A*!B); PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_XNOR_"));
377 if (enabled_gates.empty() || enabled_gates.count("ANDNOT"))
378 fprintf(f, "GATE ANDNOT %d Y=A*!B; PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_ANDNOT_"));
379 if (enabled_gates.empty() || enabled_gates.count("ORNOT"))
380 fprintf(f, "GATE ORNOT %d Y=A+!B; PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_ORNOT_"));
381 if (enabled_gates.empty() || enabled_gates.count("AOI3"))
382 fprintf(f, "GATE AOI3 %d Y=!((A*B)+C); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_AOI3_"));
383 if (enabled_gates.empty() || enabled_gates.count("OAI3"))
384 fprintf(f, "GATE OAI3 %d Y=!((A+B)*C); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_OAI3_"));
385 if (enabled_gates.empty() || enabled_gates.count("AOI4"))
386 fprintf(f, "GATE AOI4 %d Y=!((A*B)+(C*D)); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_AOI4_"));
387 if (enabled_gates.empty() || enabled_gates.count("OAI4"))
388 fprintf(f, "GATE OAI4 %d Y=!((A+B)*(C+D)); PIN * INV 1 999 1 0 1 0\n", get_cell_cost("$_OAI4_"));
389 if (enabled_gates.empty() || enabled_gates.count("MUX"))
390 fprintf(f, "GATE MUX %d Y=(A*B)+(S*B)+(!S*A); PIN * UNKNOWN 1 999 1 0 1 0\n", get_cell_cost("$_MUX_"));
391 if (map_mux4)
392 fprintf(f, "GATE MUX4 %d Y=(!S*!T*A)+(S*!T*B)+(!S*T*C)+(S*T*D); PIN * UNKNOWN 1 999 1 0 1 0\n", 2*get_cell_cost("$_MUX_"));
393 if (map_mux8)
394 fprintf(f, "GATE MUX8 %d Y=(!S*!T*!U*A)+(S*!T*!U*B)+(!S*T*!U*C)+(S*T*!U*D)+(!S*!T*U*E)+(S*!T*U*F)+(!S*T*U*G)+(S*T*U*H); PIN * UNKNOWN 1 999 1 0 1 0\n", 4*get_cell_cost("$_MUX_"));
395 if (map_mux16)
396 fprintf(f, "GATE MUX16 %d Y=(!S*!T*!U*!V*A)+(S*!T*!U*!V*B)+(!S*T*!U*!V*C)+(S*T*!U*!V*D)+(!S*!T*U*!V*E)+(S*!T*U*!V*F)+(!S*T*U*!V*G)+(S*T*U*!V*H)+(!S*!T*!U*V*I)+(S*!T*!U*V*J)+(!S*T*!U*V*K)+(S*T*!U*V*L)+(!S*!T*U*V*M)+(S*!T*U*V*N)+(!S*T*U*V*O)+(S*T*U*V*P); PIN * UNKNOWN 1 999 1 0 1 0\n", 8*get_cell_cost("$_MUX_"));
397 fclose(f);
398
399 if (!lut_costs.empty()) {
400 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
401 f = fopen(buffer.c_str(), "wt");
402 if (f == NULL)
403 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
404 for (int i = 0; i < GetSize(lut_costs); i++)
405 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
406 fclose(f);
407 }
408
409 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
410 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
411
412 #ifndef YOSYS_LINK_ABC
413 abc_output_filter filt(tempdir_name, show_tempdir);
414 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
415 #else
416 // These needs to be mutable, supposedly due to getopt
417 char *abc_argv[5];
418 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
419 abc_argv[0] = strdup(exe_file.c_str());
420 abc_argv[1] = strdup("-s");
421 abc_argv[2] = strdup("-f");
422 abc_argv[3] = strdup(tmp_script_name.c_str());
423 abc_argv[4] = 0;
424 int ret = Abc_RealMain(4, abc_argv);
425 free(abc_argv[0]);
426 free(abc_argv[1]);
427 free(abc_argv[2]);
428 free(abc_argv[3]);
429 #endif
430 if (ret != 0)
431 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
432
433 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.xaig");
434 std::ifstream ifs;
435 ifs.open(buffer);
436 if (ifs.fail())
437 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
438
439 bool builtin_lib = liberty_file.empty();
440 RTLIL::Design *mapped_design = new RTLIL::Design;
441 //parse_blif(mapped_design, ifs, builtin_lib ? "\\DFF" : "\\_dff_", false, sop_mode);
442 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.symbols");
443 AigerReader reader(mapped_design, ifs, "\\netlist", "\\clk", buffer, true /* wideports */);
444 reader.parse_xaiger();
445
446 ifs.close();
447
448 log_header(design, "Re-integrating ABC results.\n");
449 RTLIL::Module *mapped_mod = mapped_design->modules_["\\netlist"];
450 if (mapped_mod == NULL)
451 log_error("ABC output file does not contain a module `netlist'.\n");
452 for (auto &it : mapped_mod->wires_) {
453 RTLIL::Wire *w = it.second;
454 RTLIL::Wire *wire = module->addWire(remap_name(w->name), GetSize(w));
455 if (markgroups) wire->attributes["\\abcgroup"] = map_autoidx;
456 design->select(module, wire);
457 }
458
459 std::map<std::string, int> cell_stats;
460 for (auto c : mapped_mod->cells())
461 {
462 if (builtin_lib)
463 {
464 cell_stats[RTLIL::unescape_id(c->type)]++;
465 if (c->type == "\\ZERO" || c->type == "\\ONE") {
466 RTLIL::SigSig conn;
467 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]);
468 conn.second = RTLIL::SigSpec(c->type == "\\ZERO" ? 0 : 1, 1);
469 module->connect(conn);
470 continue;
471 }
472 if (c->type == "\\BUF") {
473 RTLIL::SigSig conn;
474 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]);
475 conn.second = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]);
476 module->connect(conn);
477 continue;
478 }
479 if (c->type == "\\NOT") {
480 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_NOT_");
481 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
482 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
483 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
484 design->select(module, cell);
485 continue;
486 }
487 if (c->type == "\\AND" || c->type == "\\OR" || c->type == "\\XOR" || c->type == "\\NAND" || c->type == "\\NOR" ||
488 c->type == "\\XNOR" || c->type == "\\ANDNOT" || c->type == "\\ORNOT") {
489 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
490 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
491 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
492 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
493 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
494 design->select(module, cell);
495 continue;
496 }
497 if (c->type == "\\MUX") {
498 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX_");
499 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
500 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
501 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
502 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
503 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
504 design->select(module, cell);
505 continue;
506 }
507 if (c->type == "\\MUX4") {
508 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX4_");
509 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
510 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
511 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
512 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
513 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
514 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
515 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
516 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
517 design->select(module, cell);
518 continue;
519 }
520 if (c->type == "\\MUX8") {
521 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX8_");
522 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
523 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
524 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
525 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
526 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
527 cell->setPort("\\E", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\E").as_wire()->name)]));
528 cell->setPort("\\F", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\F").as_wire()->name)]));
529 cell->setPort("\\G", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\G").as_wire()->name)]));
530 cell->setPort("\\H", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\H").as_wire()->name)]));
531 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
532 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
533 cell->setPort("\\U", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\U").as_wire()->name)]));
534 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
535 design->select(module, cell);
536 continue;
537 }
538 if (c->type == "\\MUX16") {
539 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX16_");
540 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
541 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
542 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
543 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
544 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
545 cell->setPort("\\E", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\E").as_wire()->name)]));
546 cell->setPort("\\F", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\F").as_wire()->name)]));
547 cell->setPort("\\G", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\G").as_wire()->name)]));
548 cell->setPort("\\H", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\H").as_wire()->name)]));
549 cell->setPort("\\I", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\I").as_wire()->name)]));
550 cell->setPort("\\J", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\J").as_wire()->name)]));
551 cell->setPort("\\K", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\K").as_wire()->name)]));
552 cell->setPort("\\L", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\L").as_wire()->name)]));
553 cell->setPort("\\M", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\M").as_wire()->name)]));
554 cell->setPort("\\N", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\N").as_wire()->name)]));
555 cell->setPort("\\O", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\O").as_wire()->name)]));
556 cell->setPort("\\P", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\P").as_wire()->name)]));
557 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
558 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
559 cell->setPort("\\U", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\U").as_wire()->name)]));
560 cell->setPort("\\V", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\V").as_wire()->name)]));
561 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
562 design->select(module, cell);
563 continue;
564 }
565 if (c->type == "\\AOI3" || c->type == "\\OAI3") {
566 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
567 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
568 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
569 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
570 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
571 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
572 design->select(module, cell);
573 continue;
574 }
575 if (c->type == "\\AOI4" || c->type == "\\OAI4") {
576 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
577 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
578 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
579 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
580 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
581 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
582 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
583 design->select(module, cell);
584 continue;
585 }
586 if (c->type == "\\DFF") {
587 log_assert(clk_sig.size() == 1);
588 RTLIL::Cell *cell;
589 if (en_sig.size() == 0) {
590 cell = module->addCell(remap_name(c->name), clk_polarity ? "$_DFF_P_" : "$_DFF_N_");
591 } else {
592 log_assert(en_sig.size() == 1);
593 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
594 cell->setPort("\\E", en_sig);
595 }
596 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
597 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
598 cell->setPort("\\Q", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Q").as_wire()->name)]));
599 cell->setPort("\\C", clk_sig);
600 design->select(module, cell);
601 continue;
602 }
603 }
604
605 cell_stats[RTLIL::unescape_id(c->type)]++;
606
607 if (c->type == "\\_const0_" || c->type == "\\_const1_") {
608 RTLIL::SigSig conn;
609 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->connections().begin()->second.as_wire()->name)]);
610 conn.second = RTLIL::SigSpec(c->type == "\\_const0_" ? 0 : 1, 1);
611 module->connect(conn);
612 continue;
613 }
614
615 if (c->type == "\\_dff_") {
616 log_assert(clk_sig.size() == 1);
617 RTLIL::Cell *cell;
618 if (en_sig.size() == 0) {
619 cell = module->addCell(remap_name(c->name), clk_polarity ? "$_DFF_P_" : "$_DFF_N_");
620 } else {
621 log_assert(en_sig.size() == 1);
622 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
623 cell->setPort("\\E", en_sig);
624 }
625 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
626 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
627 cell->setPort("\\Q", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Q").as_wire()->name)]));
628 cell->setPort("\\C", clk_sig);
629 design->select(module, cell);
630 continue;
631 }
632
633 if (c->type == "$lut" && GetSize(c->getPort("\\A")) == 1 && c->getParam("\\LUT").as_int() == 2) {
634 SigSpec my_a = module->wires_[remap_name(c->getPort("\\A").as_wire()->name)];
635 SigSpec my_y = module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)];
636 module->connect(my_y, my_a);
637 continue;
638 }
639
640 RTLIL::Cell *cell = module->addCell(remap_name(c->name), c->type);
641 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
642 cell->parameters = c->parameters;
643 for (auto &conn : c->connections()) {
644 RTLIL::SigSpec newsig;
645 for (auto c : conn.second.chunks()) {
646 if (c.width == 0)
647 continue;
648 //log_assert(c.width == 1);
649 c.wire = module->wires_[remap_name(c.wire->name)];
650 newsig.append(c);
651 }
652 cell->setPort(conn.first, newsig);
653 }
654 design->select(module, cell);
655 }
656
657 // Copy connections (and rename) from mapped_mod to module
658 for (auto conn : mapped_mod->connections()) {
659 if (!conn.first.is_fully_const()) {
660 auto chunks = conn.first.chunks();
661 for (auto &c : chunks)
662 c.wire = module->wires_[remap_name(c.wire->name)];
663 conn.first = std::move(chunks);
664 }
665 if (!conn.second.is_fully_const()) {
666 auto chunks = conn.second.chunks();
667 for (auto &c : chunks)
668 c.wire = module->wires_[remap_name(c.wire->name)];
669 conn.second = std::move(chunks);
670 }
671 module->connect(conn);
672 }
673
674 if (recover_init)
675 for (auto wire : mapped_mod->wires()) {
676 if (wire->attributes.count("\\init")) {
677 Wire *w = module->wires_[remap_name(wire->name)];
678 log_assert(w->attributes.count("\\init") == 0);
679 w->attributes["\\init"] = wire->attributes.at("\\init");
680 }
681 }
682
683 for (auto &it : cell_stats)
684 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
685 int in_wires = 0, out_wires = 0;
686 //for (auto &si : signal_list)
687 // if (si.is_port) {
688 // char buffer[100];
689 // snprintf(buffer, 100, "\\n%d", si.id);
690 // RTLIL::SigSig conn;
691 // if (si.type != G(NONE)) {
692 // conn.first = si.bit;
693 // conn.second = RTLIL::SigSpec(module->wires_[remap_name(buffer)]);
694 // out_wires++;
695 // } else {
696 // conn.first = RTLIL::SigSpec(module->wires_[remap_name(buffer)]);
697 // conn.second = si.bit;
698 // in_wires++;
699 // }
700 // module->connect(conn);
701 // }
702
703 pool<RTLIL::SigBit> output_bits;
704 std::vector<RTLIL::SigSig> connections;
705 // Stitch in mapped_mod's inputs/outputs into module
706 for (auto &it : mapped_mod->wires_) {
707 RTLIL::Wire *w = it.second;
708 if (!w->port_input && !w->port_output)
709 continue;
710 RTLIL::Wire *wire = module->wire(w->name);
711 RTLIL::Wire *remap_wire = module->wire(remap_name(w->name));
712 if (w->port_input) {
713 RTLIL::SigSig conn;
714 log_assert(GetSize(wire) >= GetSize(remap_wire));
715 conn.first = remap_wire;
716 conn.second = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
717 in_wires++;
718 connections.emplace_back(std::move(conn));
719 printf("INPUT: assign %s = %s\n", remap_wire->name.c_str(), wire->name.c_str());
720 }
721 else if (w->port_output) {
722 RTLIL::SigSig conn;
723 log_assert(GetSize(wire) >= GetSize(remap_wire));
724 conn.first = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
725 conn.second = remap_wire;
726 for (int i = 0; i < GetSize(remap_wire); i++)
727 output_bits.insert({wire, i});
728 printf("OUTPUT: assign %s = %s\n", wire->name.c_str(), remap_wire->name.c_str());
729 connections.emplace_back(std::move(conn));
730 }
731 else log_abort();
732 }
733 // Go through all cell output connections,
734 // and for those output ports driving wires
735 // also driven by mapped_mod, disconnect them
736 for (auto cell : module->cells()) {
737 for (auto &it : cell->connections_) {
738 auto port_name = it.first;
739 if (!cell->output(port_name)) continue;
740 auto &signal = it.second;
741 if (!signal.is_bit()) continue;
742 if (output_bits.count(signal.as_bit()))
743 signal = RTLIL::State::Sx;
744 }
745 }
746 // Do the same for module connections
747 for (auto &it : module->connections_) {
748 auto &signal = it.first;
749 if (!signal.is_bit()) continue;
750 if (output_bits.count(signal.as_bit()))
751 signal = RTLIL::State::Sx;
752 }
753 for (const auto &c : connections)
754 module->connect(c);
755
756 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
757 log("ABC RESULTS: input signals: %8d\n", in_wires);
758 log("ABC RESULTS: output signals: %8d\n", out_wires);
759
760 delete mapped_design;
761 }
762 //else
763 //{
764 // log("Don't call ABC as there is nothing to map.\n");
765 //}
766
767 Pass::call(design, "clean");
768
769 if (cleanup)
770 {
771 log("Removing temp directory.\n");
772 remove_directory(tempdir_name);
773 }
774
775 log_pop();
776 }
777
778 struct Abc9Pass : public Pass {
779 Abc9Pass() : Pass("abc9", "use ABC for technology mapping") { }
780 void help() YS_OVERRIDE
781 {
782 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
783 log("\n");
784 log(" abc9 [options] [selection]\n");
785 log("\n");
786 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
787 log("library to a target architecture.\n");
788 log("\n");
789 log(" -exe <command>\n");
790 #ifdef ABCEXTERNAL
791 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
792 #else
793 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
794 #endif
795 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
796 log("\n");
797 log(" -script <file>\n");
798 log(" use the specified ABC script file instead of the default script.\n");
799 log("\n");
800 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
801 log(" string is interpreted as the command string to be passed to ABC. The\n");
802 log(" leading plus sign is removed and all commas (,) in the string are\n");
803 log(" replaced with blanks before the string is passed to ABC.\n");
804 log("\n");
805 log(" if no -script parameter is given, the following scripts are used:\n");
806 log("\n");
807 log(" for -liberty without -constr:\n");
808 log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str());
809 log("\n");
810 log(" for -liberty with -constr:\n");
811 log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str());
812 log("\n");
813 log(" for -lut/-luts (only one LUT size):\n");
814 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str());
815 log("\n");
816 log(" for -lut/-luts (different LUT sizes):\n");
817 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
818 log("\n");
819 log(" for -sop:\n");
820 log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str());
821 log("\n");
822 log(" otherwise:\n");
823 log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str());
824 log("\n");
825 log(" -fast\n");
826 log(" use different default scripts that are slightly faster (at the cost\n");
827 log(" of output quality):\n");
828 log("\n");
829 log(" for -liberty without -constr:\n");
830 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str());
831 log("\n");
832 log(" for -liberty with -constr:\n");
833 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str());
834 log("\n");
835 log(" for -lut/-luts:\n");
836 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
837 log("\n");
838 log(" for -sop:\n");
839 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str());
840 log("\n");
841 log(" otherwise:\n");
842 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str());
843 log("\n");
844 log(" -liberty <file>\n");
845 log(" generate netlists for the specified cell library (using the liberty\n");
846 log(" file format).\n");
847 log("\n");
848 log(" -constr <file>\n");
849 log(" pass this file with timing constraints to ABC. use with -liberty.\n");
850 log("\n");
851 log(" a constr file contains two lines:\n");
852 log(" set_driving_cell <cell_name>\n");
853 log(" set_load <floating_point_number>\n");
854 log("\n");
855 log(" the set_driving_cell statement defines which cell type is assumed to\n");
856 log(" drive the primary inputs and the set_load statement sets the load in\n");
857 log(" femtofarads for each primary output.\n");
858 log("\n");
859 log(" -D <picoseconds>\n");
860 log(" set delay target. the string {D} in the default scripts above is\n");
861 log(" replaced by this option when used, and an empty string otherwise.\n");
862 log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
863 log(" default scripts above.\n");
864 log("\n");
865 log(" -I <num>\n");
866 log(" maximum number of SOP inputs.\n");
867 log(" (replaces {I} in the default scripts above)\n");
868 log("\n");
869 log(" -P <num>\n");
870 log(" maximum number of SOP products.\n");
871 log(" (replaces {P} in the default scripts above)\n");
872 log("\n");
873 log(" -S <num>\n");
874 log(" maximum number of LUT inputs shared.\n");
875 log(" (replaces {S} in the default scripts above, default: -S 1)\n");
876 log("\n");
877 log(" -lut <width>\n");
878 log(" generate netlist using luts of (max) the specified width.\n");
879 log("\n");
880 log(" -lut <w1>:<w2>\n");
881 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
882 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
883 log(" the area cost doubles with each additional input bit. the delay cost\n");
884 log(" is still constant for all lut widths.\n");
885 log("\n");
886 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
887 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
888 log(" 2, 3, .. inputs.\n");
889 log("\n");
890 log(" -sop\n");
891 log(" map to sum-of-product cells and inverters\n");
892 log("\n");
893 // log(" -mux4, -mux8, -mux16\n");
894 // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n");
895 // log(" (ignored when used with -liberty or -lut)\n");
896 // log("\n");
897 log(" -g type1,type2,...\n");
898 log(" Map to the specified list of gate types. Supported gates types are:\n");
899 log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX, AOI3, OAI3, AOI4, OAI4.\n");
900 log(" (The NOT gate is always added to this list automatically.)\n");
901 log("\n");
902 log(" The following aliases can be used to reference common sets of gate types:\n");
903 log(" simple: AND OR XOR MUX\n");
904 log(" cmos2: NAND NOR\n");
905 log(" cmos3: NAND NOR AOI3 OAI3\n");
906 log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n");
907 log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n");
908 log(" aig: AND NAND OR NOR ANDNOT ORNOT\n");
909 log("\n");
910 log(" Prefix a gate type with a '-' to remove it from the list. For example\n");
911 log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n");
912 log("\n");
913 log(" -dff\n");
914 log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
915 log(" clock domains are automatically partitioned in clock domains and each\n");
916 log(" domain is passed through ABC independently.\n");
917 log("\n");
918 log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
919 log(" use only the specified clock domain. this is like -dff, but only FF\n");
920 log(" cells that belong to the specified clock domain are used.\n");
921 log("\n");
922 log(" -keepff\n");
923 log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
924 log(" them, for example for equivalence checking.)\n");
925 log("\n");
926 log(" -nocleanup\n");
927 log(" when this option is used, the temporary files created by this pass\n");
928 log(" are not removed. this is useful for debugging.\n");
929 log("\n");
930 log(" -showtmp\n");
931 log(" print the temp dir name in log. usually this is suppressed so that the\n");
932 log(" command output is identical across runs.\n");
933 log("\n");
934 log(" -markgroups\n");
935 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
936 log(" this attribute is a unique integer for each ABC process started. This\n");
937 log(" is useful for debugging the partitioning of clock domains.\n");
938 log("\n");
939 log("When neither -liberty nor -lut is used, the Yosys standard cell library is\n");
940 log("loaded into ABC before the ABC script is executed.\n");
941 log("\n");
942 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
943 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
944 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
945 log("output when passing an ABC script that writes a file. Instead write your full\n");
946 log("design as BLIF file with write_blif and the load that into ABC externally if\n");
947 log("you want to use ABC to convert your design into another format.\n");
948 log("\n");
949 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
950 log("\n");
951 }
952 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
953 {
954 log_header(design, "Executing ABC9 pass (technology mapping using ABC).\n");
955 log_push();
956
957 assign_map.clear();
958 signal_map.clear();
959 signal_init.clear();
960 pi_map.clear();
961 po_map.clear();
962
963 #ifdef ABCEXTERNAL
964 std::string exe_file = ABCEXTERNAL;
965 #else
966 std::string exe_file = proc_self_dirname() + "yosys-abc";
967 #endif
968 std::string script_file, liberty_file, constr_file, clk_str;
969 std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1";
970 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
971 bool show_tempdir = false, sop_mode = false;
972 show_tempdir = true; cleanup = false;
973 vector<int> lut_costs;
974 markgroups = false;
975
976 map_mux4 = false;
977 map_mux8 = false;
978 map_mux16 = false;
979 enabled_gates.clear();
980
981 #ifdef _WIN32
982 #ifndef ABCEXTERNAL
983 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
984 exe_file = proc_self_dirname() + "..\\yosys-abc";
985 #endif
986 #endif
987
988 size_t argidx;
989 char pwd [PATH_MAX];
990 if (!getcwd(pwd, sizeof(pwd))) {
991 log_cmd_error("getcwd failed: %s\n", strerror(errno));
992 log_abort();
993 }
994 for (argidx = 1; argidx < args.size(); argidx++) {
995 std::string arg = args[argidx];
996 if (arg == "-exe" && argidx+1 < args.size()) {
997 exe_file = args[++argidx];
998 continue;
999 }
1000 if (arg == "-script" && argidx+1 < args.size()) {
1001 script_file = args[++argidx];
1002 rewrite_filename(script_file);
1003 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
1004 script_file = std::string(pwd) + "/" + script_file;
1005 continue;
1006 }
1007 if (arg == "-liberty" && argidx+1 < args.size()) {
1008 liberty_file = args[++argidx];
1009 rewrite_filename(liberty_file);
1010 if (!liberty_file.empty() && !is_absolute_path(liberty_file))
1011 liberty_file = std::string(pwd) + "/" + liberty_file;
1012 continue;
1013 }
1014 if (arg == "-constr" && argidx+1 < args.size()) {
1015 rewrite_filename(constr_file);
1016 constr_file = args[++argidx];
1017 if (!constr_file.empty() && !is_absolute_path(constr_file))
1018 constr_file = std::string(pwd) + "/" + constr_file;
1019 continue;
1020 }
1021 if (arg == "-D" && argidx+1 < args.size()) {
1022 delay_target = "-D " + args[++argidx];
1023 continue;
1024 }
1025 if (arg == "-I" && argidx+1 < args.size()) {
1026 sop_inputs = "-I " + args[++argidx];
1027 continue;
1028 }
1029 if (arg == "-P" && argidx+1 < args.size()) {
1030 sop_products = "-P " + args[++argidx];
1031 continue;
1032 }
1033 if (arg == "-S" && argidx+1 < args.size()) {
1034 lutin_shared = "-S " + args[++argidx];
1035 continue;
1036 }
1037 if (arg == "-lut" && argidx+1 < args.size()) {
1038 string arg = args[++argidx];
1039 size_t pos = arg.find_first_of(':');
1040 int lut_mode = 0, lut_mode2 = 0;
1041 if (pos != string::npos) {
1042 lut_mode = atoi(arg.substr(0, pos).c_str());
1043 lut_mode2 = atoi(arg.substr(pos+1).c_str());
1044 } else {
1045 lut_mode = atoi(arg.c_str());
1046 lut_mode2 = lut_mode;
1047 }
1048 lut_costs.clear();
1049 for (int i = 0; i < lut_mode; i++)
1050 lut_costs.push_back(1);
1051 for (int i = lut_mode; i < lut_mode2; i++)
1052 lut_costs.push_back(2 << (i - lut_mode));
1053 continue;
1054 }
1055 if (arg == "-luts" && argidx+1 < args.size()) {
1056 lut_costs.clear();
1057 for (auto &tok : split_tokens(args[++argidx], ",")) {
1058 auto parts = split_tokens(tok, ":");
1059 if (GetSize(parts) == 0 && !lut_costs.empty())
1060 lut_costs.push_back(lut_costs.back());
1061 else if (GetSize(parts) == 1)
1062 lut_costs.push_back(atoi(parts.at(0).c_str()));
1063 else if (GetSize(parts) == 2)
1064 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
1065 lut_costs.push_back(atoi(parts.at(1).c_str()));
1066 else
1067 log_cmd_error("Invalid -luts syntax.\n");
1068 }
1069 continue;
1070 }
1071 if (arg == "-sop") {
1072 sop_mode = true;
1073 continue;
1074 }
1075 if (arg == "-mux4") {
1076 map_mux4 = true;
1077 continue;
1078 }
1079 if (arg == "-mux8") {
1080 map_mux8 = true;
1081 continue;
1082 }
1083 if (arg == "-mux16") {
1084 map_mux16 = true;
1085 continue;
1086 }
1087 if (arg == "-g" && argidx+1 < args.size()) {
1088 for (auto g : split_tokens(args[++argidx], ",")) {
1089 vector<string> gate_list;
1090 bool remove_gates = false;
1091 if (GetSize(g) > 0 && g[0] == '-') {
1092 remove_gates = true;
1093 g = g.substr(1);
1094 }
1095 if (g == "AND") goto ok_gate;
1096 if (g == "NAND") goto ok_gate;
1097 if (g == "OR") goto ok_gate;
1098 if (g == "NOR") goto ok_gate;
1099 if (g == "XOR") goto ok_gate;
1100 if (g == "XNOR") goto ok_gate;
1101 if (g == "ANDNOT") goto ok_gate;
1102 if (g == "ORNOT") goto ok_gate;
1103 if (g == "MUX") goto ok_gate;
1104 if (g == "AOI3") goto ok_gate;
1105 if (g == "OAI3") goto ok_gate;
1106 if (g == "AOI4") goto ok_gate;
1107 if (g == "OAI4") goto ok_gate;
1108 if (g == "simple") {
1109 gate_list.push_back("AND");
1110 gate_list.push_back("OR");
1111 gate_list.push_back("XOR");
1112 gate_list.push_back("MUX");
1113 goto ok_alias;
1114 }
1115 if (g == "cmos2") {
1116 gate_list.push_back("NAND");
1117 gate_list.push_back("NOR");
1118 goto ok_alias;
1119 }
1120 if (g == "cmos3") {
1121 gate_list.push_back("NAND");
1122 gate_list.push_back("NOR");
1123 gate_list.push_back("AOI3");
1124 gate_list.push_back("OAI3");
1125 goto ok_alias;
1126 }
1127 if (g == "cmos4") {
1128 gate_list.push_back("NAND");
1129 gate_list.push_back("NOR");
1130 gate_list.push_back("AOI3");
1131 gate_list.push_back("OAI3");
1132 gate_list.push_back("AOI4");
1133 gate_list.push_back("OAI4");
1134 goto ok_alias;
1135 }
1136 if (g == "gates") {
1137 gate_list.push_back("AND");
1138 gate_list.push_back("NAND");
1139 gate_list.push_back("OR");
1140 gate_list.push_back("NOR");
1141 gate_list.push_back("XOR");
1142 gate_list.push_back("XNOR");
1143 gate_list.push_back("ANDNOT");
1144 gate_list.push_back("ORNOT");
1145 goto ok_alias;
1146 }
1147 if (g == "aig") {
1148 gate_list.push_back("AND");
1149 gate_list.push_back("NAND");
1150 gate_list.push_back("OR");
1151 gate_list.push_back("NOR");
1152 gate_list.push_back("ANDNOT");
1153 gate_list.push_back("ORNOT");
1154 goto ok_alias;
1155 }
1156 cmd_error(args, argidx, stringf("Unsupported gate type: %s", g.c_str()));
1157 ok_gate:
1158 gate_list.push_back(g);
1159 ok_alias:
1160 for (auto gate : gate_list) {
1161 if (remove_gates)
1162 enabled_gates.erase(gate);
1163 else
1164 enabled_gates.insert(gate);
1165 }
1166 }
1167 continue;
1168 }
1169 if (arg == "-fast") {
1170 fast_mode = true;
1171 continue;
1172 }
1173 if (arg == "-dff") {
1174 dff_mode = true;
1175 continue;
1176 }
1177 if (arg == "-clk" && argidx+1 < args.size()) {
1178 clk_str = args[++argidx];
1179 dff_mode = true;
1180 continue;
1181 }
1182 if (arg == "-keepff") {
1183 keepff = true;
1184 continue;
1185 }
1186 if (arg == "-nocleanup") {
1187 cleanup = false;
1188 continue;
1189 }
1190 if (arg == "-showtmp") {
1191 show_tempdir = true;
1192 continue;
1193 }
1194 if (arg == "-markgroups") {
1195 markgroups = true;
1196 continue;
1197 }
1198 break;
1199 }
1200 extra_args(args, argidx, design);
1201
1202 if (!lut_costs.empty() && !liberty_file.empty())
1203 log_cmd_error("Got -lut and -liberty! This two options are exclusive.\n");
1204 if (!constr_file.empty() && liberty_file.empty())
1205 log_cmd_error("Got -constr but no -liberty!\n");
1206
1207 for (auto mod : design->selected_modules())
1208 {
1209 if (mod->processes.size() > 0) {
1210 log("Skipping module %s as it contains processes.\n", log_id(mod));
1211 continue;
1212 }
1213
1214 assign_map.set(mod);
1215 signal_init.clear();
1216
1217 for (Wire *wire : mod->wires())
1218 if (wire->attributes.count("\\init")) {
1219 SigSpec initsig = assign_map(wire);
1220 Const initval = wire->attributes.at("\\init");
1221 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
1222 switch (initval[i]) {
1223 case State::S0:
1224 signal_init[initsig[i]] = State::S0;
1225 break;
1226 case State::S1:
1227 signal_init[initsig[i]] = State::S0;
1228 break;
1229 default:
1230 break;
1231 }
1232 }
1233
1234 if (!dff_mode || !clk_str.empty()) {
1235 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1236 delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode);
1237 continue;
1238 }
1239
1240 CellTypes ct(design);
1241
1242 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1243 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1244
1245 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1246 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1247 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1248
1249 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1250 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1251 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1252
1253 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1254 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1255
1256 for (auto cell : all_cells)
1257 {
1258 clkdomain_t key;
1259
1260 for (auto &conn : cell->connections())
1261 for (auto bit : conn.second) {
1262 bit = assign_map(bit);
1263 if (bit.wire != nullptr) {
1264 cell_to_bit[cell].insert(bit);
1265 bit_to_cell[bit].insert(cell);
1266 if (ct.cell_input(cell->type, conn.first)) {
1267 cell_to_bit_up[cell].insert(bit);
1268 bit_to_cell_down[bit].insert(cell);
1269 }
1270 if (ct.cell_output(cell->type, conn.first)) {
1271 cell_to_bit_down[cell].insert(bit);
1272 bit_to_cell_up[bit].insert(cell);
1273 }
1274 }
1275 }
1276
1277 if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
1278 {
1279 key = clkdomain_t(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")), true, RTLIL::SigSpec());
1280 }
1281 else
1282 if (cell->type == "$_DFFE_NN_" || cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_")
1283 {
1284 bool this_clk_pol = cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_";
1285 bool this_en_pol = cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PP_";
1286 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort("\\C")), this_en_pol, assign_map(cell->getPort("\\E")));
1287 }
1288 else
1289 continue;
1290
1291 unassigned_cells.erase(cell);
1292 expand_queue.insert(cell);
1293 expand_queue_up.insert(cell);
1294 expand_queue_down.insert(cell);
1295
1296 assigned_cells[key].push_back(cell);
1297 assigned_cells_reverse[cell] = key;
1298 }
1299
1300 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1301 {
1302 if (!expand_queue_up.empty())
1303 {
1304 RTLIL::Cell *cell = *expand_queue_up.begin();
1305 clkdomain_t key = assigned_cells_reverse.at(cell);
1306 expand_queue_up.erase(cell);
1307
1308 for (auto bit : cell_to_bit_up[cell])
1309 for (auto c : bit_to_cell_up[bit])
1310 if (unassigned_cells.count(c)) {
1311 unassigned_cells.erase(c);
1312 next_expand_queue_up.insert(c);
1313 assigned_cells[key].push_back(c);
1314 assigned_cells_reverse[c] = key;
1315 expand_queue.insert(c);
1316 }
1317 }
1318
1319 if (!expand_queue_down.empty())
1320 {
1321 RTLIL::Cell *cell = *expand_queue_down.begin();
1322 clkdomain_t key = assigned_cells_reverse.at(cell);
1323 expand_queue_down.erase(cell);
1324
1325 for (auto bit : cell_to_bit_down[cell])
1326 for (auto c : bit_to_cell_down[bit])
1327 if (unassigned_cells.count(c)) {
1328 unassigned_cells.erase(c);
1329 next_expand_queue_up.insert(c);
1330 assigned_cells[key].push_back(c);
1331 assigned_cells_reverse[c] = key;
1332 expand_queue.insert(c);
1333 }
1334 }
1335
1336 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1337 expand_queue_up.swap(next_expand_queue_up);
1338 expand_queue_down.swap(next_expand_queue_down);
1339 }
1340 }
1341
1342 while (!expand_queue.empty())
1343 {
1344 RTLIL::Cell *cell = *expand_queue.begin();
1345 clkdomain_t key = assigned_cells_reverse.at(cell);
1346 expand_queue.erase(cell);
1347
1348 for (auto bit : cell_to_bit.at(cell)) {
1349 for (auto c : bit_to_cell[bit])
1350 if (unassigned_cells.count(c)) {
1351 unassigned_cells.erase(c);
1352 next_expand_queue.insert(c);
1353 assigned_cells[key].push_back(c);
1354 assigned_cells_reverse[c] = key;
1355 }
1356 bit_to_cell[bit].clear();
1357 }
1358
1359 if (expand_queue.empty())
1360 expand_queue.swap(next_expand_queue);
1361 }
1362
1363 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1364 for (auto cell : unassigned_cells) {
1365 assigned_cells[key].push_back(cell);
1366 assigned_cells_reverse[cell] = key;
1367 }
1368
1369 log_header(design, "Summary of detected clock domains:\n");
1370 for (auto &it : assigned_cells)
1371 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1372 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1373 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1374
1375 for (auto &it : assigned_cells) {
1376 clk_polarity = std::get<0>(it.first);
1377 clk_sig = assign_map(std::get<1>(it.first));
1378 en_polarity = std::get<2>(it.first);
1379 en_sig = assign_map(std::get<3>(it.first));
1380 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1381 keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode);
1382 assign_map.set(mod);
1383 }
1384 }
1385
1386 assign_map.clear();
1387 signal_map.clear();
1388 signal_init.clear();
1389 pi_map.clear();
1390 po_map.clear();
1391
1392 log_pop();
1393 }
1394 } Abc9Pass;
1395
1396 PRIVATE_NAMESPACE_END