Move lookup inside if
[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 pool<RTLIL::SigBit> output_bits;
453 for (auto &it : mapped_mod->wires_) {
454 RTLIL::Wire *w = it.second;
455 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
456 if (markgroups) remap_wire->attributes["\\abcgroup"] = map_autoidx;
457 design->select(module, remap_wire);
458 if (w->port_output) {
459 RTLIL::Wire *wire = module->wire(w->name);
460 for (int i = 0; i < GetSize(wire); i++)
461 output_bits.insert({wire, i});
462 }
463 }
464
465 std::map<std::string, int> cell_stats;
466 for (auto c : mapped_mod->cells())
467 {
468 if (builtin_lib)
469 {
470 cell_stats[RTLIL::unescape_id(c->type)]++;
471 if (c->type == "\\ZERO" || c->type == "\\ONE") {
472 RTLIL::SigSig conn;
473 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]);
474 conn.second = RTLIL::SigSpec(c->type == "\\ZERO" ? 0 : 1, 1);
475 module->connect(conn);
476 continue;
477 }
478 if (c->type == "\\BUF") {
479 RTLIL::SigSig conn;
480 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]);
481 conn.second = RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]);
482 module->connect(conn);
483 continue;
484 }
485 if (c->type == "\\NOT") {
486 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_NOT_");
487 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
488 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
489 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
490 design->select(module, cell);
491 continue;
492 }
493 if (c->type == "\\AND" || c->type == "\\OR" || c->type == "\\XOR" || c->type == "\\NAND" || c->type == "\\NOR" ||
494 c->type == "\\XNOR" || c->type == "\\ANDNOT" || c->type == "\\ORNOT") {
495 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
496 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
497 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
498 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
499 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
500 design->select(module, cell);
501 continue;
502 }
503 if (c->type == "\\MUX") {
504 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX_");
505 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
506 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
507 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
508 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
509 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
510 design->select(module, cell);
511 continue;
512 }
513 if (c->type == "\\MUX4") {
514 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX4_");
515 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
516 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
517 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
518 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
519 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
520 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
521 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
522 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
523 design->select(module, cell);
524 continue;
525 }
526 if (c->type == "\\MUX8") {
527 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX8_");
528 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
529 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
530 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
531 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
532 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
533 cell->setPort("\\E", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\E").as_wire()->name)]));
534 cell->setPort("\\F", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\F").as_wire()->name)]));
535 cell->setPort("\\G", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\G").as_wire()->name)]));
536 cell->setPort("\\H", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\H").as_wire()->name)]));
537 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
538 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
539 cell->setPort("\\U", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\U").as_wire()->name)]));
540 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
541 design->select(module, cell);
542 continue;
543 }
544 if (c->type == "\\MUX16") {
545 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_MUX16_");
546 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
547 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
548 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
549 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
550 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
551 cell->setPort("\\E", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\E").as_wire()->name)]));
552 cell->setPort("\\F", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\F").as_wire()->name)]));
553 cell->setPort("\\G", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\G").as_wire()->name)]));
554 cell->setPort("\\H", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\H").as_wire()->name)]));
555 cell->setPort("\\I", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\I").as_wire()->name)]));
556 cell->setPort("\\J", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\J").as_wire()->name)]));
557 cell->setPort("\\K", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\K").as_wire()->name)]));
558 cell->setPort("\\L", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\L").as_wire()->name)]));
559 cell->setPort("\\M", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\M").as_wire()->name)]));
560 cell->setPort("\\N", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\N").as_wire()->name)]));
561 cell->setPort("\\O", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\O").as_wire()->name)]));
562 cell->setPort("\\P", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\P").as_wire()->name)]));
563 cell->setPort("\\S", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\S").as_wire()->name)]));
564 cell->setPort("\\T", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\T").as_wire()->name)]));
565 cell->setPort("\\U", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\U").as_wire()->name)]));
566 cell->setPort("\\V", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\V").as_wire()->name)]));
567 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
568 design->select(module, cell);
569 continue;
570 }
571 if (c->type == "\\AOI3" || c->type == "\\OAI3") {
572 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
573 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
574 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
575 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
576 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
577 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
578 design->select(module, cell);
579 continue;
580 }
581 if (c->type == "\\AOI4" || c->type == "\\OAI4") {
582 RTLIL::Cell *cell = module->addCell(remap_name(c->name), "$_" + c->type.substr(1) + "_");
583 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
584 cell->setPort("\\A", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\A").as_wire()->name)]));
585 cell->setPort("\\B", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\B").as_wire()->name)]));
586 cell->setPort("\\C", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\C").as_wire()->name)]));
587 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
588 cell->setPort("\\Y", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)]));
589 design->select(module, cell);
590 continue;
591 }
592 if (c->type == "\\DFF") {
593 log_assert(clk_sig.size() == 1);
594 RTLIL::Cell *cell;
595 if (en_sig.size() == 0) {
596 cell = module->addCell(remap_name(c->name), clk_polarity ? "$_DFF_P_" : "$_DFF_N_");
597 } else {
598 log_assert(en_sig.size() == 1);
599 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
600 cell->setPort("\\E", en_sig);
601 }
602 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
603 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
604 cell->setPort("\\Q", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Q").as_wire()->name)]));
605 cell->setPort("\\C", clk_sig);
606 design->select(module, cell);
607 continue;
608 }
609 }
610
611 cell_stats[RTLIL::unescape_id(c->type)]++;
612
613 if (c->type == "\\_const0_" || c->type == "\\_const1_") {
614 RTLIL::SigSig conn;
615 conn.first = RTLIL::SigSpec(module->wires_[remap_name(c->connections().begin()->second.as_wire()->name)]);
616 conn.second = RTLIL::SigSpec(c->type == "\\_const0_" ? 0 : 1, 1);
617 module->connect(conn);
618 continue;
619 }
620
621 if (c->type == "\\_dff_") {
622 log_assert(clk_sig.size() == 1);
623 RTLIL::Cell *cell;
624 if (en_sig.size() == 0) {
625 cell = module->addCell(remap_name(c->name), clk_polarity ? "$_DFF_P_" : "$_DFF_N_");
626 } else {
627 log_assert(en_sig.size() == 1);
628 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
629 cell->setPort("\\E", en_sig);
630 }
631 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
632 cell->setPort("\\D", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\D").as_wire()->name)]));
633 cell->setPort("\\Q", RTLIL::SigSpec(module->wires_[remap_name(c->getPort("\\Q").as_wire()->name)]));
634 cell->setPort("\\C", clk_sig);
635 design->select(module, cell);
636 continue;
637 }
638
639 if (c->type == "$lut" && GetSize(c->getPort("\\A")) == 1 && c->getParam("\\LUT").as_int() == 2) {
640 SigSpec my_a = module->wires_[remap_name(c->getPort("\\A").as_wire()->name)];
641 SigSpec my_y = module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)];
642 module->connect(my_y, my_a);
643 continue;
644 }
645
646 RTLIL::Cell *cell = module->addCell(remap_name(c->name), c->type);
647 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
648 cell->parameters = c->parameters;
649 for (auto &conn : c->connections()) {
650 RTLIL::SigSpec newsig;
651 for (auto c : conn.second.chunks()) {
652 if (c.width == 0)
653 continue;
654 //log_assert(c.width == 1);
655 c.wire = module->wires_[remap_name(c.wire->name)];
656 newsig.append(c);
657 }
658 cell->setPort(conn.first, newsig);
659 }
660 design->select(module, cell);
661 }
662
663 // Copy connections (and rename) from mapped_mod to module
664 for (auto conn : mapped_mod->connections()) {
665 if (!conn.first.is_fully_const()) {
666 auto chunks = conn.first.chunks();
667 for (auto &c : chunks)
668 c.wire = module->wires_[remap_name(c.wire->name)];
669 conn.first = std::move(chunks);
670 }
671 if (!conn.second.is_fully_const()) {
672 auto chunks = conn.second.chunks();
673 for (auto &c : chunks)
674 c.wire = module->wires_[remap_name(c.wire->name)];
675 conn.second = std::move(chunks);
676 }
677 module->connect(conn);
678 }
679
680 if (recover_init)
681 for (auto wire : mapped_mod->wires()) {
682 if (wire->attributes.count("\\init")) {
683 Wire *w = module->wires_[remap_name(wire->name)];
684 log_assert(w->attributes.count("\\init") == 0);
685 w->attributes["\\init"] = wire->attributes.at("\\init");
686 }
687 }
688
689 for (auto &it : cell_stats)
690 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
691 int in_wires = 0, out_wires = 0;
692 //for (auto &si : signal_list)
693 // if (si.is_port) {
694 // char buffer[100];
695 // snprintf(buffer, 100, "\\n%d", si.id);
696 // RTLIL::SigSig conn;
697 // if (si.type != G(NONE)) {
698 // conn.first = si.bit;
699 // conn.second = RTLIL::SigSpec(module->wires_[remap_name(buffer)]);
700 // out_wires++;
701 // } else {
702 // conn.first = RTLIL::SigSpec(module->wires_[remap_name(buffer)]);
703 // conn.second = si.bit;
704 // in_wires++;
705 // }
706 // module->connect(conn);
707 // }
708
709 // Go through all cell output connections,
710 // and for those output ports driving wires
711 // also driven by mapped_mod, disconnect them
712 for (auto cell : module->cells()) {
713 for (auto &it : cell->connections_) {
714 auto port_name = it.first;
715 if (!cell->output(port_name)) continue;
716 auto &signal = it.second;
717 if (!signal.is_bit()) continue;
718 if (output_bits.count(signal.as_bit()))
719 signal = RTLIL::State::Sx;
720 }
721 }
722 // Do the same for module connections
723 for (auto &it : module->connections_) {
724 auto &signal = it.first;
725 if (!signal.is_bit()) continue;
726 if (output_bits.count(signal.as_bit()))
727 signal = RTLIL::State::Sx;
728 }
729
730 // Stitch in mapped_mod's inputs/outputs into module
731 for (auto &it : mapped_mod->wires_) {
732 RTLIL::Wire *w = it.second;
733 if (!w->port_input && !w->port_output)
734 continue;
735 RTLIL::Wire *wire = module->wire(w->name);
736 RTLIL::Wire *remap_wire = module->wire(remap_name(w->name));
737 if (w->port_input) {
738 RTLIL::SigSig conn;
739 log_assert(GetSize(wire) >= GetSize(remap_wire));
740 conn.first = remap_wire;
741 conn.second = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
742 in_wires++;
743 module->connect(conn);
744 printf("INPUT: assign %s = %s\n", remap_wire->name.c_str(), wire->name.c_str());
745 }
746 else if (w->port_output) {
747 RTLIL::SigSig conn;
748 log_assert(GetSize(wire) >= GetSize(remap_wire));
749 conn.first = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
750 conn.second = remap_wire;
751 for (int i = 0; i < GetSize(remap_wire); i++)
752 output_bits.insert({wire, i});
753 printf("OUTPUT: assign %s = %s\n", wire->name.c_str(), remap_wire->name.c_str());
754 module->connect(conn);
755 }
756 else log_abort();
757 }
758
759 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
760 log("ABC RESULTS: input signals: %8d\n", in_wires);
761 log("ABC RESULTS: output signals: %8d\n", out_wires);
762
763 delete mapped_design;
764 }
765 //else
766 //{
767 // log("Don't call ABC as there is nothing to map.\n");
768 //}
769
770 Pass::call(design, "clean");
771
772 if (cleanup)
773 {
774 log("Removing temp directory.\n");
775 remove_directory(tempdir_name);
776 }
777
778 log_pop();
779 }
780
781 struct Abc9Pass : public Pass {
782 Abc9Pass() : Pass("abc9", "use ABC for technology mapping") { }
783 void help() YS_OVERRIDE
784 {
785 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
786 log("\n");
787 log(" abc9 [options] [selection]\n");
788 log("\n");
789 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
790 log("library to a target architecture.\n");
791 log("\n");
792 log(" -exe <command>\n");
793 #ifdef ABCEXTERNAL
794 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
795 #else
796 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
797 #endif
798 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
799 log("\n");
800 log(" -script <file>\n");
801 log(" use the specified ABC script file instead of the default script.\n");
802 log("\n");
803 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
804 log(" string is interpreted as the command string to be passed to ABC. The\n");
805 log(" leading plus sign is removed and all commas (,) in the string are\n");
806 log(" replaced with blanks before the string is passed to ABC.\n");
807 log("\n");
808 log(" if no -script parameter is given, the following scripts are used:\n");
809 log("\n");
810 log(" for -liberty without -constr:\n");
811 log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str());
812 log("\n");
813 log(" for -liberty with -constr:\n");
814 log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str());
815 log("\n");
816 log(" for -lut/-luts (only one LUT size):\n");
817 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str());
818 log("\n");
819 log(" for -lut/-luts (different LUT sizes):\n");
820 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
821 log("\n");
822 log(" for -sop:\n");
823 log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str());
824 log("\n");
825 log(" otherwise:\n");
826 log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str());
827 log("\n");
828 log(" -fast\n");
829 log(" use different default scripts that are slightly faster (at the cost\n");
830 log(" of output quality):\n");
831 log("\n");
832 log(" for -liberty without -constr:\n");
833 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str());
834 log("\n");
835 log(" for -liberty with -constr:\n");
836 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str());
837 log("\n");
838 log(" for -lut/-luts:\n");
839 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
840 log("\n");
841 log(" for -sop:\n");
842 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str());
843 log("\n");
844 log(" otherwise:\n");
845 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str());
846 log("\n");
847 log(" -liberty <file>\n");
848 log(" generate netlists for the specified cell library (using the liberty\n");
849 log(" file format).\n");
850 log("\n");
851 log(" -constr <file>\n");
852 log(" pass this file with timing constraints to ABC. use with -liberty.\n");
853 log("\n");
854 log(" a constr file contains two lines:\n");
855 log(" set_driving_cell <cell_name>\n");
856 log(" set_load <floating_point_number>\n");
857 log("\n");
858 log(" the set_driving_cell statement defines which cell type is assumed to\n");
859 log(" drive the primary inputs and the set_load statement sets the load in\n");
860 log(" femtofarads for each primary output.\n");
861 log("\n");
862 log(" -D <picoseconds>\n");
863 log(" set delay target. the string {D} in the default scripts above is\n");
864 log(" replaced by this option when used, and an empty string otherwise.\n");
865 log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
866 log(" default scripts above.\n");
867 log("\n");
868 log(" -I <num>\n");
869 log(" maximum number of SOP inputs.\n");
870 log(" (replaces {I} in the default scripts above)\n");
871 log("\n");
872 log(" -P <num>\n");
873 log(" maximum number of SOP products.\n");
874 log(" (replaces {P} in the default scripts above)\n");
875 log("\n");
876 log(" -S <num>\n");
877 log(" maximum number of LUT inputs shared.\n");
878 log(" (replaces {S} in the default scripts above, default: -S 1)\n");
879 log("\n");
880 log(" -lut <width>\n");
881 log(" generate netlist using luts of (max) the specified width.\n");
882 log("\n");
883 log(" -lut <w1>:<w2>\n");
884 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
885 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
886 log(" the area cost doubles with each additional input bit. the delay cost\n");
887 log(" is still constant for all lut widths.\n");
888 log("\n");
889 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
890 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
891 log(" 2, 3, .. inputs.\n");
892 log("\n");
893 log(" -sop\n");
894 log(" map to sum-of-product cells and inverters\n");
895 log("\n");
896 // log(" -mux4, -mux8, -mux16\n");
897 // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n");
898 // log(" (ignored when used with -liberty or -lut)\n");
899 // log("\n");
900 log(" -g type1,type2,...\n");
901 log(" Map to the specified list of gate types. Supported gates types are:\n");
902 log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX, AOI3, OAI3, AOI4, OAI4.\n");
903 log(" (The NOT gate is always added to this list automatically.)\n");
904 log("\n");
905 log(" The following aliases can be used to reference common sets of gate types:\n");
906 log(" simple: AND OR XOR MUX\n");
907 log(" cmos2: NAND NOR\n");
908 log(" cmos3: NAND NOR AOI3 OAI3\n");
909 log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n");
910 log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n");
911 log(" aig: AND NAND OR NOR ANDNOT ORNOT\n");
912 log("\n");
913 log(" Prefix a gate type with a '-' to remove it from the list. For example\n");
914 log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n");
915 log("\n");
916 log(" -dff\n");
917 log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
918 log(" clock domains are automatically partitioned in clock domains and each\n");
919 log(" domain is passed through ABC independently.\n");
920 log("\n");
921 log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
922 log(" use only the specified clock domain. this is like -dff, but only FF\n");
923 log(" cells that belong to the specified clock domain are used.\n");
924 log("\n");
925 log(" -keepff\n");
926 log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
927 log(" them, for example for equivalence checking.)\n");
928 log("\n");
929 log(" -nocleanup\n");
930 log(" when this option is used, the temporary files created by this pass\n");
931 log(" are not removed. this is useful for debugging.\n");
932 log("\n");
933 log(" -showtmp\n");
934 log(" print the temp dir name in log. usually this is suppressed so that the\n");
935 log(" command output is identical across runs.\n");
936 log("\n");
937 log(" -markgroups\n");
938 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
939 log(" this attribute is a unique integer for each ABC process started. This\n");
940 log(" is useful for debugging the partitioning of clock domains.\n");
941 log("\n");
942 log("When neither -liberty nor -lut is used, the Yosys standard cell library is\n");
943 log("loaded into ABC before the ABC script is executed.\n");
944 log("\n");
945 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
946 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
947 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
948 log("output when passing an ABC script that writes a file. Instead write your full\n");
949 log("design as BLIF file with write_blif and the load that into ABC externally if\n");
950 log("you want to use ABC to convert your design into another format.\n");
951 log("\n");
952 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
953 log("\n");
954 }
955 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
956 {
957 log_header(design, "Executing ABC9 pass (technology mapping using ABC).\n");
958 log_push();
959
960 assign_map.clear();
961 signal_map.clear();
962 signal_init.clear();
963 pi_map.clear();
964 po_map.clear();
965
966 #ifdef ABCEXTERNAL
967 std::string exe_file = ABCEXTERNAL;
968 #else
969 std::string exe_file = proc_self_dirname() + "yosys-abc";
970 #endif
971 std::string script_file, liberty_file, constr_file, clk_str;
972 std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1";
973 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
974 bool show_tempdir = false, sop_mode = false;
975 show_tempdir = true; cleanup = false;
976 vector<int> lut_costs;
977 markgroups = false;
978
979 map_mux4 = false;
980 map_mux8 = false;
981 map_mux16 = false;
982 enabled_gates.clear();
983
984 #ifdef _WIN32
985 #ifndef ABCEXTERNAL
986 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
987 exe_file = proc_self_dirname() + "..\\yosys-abc";
988 #endif
989 #endif
990
991 size_t argidx;
992 char pwd [PATH_MAX];
993 if (!getcwd(pwd, sizeof(pwd))) {
994 log_cmd_error("getcwd failed: %s\n", strerror(errno));
995 log_abort();
996 }
997 for (argidx = 1; argidx < args.size(); argidx++) {
998 std::string arg = args[argidx];
999 if (arg == "-exe" && argidx+1 < args.size()) {
1000 exe_file = args[++argidx];
1001 continue;
1002 }
1003 if (arg == "-script" && argidx+1 < args.size()) {
1004 script_file = args[++argidx];
1005 rewrite_filename(script_file);
1006 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
1007 script_file = std::string(pwd) + "/" + script_file;
1008 continue;
1009 }
1010 if (arg == "-liberty" && argidx+1 < args.size()) {
1011 liberty_file = args[++argidx];
1012 rewrite_filename(liberty_file);
1013 if (!liberty_file.empty() && !is_absolute_path(liberty_file))
1014 liberty_file = std::string(pwd) + "/" + liberty_file;
1015 continue;
1016 }
1017 if (arg == "-constr" && argidx+1 < args.size()) {
1018 rewrite_filename(constr_file);
1019 constr_file = args[++argidx];
1020 if (!constr_file.empty() && !is_absolute_path(constr_file))
1021 constr_file = std::string(pwd) + "/" + constr_file;
1022 continue;
1023 }
1024 if (arg == "-D" && argidx+1 < args.size()) {
1025 delay_target = "-D " + args[++argidx];
1026 continue;
1027 }
1028 if (arg == "-I" && argidx+1 < args.size()) {
1029 sop_inputs = "-I " + args[++argidx];
1030 continue;
1031 }
1032 if (arg == "-P" && argidx+1 < args.size()) {
1033 sop_products = "-P " + args[++argidx];
1034 continue;
1035 }
1036 if (arg == "-S" && argidx+1 < args.size()) {
1037 lutin_shared = "-S " + args[++argidx];
1038 continue;
1039 }
1040 if (arg == "-lut" && argidx+1 < args.size()) {
1041 string arg = args[++argidx];
1042 size_t pos = arg.find_first_of(':');
1043 int lut_mode = 0, lut_mode2 = 0;
1044 if (pos != string::npos) {
1045 lut_mode = atoi(arg.substr(0, pos).c_str());
1046 lut_mode2 = atoi(arg.substr(pos+1).c_str());
1047 } else {
1048 lut_mode = atoi(arg.c_str());
1049 lut_mode2 = lut_mode;
1050 }
1051 lut_costs.clear();
1052 for (int i = 0; i < lut_mode; i++)
1053 lut_costs.push_back(1);
1054 for (int i = lut_mode; i < lut_mode2; i++)
1055 lut_costs.push_back(2 << (i - lut_mode));
1056 continue;
1057 }
1058 if (arg == "-luts" && argidx+1 < args.size()) {
1059 lut_costs.clear();
1060 for (auto &tok : split_tokens(args[++argidx], ",")) {
1061 auto parts = split_tokens(tok, ":");
1062 if (GetSize(parts) == 0 && !lut_costs.empty())
1063 lut_costs.push_back(lut_costs.back());
1064 else if (GetSize(parts) == 1)
1065 lut_costs.push_back(atoi(parts.at(0).c_str()));
1066 else if (GetSize(parts) == 2)
1067 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
1068 lut_costs.push_back(atoi(parts.at(1).c_str()));
1069 else
1070 log_cmd_error("Invalid -luts syntax.\n");
1071 }
1072 continue;
1073 }
1074 if (arg == "-sop") {
1075 sop_mode = true;
1076 continue;
1077 }
1078 if (arg == "-mux4") {
1079 map_mux4 = true;
1080 continue;
1081 }
1082 if (arg == "-mux8") {
1083 map_mux8 = true;
1084 continue;
1085 }
1086 if (arg == "-mux16") {
1087 map_mux16 = true;
1088 continue;
1089 }
1090 if (arg == "-g" && argidx+1 < args.size()) {
1091 for (auto g : split_tokens(args[++argidx], ",")) {
1092 vector<string> gate_list;
1093 bool remove_gates = false;
1094 if (GetSize(g) > 0 && g[0] == '-') {
1095 remove_gates = true;
1096 g = g.substr(1);
1097 }
1098 if (g == "AND") goto ok_gate;
1099 if (g == "NAND") goto ok_gate;
1100 if (g == "OR") goto ok_gate;
1101 if (g == "NOR") goto ok_gate;
1102 if (g == "XOR") goto ok_gate;
1103 if (g == "XNOR") goto ok_gate;
1104 if (g == "ANDNOT") goto ok_gate;
1105 if (g == "ORNOT") goto ok_gate;
1106 if (g == "MUX") goto ok_gate;
1107 if (g == "AOI3") goto ok_gate;
1108 if (g == "OAI3") goto ok_gate;
1109 if (g == "AOI4") goto ok_gate;
1110 if (g == "OAI4") goto ok_gate;
1111 if (g == "simple") {
1112 gate_list.push_back("AND");
1113 gate_list.push_back("OR");
1114 gate_list.push_back("XOR");
1115 gate_list.push_back("MUX");
1116 goto ok_alias;
1117 }
1118 if (g == "cmos2") {
1119 gate_list.push_back("NAND");
1120 gate_list.push_back("NOR");
1121 goto ok_alias;
1122 }
1123 if (g == "cmos3") {
1124 gate_list.push_back("NAND");
1125 gate_list.push_back("NOR");
1126 gate_list.push_back("AOI3");
1127 gate_list.push_back("OAI3");
1128 goto ok_alias;
1129 }
1130 if (g == "cmos4") {
1131 gate_list.push_back("NAND");
1132 gate_list.push_back("NOR");
1133 gate_list.push_back("AOI3");
1134 gate_list.push_back("OAI3");
1135 gate_list.push_back("AOI4");
1136 gate_list.push_back("OAI4");
1137 goto ok_alias;
1138 }
1139 if (g == "gates") {
1140 gate_list.push_back("AND");
1141 gate_list.push_back("NAND");
1142 gate_list.push_back("OR");
1143 gate_list.push_back("NOR");
1144 gate_list.push_back("XOR");
1145 gate_list.push_back("XNOR");
1146 gate_list.push_back("ANDNOT");
1147 gate_list.push_back("ORNOT");
1148 goto ok_alias;
1149 }
1150 if (g == "aig") {
1151 gate_list.push_back("AND");
1152 gate_list.push_back("NAND");
1153 gate_list.push_back("OR");
1154 gate_list.push_back("NOR");
1155 gate_list.push_back("ANDNOT");
1156 gate_list.push_back("ORNOT");
1157 goto ok_alias;
1158 }
1159 cmd_error(args, argidx, stringf("Unsupported gate type: %s", g.c_str()));
1160 ok_gate:
1161 gate_list.push_back(g);
1162 ok_alias:
1163 for (auto gate : gate_list) {
1164 if (remove_gates)
1165 enabled_gates.erase(gate);
1166 else
1167 enabled_gates.insert(gate);
1168 }
1169 }
1170 continue;
1171 }
1172 if (arg == "-fast") {
1173 fast_mode = true;
1174 continue;
1175 }
1176 if (arg == "-dff") {
1177 dff_mode = true;
1178 continue;
1179 }
1180 if (arg == "-clk" && argidx+1 < args.size()) {
1181 clk_str = args[++argidx];
1182 dff_mode = true;
1183 continue;
1184 }
1185 if (arg == "-keepff") {
1186 keepff = true;
1187 continue;
1188 }
1189 if (arg == "-nocleanup") {
1190 cleanup = false;
1191 continue;
1192 }
1193 if (arg == "-showtmp") {
1194 show_tempdir = true;
1195 continue;
1196 }
1197 if (arg == "-markgroups") {
1198 markgroups = true;
1199 continue;
1200 }
1201 break;
1202 }
1203 extra_args(args, argidx, design);
1204
1205 if (!lut_costs.empty() && !liberty_file.empty())
1206 log_cmd_error("Got -lut and -liberty! This two options are exclusive.\n");
1207 if (!constr_file.empty() && liberty_file.empty())
1208 log_cmd_error("Got -constr but no -liberty!\n");
1209
1210 for (auto mod : design->selected_modules())
1211 {
1212 if (mod->processes.size() > 0) {
1213 log("Skipping module %s as it contains processes.\n", log_id(mod));
1214 continue;
1215 }
1216
1217 assign_map.set(mod);
1218 signal_init.clear();
1219
1220 for (Wire *wire : mod->wires())
1221 if (wire->attributes.count("\\init")) {
1222 SigSpec initsig = assign_map(wire);
1223 Const initval = wire->attributes.at("\\init");
1224 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
1225 switch (initval[i]) {
1226 case State::S0:
1227 signal_init[initsig[i]] = State::S0;
1228 break;
1229 case State::S1:
1230 signal_init[initsig[i]] = State::S0;
1231 break;
1232 default:
1233 break;
1234 }
1235 }
1236
1237 if (!dff_mode || !clk_str.empty()) {
1238 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1239 delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode);
1240 continue;
1241 }
1242
1243 CellTypes ct(design);
1244
1245 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1246 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1247
1248 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1249 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1250 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1251
1252 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1253 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1254 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1255
1256 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1257 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1258
1259 for (auto cell : all_cells)
1260 {
1261 clkdomain_t key;
1262
1263 for (auto &conn : cell->connections())
1264 for (auto bit : conn.second) {
1265 bit = assign_map(bit);
1266 if (bit.wire != nullptr) {
1267 cell_to_bit[cell].insert(bit);
1268 bit_to_cell[bit].insert(cell);
1269 if (ct.cell_input(cell->type, conn.first)) {
1270 cell_to_bit_up[cell].insert(bit);
1271 bit_to_cell_down[bit].insert(cell);
1272 }
1273 if (ct.cell_output(cell->type, conn.first)) {
1274 cell_to_bit_down[cell].insert(bit);
1275 bit_to_cell_up[bit].insert(cell);
1276 }
1277 }
1278 }
1279
1280 if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
1281 {
1282 key = clkdomain_t(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")), true, RTLIL::SigSpec());
1283 }
1284 else
1285 if (cell->type == "$_DFFE_NN_" || cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_")
1286 {
1287 bool this_clk_pol = cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_";
1288 bool this_en_pol = cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PP_";
1289 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort("\\C")), this_en_pol, assign_map(cell->getPort("\\E")));
1290 }
1291 else
1292 continue;
1293
1294 unassigned_cells.erase(cell);
1295 expand_queue.insert(cell);
1296 expand_queue_up.insert(cell);
1297 expand_queue_down.insert(cell);
1298
1299 assigned_cells[key].push_back(cell);
1300 assigned_cells_reverse[cell] = key;
1301 }
1302
1303 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1304 {
1305 if (!expand_queue_up.empty())
1306 {
1307 RTLIL::Cell *cell = *expand_queue_up.begin();
1308 clkdomain_t key = assigned_cells_reverse.at(cell);
1309 expand_queue_up.erase(cell);
1310
1311 for (auto bit : cell_to_bit_up[cell])
1312 for (auto c : bit_to_cell_up[bit])
1313 if (unassigned_cells.count(c)) {
1314 unassigned_cells.erase(c);
1315 next_expand_queue_up.insert(c);
1316 assigned_cells[key].push_back(c);
1317 assigned_cells_reverse[c] = key;
1318 expand_queue.insert(c);
1319 }
1320 }
1321
1322 if (!expand_queue_down.empty())
1323 {
1324 RTLIL::Cell *cell = *expand_queue_down.begin();
1325 clkdomain_t key = assigned_cells_reverse.at(cell);
1326 expand_queue_down.erase(cell);
1327
1328 for (auto bit : cell_to_bit_down[cell])
1329 for (auto c : bit_to_cell_down[bit])
1330 if (unassigned_cells.count(c)) {
1331 unassigned_cells.erase(c);
1332 next_expand_queue_up.insert(c);
1333 assigned_cells[key].push_back(c);
1334 assigned_cells_reverse[c] = key;
1335 expand_queue.insert(c);
1336 }
1337 }
1338
1339 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1340 expand_queue_up.swap(next_expand_queue_up);
1341 expand_queue_down.swap(next_expand_queue_down);
1342 }
1343 }
1344
1345 while (!expand_queue.empty())
1346 {
1347 RTLIL::Cell *cell = *expand_queue.begin();
1348 clkdomain_t key = assigned_cells_reverse.at(cell);
1349 expand_queue.erase(cell);
1350
1351 for (auto bit : cell_to_bit.at(cell)) {
1352 for (auto c : bit_to_cell[bit])
1353 if (unassigned_cells.count(c)) {
1354 unassigned_cells.erase(c);
1355 next_expand_queue.insert(c);
1356 assigned_cells[key].push_back(c);
1357 assigned_cells_reverse[c] = key;
1358 }
1359 bit_to_cell[bit].clear();
1360 }
1361
1362 if (expand_queue.empty())
1363 expand_queue.swap(next_expand_queue);
1364 }
1365
1366 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1367 for (auto cell : unassigned_cells) {
1368 assigned_cells[key].push_back(cell);
1369 assigned_cells_reverse[cell] = key;
1370 }
1371
1372 log_header(design, "Summary of detected clock domains:\n");
1373 for (auto &it : assigned_cells)
1374 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1375 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1376 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1377
1378 for (auto &it : assigned_cells) {
1379 clk_polarity = std::get<0>(it.first);
1380 clk_sig = assign_map(std::get<1>(it.first));
1381 en_polarity = std::get<2>(it.first);
1382 en_sig = assign_map(std::get<3>(it.first));
1383 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1384 keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode);
1385 assign_map.set(mod);
1386 }
1387 }
1388
1389 assign_map.clear();
1390 signal_map.clear();
1391 signal_init.clear();
1392 pi_map.clear();
1393 po_map.clear();
1394
1395 log_pop();
1396 }
1397 } Abc9Pass;
1398
1399 PRIVATE_NAMESPACE_END