Consistency
[yosys.git] / passes / techmap / abc9.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * 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} -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 std::string wire_delay)
277 {
278 module = current_module;
279 map_autoidx = autoidx++;
280
281 signal_map.clear();
282 pi_map.clear();
283 po_map.clear();
284 recover_init = false;
285
286 if (clk_str != "$")
287 {
288 clk_polarity = true;
289 clk_sig = RTLIL::SigSpec();
290
291 en_polarity = true;
292 en_sig = RTLIL::SigSpec();
293 }
294
295 if (!clk_str.empty() && clk_str != "$")
296 {
297 if (clk_str.find(',') != std::string::npos) {
298 int pos = clk_str.find(',');
299 std::string en_str = clk_str.substr(pos+1);
300 clk_str = clk_str.substr(0, pos);
301 if (en_str[0] == '!') {
302 en_polarity = false;
303 en_str = en_str.substr(1);
304 }
305 if (module->wires_.count(RTLIL::escape_id(en_str)) != 0)
306 en_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(en_str)), 0));
307 }
308 if (clk_str[0] == '!') {
309 clk_polarity = false;
310 clk_str = clk_str.substr(1);
311 }
312 if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
313 clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
314 }
315
316 if (dff_mode && clk_sig.empty())
317 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
318
319 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
320 if (!cleanup)
321 tempdir_name[0] = tempdir_name[4] = '_';
322 tempdir_name = make_temp_dir(tempdir_name);
323 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
324 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
325
326 std::string abc_script;
327
328 if (!liberty_file.empty()) {
329 abc_script += stringf("read_lib -w %s; ", liberty_file.c_str());
330 if (!constr_file.empty())
331 abc_script += stringf("read_constr -v %s; ", constr_file.c_str());
332 } else
333 if (!lut_costs.empty()) {
334 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
335 if (!box_file.empty())
336 abc_script += stringf("read_box -v %s; ", box_file.c_str());
337 }
338 else
339 if (!lut_file.empty()) {
340 abc_script += stringf("read_lut %s; ", lut_file.c_str());
341 if (!box_file.empty())
342 abc_script += stringf("read_box -v %s; ", box_file.c_str());
343 }
344 else
345 abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str());
346
347 abc_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
348
349 if (!script_file.empty()) {
350 if (script_file[0] == '+') {
351 for (size_t i = 1; i < script_file.size(); i++)
352 if (script_file[i] == '\'')
353 abc_script += "'\\''";
354 else if (script_file[i] == ',')
355 abc_script += " ";
356 else
357 abc_script += script_file[i];
358 } else
359 abc_script += stringf("source %s", script_file.c_str());
360 } else if (!lut_costs.empty() || !lut_file.empty()) {
361 //bool all_luts_cost_same = true;
362 //for (int this_cost : lut_costs)
363 // if (this_cost != lut_costs.front())
364 // all_luts_cost_same = false;
365 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
366 //if (all_luts_cost_same && !fast_mode)
367 // abc_script += "; lutpack {S}";
368 } else if (!liberty_file.empty())
369 abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
370 else if (sop_mode)
371 abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
372 else
373 abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
374
375 if (script_file.empty() && !delay_target.empty())
376 for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
377 abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
378
379 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
380 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
381
382 for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
383 abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3);
384
385 for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
386 abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3);
387
388 for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
389 abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
390
391 for (size_t pos = abc_script.find("{W}"); pos != std::string::npos; pos = abc_script.find("{W}", pos))
392 abc_script = abc_script.substr(0, pos) + wire_delay + abc_script.substr(pos+3);
393
394 abc_script += stringf("; &write %s/output.aig", tempdir_name.c_str());
395 abc_script = add_echos_to_abc_cmd(abc_script);
396
397 for (size_t i = 0; i+1 < abc_script.size(); i++)
398 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
399 abc_script[i+1] = '\n';
400
401 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
402 fprintf(f, "%s\n", abc_script.c_str());
403 fclose(f);
404
405 if (dff_mode || !clk_str.empty())
406 {
407 if (clk_sig.size() == 0)
408 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
409 else {
410 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
411 if (en_sig.size() != 0)
412 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
413 log("\n");
414 }
415 }
416
417 design->selection_stack.emplace_back(false);
418 RTLIL::Selection& sel = design->selection_stack.back();
419 sel.select(module);
420
421 // Behave as for "abc" where BLIF writer implicitly outputs all undef as zero
422 Pass::call(design, "setundef -zero");
423
424 Pass::call(design, "aigmap");
425
426 handle_loops(design);
427
428 Pass::call(design, stringf("write_xaiger -O -map %s/input.sym %s/input.xaig; ", tempdir_name.c_str(), tempdir_name.c_str()));
429
430 #if 0
431 std::string buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
432 std::ifstream ifs;
433 ifs.open(buffer);
434 if (ifs.fail())
435 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
436 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
437 log_assert(!design->module("$__abc9__"));
438 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, false /* wideports */);
439 reader.parse_xaiger();
440 ifs.close();
441 Pass::call(design, stringf("write_verilog -noexpr -norename %s/%s", tempdir_name.c_str(), "input.v"));
442 design->remove(design->module("$__abc9__"));
443 #endif
444
445 design->selection_stack.pop_back();
446
447 // Now 'unexpose' those wires by undoing
448 // the expose operation -- remove them from PO/PI
449 // and re-connecting them back together
450 for (auto wire : module->wires()) {
451 auto it = wire->attributes.find("\\abc_scc_break");
452 if (it != wire->attributes.end()) {
453 wire->attributes.erase(it);
454 log_assert(wire->port_output);
455 wire->port_output = false;
456 RTLIL::Wire *i_wire = module->wire(wire->name.str() + ".abci");
457 log_assert(i_wire);
458 log_assert(i_wire->port_input);
459 i_wire->port_input = false;
460 module->connect(i_wire, wire);
461 }
462 }
463 module->fixup_ports();
464
465 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
466 // count_gates, GetSize(signal_list), count_input, count_output);
467
468 log_push();
469
470 //if (count_output > 0)
471 {
472 log_header(design, "Executing ABC9.\n");
473
474 std::string buffer;
475 if (!lut_costs.empty()) {
476 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
477 f = fopen(buffer.c_str(), "wt");
478 if (f == NULL)
479 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
480 for (int i = 0; i < GetSize(lut_costs); i++)
481 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
482 fclose(f);
483 }
484
485 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
486 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
487
488 #ifndef YOSYS_LINK_ABC
489 abc_output_filter filt(tempdir_name, show_tempdir);
490 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
491 #else
492 // These needs to be mutable, supposedly due to getopt
493 char *abc_argv[5];
494 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
495 abc_argv[0] = strdup(exe_file.c_str());
496 abc_argv[1] = strdup("-s");
497 abc_argv[2] = strdup("-f");
498 abc_argv[3] = strdup(tmp_script_name.c_str());
499 abc_argv[4] = 0;
500 int ret = Abc_RealMain(4, abc_argv);
501 free(abc_argv[0]);
502 free(abc_argv[1]);
503 free(abc_argv[2]);
504 free(abc_argv[3]);
505 #endif
506 if (ret != 0)
507 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
508
509 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
510 std::ifstream ifs;
511 ifs.open(buffer);
512 if (ifs.fail())
513 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
514
515 bool builtin_lib = liberty_file.empty();
516 //parse_blif(mapped_design, ifs, builtin_lib ? "\\DFF" : "\\_dff_", false, sop_mode);
517 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
518 log_assert(!design->module("$__abc9__"));
519 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, false /* wideports */);
520 reader.parse_xaiger();
521 ifs.close();
522
523 #if 0
524 Pass::call(design, stringf("write_verilog -noexpr -norename %s/%s", tempdir_name.c_str(), "output.v"));
525 #endif
526
527 log_header(design, "Re-integrating ABC9 results.\n");
528 RTLIL::Module *mapped_mod = design->module("$__abc9__");
529 if (mapped_mod == NULL)
530 log_error("ABC output file does not contain a module `$__abc9__'.\n");
531
532 pool<RTLIL::SigBit> output_bits;
533 for (auto &it : mapped_mod->wires_) {
534 RTLIL::Wire *w = it.second;
535 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
536 if (markgroups) remap_wire->attributes["\\abcgroup"] = map_autoidx;
537 if (w->port_output) {
538 RTLIL::Wire *wire = module->wire(w->name);
539 if (wire) {
540 for (int i = 0; i < GetSize(wire); i++)
541 output_bits.insert({wire, i});
542 }
543 else {
544 // Attempt another wideports_split here because there
545 // exists the possibility that different bits of a port
546 // could be an input and output, therefore parse_xaiger()
547 // could not combine it into a wideport
548 auto r = wideports_split(w->name.str());
549 wire = module->wire(r.first);
550 log_assert(wire);
551 int i = r.second;
552 output_bits.insert({wire, i});
553 }
554 }
555 }
556
557 // Remove all AND, NOT, and ABC box instances
558 // in preparation for stitching mapped_mod in
559 dict<IdString, decltype(RTLIL::Cell::parameters)> erased_boxes;
560 for (auto it = module->cells_.begin(); it != module->cells_.end(); ) {
561 RTLIL::Cell* cell = it->second;
562 if (cell->type.in("$_AND_", "$_NOT_")) {
563 it = module->cells_.erase(it);
564 continue;
565 }
566 RTLIL::Module* box_module = design->module(cell->type);
567 if (box_module && box_module->attributes.count("\\abc_box_id")) {
568 erased_boxes.insert(std::make_pair(it->first, std::move(cell->parameters)));
569 it = module->cells_.erase(it);
570 continue;
571 }
572 ++it;
573 }
574 // Do the same for module connections
575 for (auto &it : module->connections_) {
576 auto &signal = it.first;
577 auto bits = signal.bits();
578 for (auto &b : bits)
579 if (output_bits.count(b))
580 b = module->addWire(NEW_ID);
581 signal = std::move(bits);
582 }
583
584 std::map<std::string, int> cell_stats;
585 for (auto c : mapped_mod->cells())
586 {
587 if (builtin_lib)
588 {
589 if (c->type == "$_NOT_") {
590 RTLIL::Cell *cell;
591 RTLIL::SigBit a_bit = c->getPort("\\A").as_bit();
592 RTLIL::SigBit y_bit = c->getPort("\\Y").as_bit();
593 if (!a_bit.wire) {
594 c->setPort("\\Y", module->addWire(NEW_ID));
595 module->connect(module->wires_[remap_name(y_bit.wire->name)], RTLIL::S1);
596 }
597 else if (!lut_costs.empty() || !lut_file.empty()) {
598 RTLIL::Cell* driving_lut = nullptr;
599 // ABC can return NOT gates that drive POs
600 if (!a_bit.wire->port_input) {
601 // If it's not a NOT gate that that comes from a PI directly,
602 // find the driving LUT and clone that to guarantee that we won't
603 // increase the max logic depth
604 // (TODO: Optimise by not cloning unless will increase depth)
605 RTLIL::IdString driver_name;
606 if (GetSize(a_bit.wire) == 1)
607 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
608 else
609 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
610 driving_lut = mapped_mod->cell(driver_name);
611 }
612
613 if (!driving_lut) {
614 // If a driver couldn't be found (could be from PI,
615 // or from a box) then implement using a LUT
616 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
617 RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset),
618 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
619 1);
620 }
621 else {
622 auto driver_a = driving_lut->getPort("\\A").chunks();
623 for (auto &chunk : driver_a)
624 chunk.wire = module->wires_[remap_name(chunk.wire->name)];
625 RTLIL::Const driver_lut = driving_lut->getParam("\\LUT");
626 for (auto &b : driver_lut.bits) {
627 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
628 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
629 }
630 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
631 driver_a,
632 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
633 driver_lut);
634 }
635 }
636 else {
637 cell = module->addCell(remap_name(c->name), "$_NOT_");
638 cell->setPort("\\A", RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset));
639 cell->setPort("\\Y", RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset));
640 cell_stats[RTLIL::unescape_id(c->type)]++;
641 }
642 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
643 continue;
644 }
645 }
646 cell_stats[RTLIL::unescape_id(c->type)]++;
647
648 if (c->type == "$lut") {
649 if (GetSize(c->getPort("\\A")) == 1 && c->getParam("\\LUT").as_int() == 2) {
650 SigSpec my_a = module->wires_[remap_name(c->getPort("\\A").as_wire()->name)];
651 SigSpec my_y = module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)];
652 module->connect(my_y, my_a);
653 continue;
654 }
655 }
656 else {
657 auto it = erased_boxes.find(c->name);
658 log_assert(it != erased_boxes.end());
659 c->parameters = std::move(it->second);
660 }
661
662 RTLIL::Cell* cell = module->addCell(remap_name(c->name), c->type);
663 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
664 cell->parameters = c->parameters;
665 for (auto &conn : c->connections()) {
666 RTLIL::SigSpec newsig;
667 for (auto c : conn.second.chunks()) {
668 if (c.width == 0)
669 continue;
670 //log_assert(c.width == 1);
671 if (c.wire)
672 c.wire = module->wires_[remap_name(c.wire->name)];
673 newsig.append(c);
674 }
675 cell->setPort(conn.first, newsig);
676 }
677 }
678
679 // Copy connections (and rename) from mapped_mod to module
680 for (auto conn : mapped_mod->connections()) {
681 if (!conn.first.is_fully_const()) {
682 auto chunks = conn.first.chunks();
683 for (auto &c : chunks)
684 c.wire = module->wires_[remap_name(c.wire->name)];
685 conn.first = std::move(chunks);
686 }
687 if (!conn.second.is_fully_const()) {
688 auto chunks = conn.second.chunks();
689 for (auto &c : chunks)
690 if (c.wire)
691 c.wire = module->wires_[remap_name(c.wire->name)];
692 conn.second = std::move(chunks);
693 }
694 module->connect(conn);
695 }
696
697 if (recover_init)
698 for (auto wire : mapped_mod->wires()) {
699 if (wire->attributes.count("\\init")) {
700 Wire *w = module->wires_[remap_name(wire->name)];
701 log_assert(w->attributes.count("\\init") == 0);
702 w->attributes["\\init"] = wire->attributes.at("\\init");
703 }
704 }
705
706 for (auto &it : cell_stats)
707 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
708 int in_wires = 0, out_wires = 0;
709
710 // Stitch in mapped_mod's inputs/outputs into module
711 for (auto &it : mapped_mod->wires_) {
712 RTLIL::Wire *w = it.second;
713 if (!w->port_input && !w->port_output)
714 continue;
715 RTLIL::Wire *wire = module->wire(w->name);
716 RTLIL::Wire *remap_wire = module->wire(remap_name(w->name));
717 RTLIL::SigSpec signal;
718 if (wire) {
719 signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
720 }
721 else {
722 // Attempt another wideports_split here because there
723 // exists the possibility that different bits of a port
724 // could be an input and output, therefore parse_xaiger()
725 // could not combine it into a wideport
726 auto r = wideports_split(w->name.str());
727 wire = module->wire(r.first);
728 log_assert(wire);
729 int i = r.second;
730 signal = RTLIL::SigSpec(wire, i);
731 }
732 log_assert(GetSize(signal) >= GetSize(remap_wire));
733
734 log_assert(w->port_input || w->port_output);
735 RTLIL::SigSig conn;
736 if (w->port_input) {
737 conn.first = remap_wire;
738 conn.second = signal;
739 in_wires++;
740 module->connect(conn);
741 }
742 if (w->port_output) {
743 conn.first = signal;
744 conn.second = remap_wire;
745 out_wires++;
746 module->connect(conn);
747 }
748 }
749
750 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
751 log("ABC RESULTS: input signals: %8d\n", in_wires);
752 log("ABC RESULTS: output signals: %8d\n", out_wires);
753
754 design->remove(mapped_mod);
755 }
756 //else
757 //{
758 // log("Don't call ABC as there is nothing to map.\n");
759 //}
760
761 if (cleanup)
762 {
763 log("Removing temp directory.\n");
764 remove_directory(tempdir_name);
765 }
766
767 log_pop();
768 }
769
770 struct Abc9Pass : public Pass {
771 Abc9Pass() : Pass("abc9", "use ABC for technology mapping") { }
772 void help() YS_OVERRIDE
773 {
774 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
775 log("\n");
776 log(" abc9 [options] [selection]\n");
777 log("\n");
778 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
779 log("library to a target architecture.\n");
780 log("\n");
781 log(" -exe <command>\n");
782 #ifdef ABCEXTERNAL
783 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
784 #else
785 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
786 #endif
787 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
788 log("\n");
789 log(" -script <file>\n");
790 log(" use the specified ABC script file instead of the default script.\n");
791 log("\n");
792 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
793 log(" string is interpreted as the command string to be passed to ABC. The\n");
794 log(" leading plus sign is removed and all commas (,) in the string are\n");
795 log(" replaced with blanks before the string is passed to ABC.\n");
796 log("\n");
797 log(" if no -script parameter is given, the following scripts are used:\n");
798 log("\n");
799 log(" for -liberty without -constr:\n");
800 log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str());
801 log("\n");
802 log(" for -liberty with -constr:\n");
803 log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str());
804 log("\n");
805 log(" for -lut/-luts (only one LUT size):\n");
806 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str());
807 log("\n");
808 log(" for -lut/-luts (different LUT sizes):\n");
809 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
810 log("\n");
811 log(" for -sop:\n");
812 log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str());
813 log("\n");
814 log(" otherwise:\n");
815 log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str());
816 log("\n");
817 log(" -fast\n");
818 log(" use different default scripts that are slightly faster (at the cost\n");
819 log(" of output quality):\n");
820 log("\n");
821 log(" for -liberty without -constr:\n");
822 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str());
823 log("\n");
824 log(" for -liberty with -constr:\n");
825 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str());
826 log("\n");
827 log(" for -lut/-luts:\n");
828 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
829 log("\n");
830 log(" for -sop:\n");
831 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str());
832 log("\n");
833 log(" otherwise:\n");
834 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str());
835 log("\n");
836 log(" -liberty <file>\n");
837 log(" generate netlists for the specified cell library (using the liberty\n");
838 log(" file format).\n");
839 log("\n");
840 log(" -constr <file>\n");
841 log(" pass this file with timing constraints to ABC. Use with -liberty.\n");
842 log("\n");
843 log(" a constr file contains two lines:\n");
844 log(" set_driving_cell <cell_name>\n");
845 log(" set_load <floating_point_number>\n");
846 log("\n");
847 log(" the set_driving_cell statement defines which cell type is assumed to\n");
848 log(" drive the primary inputs and the set_load statement sets the load in\n");
849 log(" femtofarads for each primary output.\n");
850 log("\n");
851 log(" -D <picoseconds>\n");
852 log(" set delay target. the string {D} in the default scripts above is\n");
853 log(" replaced by this option when used, and an empty string otherwise.\n");
854 log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
855 log(" default scripts above.\n");
856 log("\n");
857 log(" -I <num>\n");
858 log(" maximum number of SOP inputs.\n");
859 log(" (replaces {I} in the default scripts above)\n");
860 log("\n");
861 log(" -P <num>\n");
862 log(" maximum number of SOP products.\n");
863 log(" (replaces {P} in the default scripts above)\n");
864 log("\n");
865 log(" -S <num>\n");
866 log(" maximum number of LUT inputs shared.\n");
867 log(" (replaces {S} in the default scripts above, default: -S 1)\n");
868 log("\n");
869 log(" -lut <width>\n");
870 log(" generate netlist using luts of (max) the specified width.\n");
871 log("\n");
872 log(" -lut <w1>:<w2>\n");
873 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
874 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
875 log(" the area cost doubles with each additional input bit. the delay cost\n");
876 log(" is still constant for all lut widths.\n");
877 log("\n");
878 log(" -lut <file>\n");
879 log(" pass this file with lut library to ABC.\n");
880 log("\n");
881 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
882 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
883 log(" 2, 3, .. inputs.\n");
884 log("\n");
885 log(" -sop\n");
886 log(" map to sum-of-product cells and inverters\n");
887 log("\n");
888 // log(" -mux4, -mux8, -mux16\n");
889 // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n");
890 // log(" (ignored when used with -liberty or -lut)\n");
891 // log("\n");
892 log(" -g type1,type2,...\n");
893 log(" Map to the specified list of gate types. Supported gates types are:\n");
894 log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX, AOI3, OAI3, AOI4, OAI4.\n");
895 log(" (The NOT gate is always added to this list automatically.)\n");
896 log("\n");
897 log(" The following aliases can be used to reference common sets of gate types:\n");
898 log(" simple: AND OR XOR MUX\n");
899 log(" cmos2: NAND NOR\n");
900 log(" cmos3: NAND NOR AOI3 OAI3\n");
901 log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n");
902 log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n");
903 log(" aig: AND NAND OR NOR ANDNOT ORNOT\n");
904 log("\n");
905 log(" Prefix a gate type with a '-' to remove it from the list. For example\n");
906 log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n");
907 log("\n");
908 log(" -dff\n");
909 log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
910 log(" clock domains are automatically partitioned in clock domains and each\n");
911 log(" domain is passed through ABC independently.\n");
912 log("\n");
913 log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
914 log(" use only the specified clock domain. this is like -dff, but only FF\n");
915 log(" cells that belong to the specified clock domain are used.\n");
916 log("\n");
917 log(" -keepff\n");
918 log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
919 log(" them, for example for equivalence checking.)\n");
920 log("\n");
921 log(" -nocleanup\n");
922 log(" when this option is used, the temporary files created by this pass\n");
923 log(" are not removed. this is useful for debugging.\n");
924 log("\n");
925 log(" -showtmp\n");
926 log(" print the temp dir name in log. usually this is suppressed so that the\n");
927 log(" command output is identical across runs.\n");
928 log("\n");
929 log(" -markgroups\n");
930 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
931 log(" this attribute is a unique integer for each ABC process started. This\n");
932 log(" is useful for debugging the partitioning of clock domains.\n");
933 log("\n");
934 log(" -box <file>\n");
935 log(" pass this file with box library to ABC. Use with -lut.\n");
936 log("\n");
937 log("When neither -liberty nor -lut is used, the Yosys standard cell library is\n");
938 log("loaded into ABC before the ABC script is executed.\n");
939 log("\n");
940 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
941 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
942 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
943 log("output when passing an ABC script that writes a file. Instead write your full\n");
944 log("design as BLIF file with write_blif and the load that into ABC externally if\n");
945 log("you want to use ABC to convert your design into another format.\n");
946 log("\n");
947 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
948 log("\n");
949 }
950 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
951 {
952 log_header(design, "Executing ABC9 pass (technology mapping using ABC).\n");
953 log_push();
954
955 assign_map.clear();
956 signal_map.clear();
957 signal_init.clear();
958 pi_map.clear();
959 po_map.clear();
960
961 #ifdef ABCEXTERNAL
962 std::string exe_file = ABCEXTERNAL;
963 #else
964 std::string exe_file = proc_self_dirname() + "yosys-abc";
965 #endif
966 std::string script_file, liberty_file, constr_file, clk_str, box_file, lut_file;
967 std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1", wire_delay;
968 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
969 bool show_tempdir = false, sop_mode = false;
970 vector<int> lut_costs;
971 markgroups = false;
972
973 #if 0
974 cleanup = false;
975 show_tempdir = true;
976 #endif
977
978 map_mux4 = false;
979 map_mux8 = false;
980 map_mux16 = false;
981 enabled_gates.clear();
982
983 #ifdef _WIN32
984 #ifndef ABCEXTERNAL
985 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
986 exe_file = proc_self_dirname() + "..\\yosys-abc";
987 #endif
988 #endif
989
990 size_t argidx;
991 char pwd [PATH_MAX];
992 if (!getcwd(pwd, sizeof(pwd))) {
993 log_cmd_error("getcwd failed: %s\n", strerror(errno));
994 log_abort();
995 }
996 for (argidx = 1; argidx < args.size(); argidx++) {
997 std::string arg = args[argidx];
998 if (arg == "-exe" && argidx+1 < args.size()) {
999 exe_file = args[++argidx];
1000 continue;
1001 }
1002 if (arg == "-script" && argidx+1 < args.size()) {
1003 script_file = args[++argidx];
1004 rewrite_filename(script_file);
1005 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
1006 script_file = std::string(pwd) + "/" + script_file;
1007 continue;
1008 }
1009 if (arg == "-liberty" && argidx+1 < args.size()) {
1010 liberty_file = args[++argidx];
1011 rewrite_filename(liberty_file);
1012 if (!liberty_file.empty() && !is_absolute_path(liberty_file))
1013 liberty_file = std::string(pwd) + "/" + liberty_file;
1014 continue;
1015 }
1016 if (arg == "-constr" && argidx+1 < args.size()) {
1017 constr_file = args[++argidx];
1018 rewrite_filename(constr_file);
1019 if (!constr_file.empty() && !is_absolute_path(constr_file))
1020 constr_file = std::string(pwd) + "/" + constr_file;
1021 continue;
1022 }
1023 if (arg == "-D" && argidx+1 < args.size()) {
1024 delay_target = "-D " + args[++argidx];
1025 continue;
1026 }
1027 if (arg == "-I" && argidx+1 < args.size()) {
1028 sop_inputs = "-I " + args[++argidx];
1029 continue;
1030 }
1031 if (arg == "-P" && argidx+1 < args.size()) {
1032 sop_products = "-P " + args[++argidx];
1033 continue;
1034 }
1035 if (arg == "-S" && argidx+1 < args.size()) {
1036 lutin_shared = "-S " + args[++argidx];
1037 continue;
1038 }
1039 if (arg == "-lut" && argidx+1 < args.size()) {
1040 string arg = args[++argidx];
1041 size_t pos = arg.find_first_of(':');
1042 int lut_mode = 0, lut_mode2 = 0;
1043 if (pos != string::npos) {
1044 lut_mode = atoi(arg.substr(0, pos).c_str());
1045 lut_mode2 = atoi(arg.substr(pos+1).c_str());
1046 } else {
1047 pos = arg.find_first_of('.');
1048 if (pos != string::npos) {
1049 lut_file = arg;
1050 rewrite_filename(lut_file);
1051 if (!lut_file.empty() && !is_absolute_path(lut_file))
1052 lut_file = std::string(pwd) + "/" + lut_file;
1053 }
1054 else {
1055 lut_mode = atoi(arg.c_str());
1056 lut_mode2 = lut_mode;
1057 }
1058 }
1059 lut_costs.clear();
1060 for (int i = 0; i < lut_mode; i++)
1061 lut_costs.push_back(1);
1062 for (int i = lut_mode; i < lut_mode2; i++)
1063 lut_costs.push_back(2 << (i - lut_mode));
1064 continue;
1065 }
1066 if (arg == "-luts" && argidx+1 < args.size()) {
1067 lut_costs.clear();
1068 for (auto &tok : split_tokens(args[++argidx], ",")) {
1069 auto parts = split_tokens(tok, ":");
1070 if (GetSize(parts) == 0 && !lut_costs.empty())
1071 lut_costs.push_back(lut_costs.back());
1072 else if (GetSize(parts) == 1)
1073 lut_costs.push_back(atoi(parts.at(0).c_str()));
1074 else if (GetSize(parts) == 2)
1075 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
1076 lut_costs.push_back(atoi(parts.at(1).c_str()));
1077 else
1078 log_cmd_error("Invalid -luts syntax.\n");
1079 }
1080 continue;
1081 }
1082 if (arg == "-sop") {
1083 sop_mode = true;
1084 continue;
1085 }
1086 if (arg == "-mux4") {
1087 map_mux4 = true;
1088 continue;
1089 }
1090 if (arg == "-mux8") {
1091 map_mux8 = true;
1092 continue;
1093 }
1094 if (arg == "-mux16") {
1095 map_mux16 = true;
1096 continue;
1097 }
1098 if (arg == "-dress") {
1099 // TODO
1100 //abc_dress = true;
1101 continue;
1102 }
1103 if (arg == "-g" && argidx+1 < args.size()) {
1104 for (auto g : split_tokens(args[++argidx], ",")) {
1105 vector<string> gate_list;
1106 bool remove_gates = false;
1107 if (GetSize(g) > 0 && g[0] == '-') {
1108 remove_gates = true;
1109 g = g.substr(1);
1110 }
1111 if (g == "AND") goto ok_gate;
1112 if (g == "NAND") goto ok_gate;
1113 if (g == "OR") goto ok_gate;
1114 if (g == "NOR") goto ok_gate;
1115 if (g == "XOR") goto ok_gate;
1116 if (g == "XNOR") goto ok_gate;
1117 if (g == "ANDNOT") goto ok_gate;
1118 if (g == "ORNOT") goto ok_gate;
1119 if (g == "MUX") goto ok_gate;
1120 if (g == "AOI3") goto ok_gate;
1121 if (g == "OAI3") goto ok_gate;
1122 if (g == "AOI4") goto ok_gate;
1123 if (g == "OAI4") goto ok_gate;
1124 if (g == "simple") {
1125 gate_list.push_back("AND");
1126 gate_list.push_back("OR");
1127 gate_list.push_back("XOR");
1128 gate_list.push_back("MUX");
1129 goto ok_alias;
1130 }
1131 if (g == "cmos2") {
1132 gate_list.push_back("NAND");
1133 gate_list.push_back("NOR");
1134 goto ok_alias;
1135 }
1136 if (g == "cmos3") {
1137 gate_list.push_back("NAND");
1138 gate_list.push_back("NOR");
1139 gate_list.push_back("AOI3");
1140 gate_list.push_back("OAI3");
1141 goto ok_alias;
1142 }
1143 if (g == "cmos4") {
1144 gate_list.push_back("NAND");
1145 gate_list.push_back("NOR");
1146 gate_list.push_back("AOI3");
1147 gate_list.push_back("OAI3");
1148 gate_list.push_back("AOI4");
1149 gate_list.push_back("OAI4");
1150 goto ok_alias;
1151 }
1152 if (g == "gates") {
1153 gate_list.push_back("AND");
1154 gate_list.push_back("NAND");
1155 gate_list.push_back("OR");
1156 gate_list.push_back("NOR");
1157 gate_list.push_back("XOR");
1158 gate_list.push_back("XNOR");
1159 gate_list.push_back("ANDNOT");
1160 gate_list.push_back("ORNOT");
1161 goto ok_alias;
1162 }
1163 if (g == "aig") {
1164 gate_list.push_back("AND");
1165 gate_list.push_back("NAND");
1166 gate_list.push_back("OR");
1167 gate_list.push_back("NOR");
1168 gate_list.push_back("ANDNOT");
1169 gate_list.push_back("ORNOT");
1170 goto ok_alias;
1171 }
1172 cmd_error(args, argidx, stringf("Unsupported gate type: %s", g.c_str()));
1173 ok_gate:
1174 gate_list.push_back(g);
1175 ok_alias:
1176 for (auto gate : gate_list) {
1177 if (remove_gates)
1178 enabled_gates.erase(gate);
1179 else
1180 enabled_gates.insert(gate);
1181 }
1182 }
1183 continue;
1184 }
1185 if (arg == "-fast") {
1186 fast_mode = true;
1187 continue;
1188 }
1189 if (arg == "-dff") {
1190 dff_mode = true;
1191 continue;
1192 }
1193 if (arg == "-clk" && argidx+1 < args.size()) {
1194 clk_str = args[++argidx];
1195 dff_mode = true;
1196 continue;
1197 }
1198 if (arg == "-keepff") {
1199 keepff = true;
1200 continue;
1201 }
1202 if (arg == "-nocleanup") {
1203 cleanup = false;
1204 continue;
1205 }
1206 if (arg == "-showtmp") {
1207 show_tempdir = true;
1208 continue;
1209 }
1210 if (arg == "-markgroups") {
1211 markgroups = true;
1212 continue;
1213 }
1214 if (arg == "-box" && argidx+1 < args.size()) {
1215 box_file = args[++argidx];
1216 rewrite_filename(box_file);
1217 if (!box_file.empty() && !is_absolute_path(box_file))
1218 box_file = std::string(pwd) + "/" + box_file;
1219 continue;
1220 }
1221 if (arg == "-W" && argidx+1 < args.size()) {
1222 wire_delay = "-W " + args[++argidx];
1223 continue;
1224 }
1225 break;
1226 }
1227 extra_args(args, argidx, design);
1228
1229 if ((!lut_costs.empty() || !lut_file.empty()) && !liberty_file.empty())
1230 log_cmd_error("Got -lut and -liberty! This two options are exclusive.\n");
1231 if (!constr_file.empty() && liberty_file.empty())
1232 log_cmd_error("Got -constr but no -liberty!\n");
1233
1234 for (auto mod : design->selected_modules())
1235 {
1236 if (mod->attributes.count("\\abc_box_id"))
1237 continue;
1238
1239 if (mod->processes.size() > 0) {
1240 log("Skipping module %s as it contains processes.\n", log_id(mod));
1241 continue;
1242 }
1243
1244 assign_map.set(mod);
1245 signal_init.clear();
1246
1247 for (Wire *wire : mod->wires())
1248 if (wire->attributes.count("\\init")) {
1249 SigSpec initsig = assign_map(wire);
1250 Const initval = wire->attributes.at("\\init");
1251 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
1252 switch (initval[i]) {
1253 case State::S0:
1254 signal_init[initsig[i]] = State::S0;
1255 break;
1256 case State::S1:
1257 signal_init[initsig[i]] = State::S0;
1258 break;
1259 default:
1260 break;
1261 }
1262 }
1263
1264 if (!dff_mode || !clk_str.empty()) {
1265 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1266 delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode,
1267 box_file, lut_file, wire_delay);
1268 continue;
1269 }
1270
1271 CellTypes ct(design);
1272
1273 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1274 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1275
1276 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1277 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1278 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1279
1280 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1281 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1282 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1283
1284 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1285 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1286
1287 for (auto cell : all_cells)
1288 {
1289 clkdomain_t key;
1290
1291 for (auto &conn : cell->connections())
1292 for (auto bit : conn.second) {
1293 bit = assign_map(bit);
1294 if (bit.wire != nullptr) {
1295 cell_to_bit[cell].insert(bit);
1296 bit_to_cell[bit].insert(cell);
1297 if (ct.cell_input(cell->type, conn.first)) {
1298 cell_to_bit_up[cell].insert(bit);
1299 bit_to_cell_down[bit].insert(cell);
1300 }
1301 if (ct.cell_output(cell->type, conn.first)) {
1302 cell_to_bit_down[cell].insert(bit);
1303 bit_to_cell_up[bit].insert(cell);
1304 }
1305 }
1306 }
1307
1308 if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
1309 {
1310 key = clkdomain_t(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")), true, RTLIL::SigSpec());
1311 }
1312 else
1313 if (cell->type == "$_DFFE_NN_" || cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_")
1314 {
1315 bool this_clk_pol = cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_";
1316 bool this_en_pol = cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PP_";
1317 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort("\\C")), this_en_pol, assign_map(cell->getPort("\\E")));
1318 }
1319 else
1320 continue;
1321
1322 unassigned_cells.erase(cell);
1323 expand_queue.insert(cell);
1324 expand_queue_up.insert(cell);
1325 expand_queue_down.insert(cell);
1326
1327 assigned_cells[key].push_back(cell);
1328 assigned_cells_reverse[cell] = key;
1329 }
1330
1331 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1332 {
1333 if (!expand_queue_up.empty())
1334 {
1335 RTLIL::Cell *cell = *expand_queue_up.begin();
1336 clkdomain_t key = assigned_cells_reverse.at(cell);
1337 expand_queue_up.erase(cell);
1338
1339 for (auto bit : cell_to_bit_up[cell])
1340 for (auto c : bit_to_cell_up[bit])
1341 if (unassigned_cells.count(c)) {
1342 unassigned_cells.erase(c);
1343 next_expand_queue_up.insert(c);
1344 assigned_cells[key].push_back(c);
1345 assigned_cells_reverse[c] = key;
1346 expand_queue.insert(c);
1347 }
1348 }
1349
1350 if (!expand_queue_down.empty())
1351 {
1352 RTLIL::Cell *cell = *expand_queue_down.begin();
1353 clkdomain_t key = assigned_cells_reverse.at(cell);
1354 expand_queue_down.erase(cell);
1355
1356 for (auto bit : cell_to_bit_down[cell])
1357 for (auto c : bit_to_cell_down[bit])
1358 if (unassigned_cells.count(c)) {
1359 unassigned_cells.erase(c);
1360 next_expand_queue_up.insert(c);
1361 assigned_cells[key].push_back(c);
1362 assigned_cells_reverse[c] = key;
1363 expand_queue.insert(c);
1364 }
1365 }
1366
1367 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1368 expand_queue_up.swap(next_expand_queue_up);
1369 expand_queue_down.swap(next_expand_queue_down);
1370 }
1371 }
1372
1373 while (!expand_queue.empty())
1374 {
1375 RTLIL::Cell *cell = *expand_queue.begin();
1376 clkdomain_t key = assigned_cells_reverse.at(cell);
1377 expand_queue.erase(cell);
1378
1379 for (auto bit : cell_to_bit.at(cell)) {
1380 for (auto c : bit_to_cell[bit])
1381 if (unassigned_cells.count(c)) {
1382 unassigned_cells.erase(c);
1383 next_expand_queue.insert(c);
1384 assigned_cells[key].push_back(c);
1385 assigned_cells_reverse[c] = key;
1386 }
1387 bit_to_cell[bit].clear();
1388 }
1389
1390 if (expand_queue.empty())
1391 expand_queue.swap(next_expand_queue);
1392 }
1393
1394 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1395 for (auto cell : unassigned_cells) {
1396 assigned_cells[key].push_back(cell);
1397 assigned_cells_reverse[cell] = key;
1398 }
1399
1400 log_header(design, "Summary of detected clock domains:\n");
1401 for (auto &it : assigned_cells)
1402 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1403 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1404 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1405
1406 for (auto &it : assigned_cells) {
1407 clk_polarity = std::get<0>(it.first);
1408 clk_sig = assign_map(std::get<1>(it.first));
1409 en_polarity = std::get<2>(it.first);
1410 en_sig = assign_map(std::get<3>(it.first));
1411 abc9_module(design, mod, script_file, exe_file, liberty_file, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1412 keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode,
1413 box_file, lut_file, wire_delay);
1414 assign_map.set(mod);
1415 }
1416 }
1417
1418 Pass::call(design, "clean");
1419
1420 assign_map.clear();
1421 signal_map.clear();
1422 signal_init.clear();
1423 pi_map.clear();
1424 po_map.clear();
1425
1426 log_pop();
1427 }
1428 } Abc9Pass;
1429
1430 PRIVATE_NAMESPACE_END