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