6fdf987f0b4529077bdcad20718b926d7a25b068
[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 #if 0
26 // Based on &flow3 - better QoR but more experimental
27 #define ABC_COMMAND_LUT "&st; &ps -l; &sweep -v; &scorr; " \
28 "&st; &if {W}; &save; &st; &syn2; &if {W} -v; &save; &load; "\
29 "&st; &if -g -K 6; &dch -f; &if {W} -v; &save; &load; "\
30 "&st; &if -g -K 6; &synch2; &if {W} -v; &save; &load; "\
31 "&mfs; &ps -l"
32 #else
33 #define ABC_COMMAND_LUT "&st; &scorr; &sweep; &dc2; &st; &dch -f; &ps; &if {W} {D} -v; &mfs; &ps -l"
34 #endif
35
36
37 #define ABC_FAST_COMMAND_LUT "&st; &if {W} {D}"
38
39 #include "kernel/register.h"
40 #include "kernel/sigtools.h"
41 #include "kernel/celltypes.h"
42 #include "kernel/cost.h"
43 #include "kernel/log.h"
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <cerrno>
48 #include <sstream>
49 #include <climits>
50
51 #ifndef _WIN32
52 # include <unistd.h>
53 # include <dirent.h>
54 #endif
55
56 #include "frontends/aiger/aigerparse.h"
57 #include "kernel/utils.h"
58
59 #ifdef YOSYS_LINK_ABC
60 extern "C" int Abc_RealMain(int argc, char *argv[]);
61 #endif
62
63 USING_YOSYS_NAMESPACE
64 PRIVATE_NAMESPACE_BEGIN
65
66 bool markgroups;
67 int map_autoidx;
68 SigMap assign_map;
69 RTLIL::Module *module;
70
71 bool clk_polarity, en_polarity;
72 RTLIL::SigSpec clk_sig, en_sig;
73
74 inline std::string remap_name(RTLIL::IdString abc_name)
75 {
76 return stringf("$abc$%d$%s", map_autoidx, abc_name.c_str()+1);
77 }
78
79 void handle_loops(RTLIL::Design *design,
80 const dict<IdString,pool<IdString>> &scc_break_inputs)
81 {
82 Pass::call(design, "scc -set_attr abc_scc_id {}");
83
84 // For every unique SCC found, (arbitrarily) find the first
85 // cell in the component, and select (and mark) all its output
86 // wires
87 pool<RTLIL::Const> ids_seen;
88 for (auto cell : module->cells()) {
89 auto it = cell->attributes.find(ID(abc_scc_id));
90 if (it != cell->attributes.end()) {
91 auto r = ids_seen.insert(it->second);
92 if (r.second) {
93 for (auto &c : cell->connections_) {
94 if (c.second.is_fully_const()) continue;
95 if (cell->output(c.first)) {
96 SigBit b = c.second.as_bit();
97 Wire *w = b.wire;
98 log_assert(!w->port_input);
99 w->port_input = true;
100 w = module->wire(stringf("%s.abci", w->name.c_str()));
101 if (!w) {
102 w = module->addWire(stringf("%s.abci", b.wire->name.c_str()), GetSize(b.wire));
103 w->port_output = true;
104 }
105 else {
106 log_assert(w->port_input);
107 log_assert(b.offset < GetSize(w));
108 }
109 w->set_bool_attribute(ID(abc_scc_break));
110 module->swap_names(b.wire, w);
111 c.second = RTLIL::SigBit(w, b.offset);
112 }
113 }
114 }
115 cell->attributes.erase(it);
116 }
117
118 auto jt = scc_break_inputs.find(cell->type);
119 if (jt != scc_break_inputs.end())
120 for (auto port_name : jt->second) {
121 RTLIL::SigSpec sig;
122 auto &rhs = cell->connections_.at(port_name);
123 for (auto b : rhs) {
124 Wire *w = b.wire;
125 if (!w) continue;
126 w->port_output = true;
127 w->set_bool_attribute(ID(abc_scc_break));
128 w = module->wire(stringf("%s.abci", w->name.c_str()));
129 if (!w) {
130 w = module->addWire(stringf("%s.abci", b.wire->name.c_str()), GetSize(b.wire));
131 w->port_input = true;
132 }
133 else {
134 log_assert(b.offset < GetSize(w));
135 log_assert(w->port_input);
136 }
137 sig.append(RTLIL::SigBit(w, b.offset));
138 }
139 rhs = sig;
140 }
141 }
142
143 module->fixup_ports();
144 }
145
146 std::string add_echos_to_abc_cmd(std::string str)
147 {
148 std::string new_str, token;
149 for (size_t i = 0; i < str.size(); i++) {
150 token += str[i];
151 if (str[i] == ';') {
152 while (i+1 < str.size() && str[i+1] == ' ')
153 i++;
154 new_str += "echo + " + token + " " + token + " ";
155 token.clear();
156 }
157 }
158
159 if (!token.empty()) {
160 if (!new_str.empty())
161 new_str += "echo + " + token + "; ";
162 new_str += token;
163 }
164
165 return new_str;
166 }
167
168 std::string fold_abc_cmd(std::string str)
169 {
170 std::string token, new_str = " ";
171 int char_counter = 10;
172
173 for (size_t i = 0; i <= str.size(); i++) {
174 if (i < str.size())
175 token += str[i];
176 if (i == str.size() || str[i] == ';') {
177 if (char_counter + token.size() > 75)
178 new_str += "\n ", char_counter = 14;
179 new_str += token, char_counter += token.size();
180 token.clear();
181 }
182 }
183
184 return new_str;
185 }
186
187 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
188 {
189 if (show_tempdir)
190 return text;
191
192 while (1) {
193 size_t pos = text.find(tempdir_name);
194 if (pos == std::string::npos)
195 break;
196 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
197 }
198
199 std::string selfdir_name = proc_self_dirname();
200 if (selfdir_name != "/") {
201 while (1) {
202 size_t pos = text.find(selfdir_name);
203 if (pos == std::string::npos)
204 break;
205 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
206 }
207 }
208
209 return text;
210 }
211
212 struct abc_output_filter
213 {
214 bool got_cr;
215 int escape_seq_state;
216 std::string linebuf;
217 std::string tempdir_name;
218 bool show_tempdir;
219
220 abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
221 {
222 got_cr = false;
223 escape_seq_state = 0;
224 }
225
226 void next_char(char ch)
227 {
228 if (escape_seq_state == 0 && ch == '\033') {
229 escape_seq_state = 1;
230 return;
231 }
232 if (escape_seq_state == 1) {
233 escape_seq_state = ch == '[' ? 2 : 0;
234 return;
235 }
236 if (escape_seq_state == 2) {
237 if ((ch < '0' || '9' < ch) && ch != ';')
238 escape_seq_state = 0;
239 return;
240 }
241 escape_seq_state = 0;
242 if (ch == '\r') {
243 got_cr = true;
244 return;
245 }
246 if (ch == '\n') {
247 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
248 got_cr = false, linebuf.clear();
249 return;
250 }
251 if (got_cr)
252 got_cr = false, linebuf.clear();
253 linebuf += ch;
254 }
255
256 void next_line(const std::string &line)
257 {
258 //int pi, po;
259 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
260 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
261 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
262 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
263 // return;
264 //}
265
266 for (char ch : line)
267 next_char(ch);
268 }
269 };
270
271 void abc9_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
272 bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str,
273 bool /*keepff*/, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode,
274 bool show_tempdir, std::string box_file, std::string lut_file,
275 std::string wire_delay, const dict<int,IdString> &box_lookup,
276 const dict<IdString,pool<IdString>> &scc_break_inputs
277 )
278 {
279 module = current_module;
280 map_autoidx = autoidx++;
281
282 if (clk_str != "$")
283 {
284 clk_polarity = true;
285 clk_sig = RTLIL::SigSpec();
286
287 en_polarity = true;
288 en_sig = RTLIL::SigSpec();
289 }
290
291 if (!clk_str.empty() && clk_str != "$")
292 {
293 if (clk_str.find(',') != std::string::npos) {
294 int pos = clk_str.find(',');
295 std::string en_str = clk_str.substr(pos+1);
296 clk_str = clk_str.substr(0, pos);
297 if (en_str[0] == '!') {
298 en_polarity = false;
299 en_str = en_str.substr(1);
300 }
301 if (module->wires_.count(RTLIL::escape_id(en_str)) != 0)
302 en_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(en_str)), 0));
303 }
304 if (clk_str[0] == '!') {
305 clk_polarity = false;
306 clk_str = clk_str.substr(1);
307 }
308 if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
309 clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
310 }
311
312 if (dff_mode && clk_sig.empty())
313 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
314
315 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
316 if (!cleanup)
317 tempdir_name[0] = tempdir_name[4] = '_';
318 tempdir_name = make_temp_dir(tempdir_name);
319 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
320 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
321
322 std::string abc_script;
323
324 if (!lut_costs.empty()) {
325 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
326 if (!box_file.empty())
327 abc_script += stringf("read_box -v %s; ", box_file.c_str());
328 }
329 else
330 if (!lut_file.empty()) {
331 abc_script += stringf("read_lut %s; ", lut_file.c_str());
332 if (!box_file.empty())
333 abc_script += stringf("read_box -v %s; ", box_file.c_str());
334 }
335 else
336 log_abort();
337
338 abc_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
339
340 if (!script_file.empty()) {
341 if (script_file[0] == '+') {
342 for (size_t i = 1; i < script_file.size(); i++)
343 if (script_file[i] == '\'')
344 abc_script += "'\\''";
345 else if (script_file[i] == ',')
346 abc_script += " ";
347 else
348 abc_script += script_file[i];
349 } else
350 abc_script += stringf("source %s", script_file.c_str());
351 } else if (!lut_costs.empty() || !lut_file.empty()) {
352 //bool all_luts_cost_same = true;
353 //for (int this_cost : lut_costs)
354 // if (this_cost != lut_costs.front())
355 // all_luts_cost_same = false;
356 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
357 //if (all_luts_cost_same && !fast_mode)
358 // abc_script += "; lutpack {S}";
359 } else
360 log_abort();
361
362 //if (script_file.empty() && !delay_target.empty())
363 // for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
364 // abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
365
366 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
367 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
368
369 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
370 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
371
372 for (size_t pos = abc_script.find("{W}"); pos != std::string::npos; pos = abc_script.find("{W}", pos))
373 abc_script = abc_script.substr(0, pos) + wire_delay + abc_script.substr(pos+3);
374
375 abc_script += stringf("; &write %s/output.aig", tempdir_name.c_str());
376 abc_script = add_echos_to_abc_cmd(abc_script);
377
378 for (size_t i = 0; i+1 < abc_script.size(); i++)
379 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
380 abc_script[i+1] = '\n';
381
382 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
383 fprintf(f, "%s\n", abc_script.c_str());
384 fclose(f);
385
386 if (dff_mode || !clk_str.empty())
387 {
388 if (clk_sig.size() == 0)
389 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
390 else {
391 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
392 if (en_sig.size() != 0)
393 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
394 log("\n");
395 }
396 }
397
398 bool count_output = false;
399 for (auto port_name : module->ports) {
400 RTLIL::Wire *port_wire = module->wire(port_name);
401 log_assert(port_wire);
402 if (port_wire->port_output) {
403 count_output = true;
404 break;
405 }
406 }
407
408 log_push();
409
410 if (count_output)
411 {
412 design->selection_stack.emplace_back(false);
413 RTLIL::Selection& sel = design->selection_stack.back();
414 sel.select(module);
415
416 handle_loops(design, scc_break_inputs);
417
418 Pass::call(design, "aigmap");
419
420 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
421 // count_gates, GetSize(signal_list), count_input, count_output);
422
423 Pass::call(design, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name.c_str(), tempdir_name.c_str()));
424
425 std::string buffer;
426 std::ifstream ifs;
427 #if 0
428 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
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(ID($__abc9__)));
434 {
435 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
436 reader.parse_xaiger();
437 }
438 ifs.close();
439 Pass::call(design, stringf("write_verilog -noexpr -norename"));
440 design->remove(design->module(ID($__abc9__)));
441 #endif
442
443 design->selection_stack.pop_back();
444
445 // Now 'unexpose' those wires by undoing
446 // the expose operation -- remove them from PO/PI
447 // and re-connecting them back together
448 for (auto wire : module->wires()) {
449 auto it = wire->attributes.find(ID(abc_scc_break));
450 if (it != wire->attributes.end()) {
451 wire->attributes.erase(it);
452 log_assert(wire->port_output);
453 wire->port_output = false;
454 RTLIL::Wire *i_wire = module->wire(wire->name.str() + ".abci");
455 log_assert(i_wire);
456 log_assert(i_wire->port_input);
457 i_wire->port_input = false;
458 module->connect(i_wire, wire);
459 }
460 }
461 module->fixup_ports();
462
463 log_header(design, "Executing ABC9.\n");
464
465 if (!lut_costs.empty()) {
466 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
467 f = fopen(buffer.c_str(), "wt");
468 if (f == NULL)
469 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
470 for (int i = 0; i < GetSize(lut_costs); i++)
471 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
472 fclose(f);
473 }
474
475 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
476 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
477
478 #ifndef YOSYS_LINK_ABC
479 abc_output_filter filt(tempdir_name, show_tempdir);
480 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
481 #else
482 // These needs to be mutable, supposedly due to getopt
483 char *abc_argv[5];
484 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
485 abc_argv[0] = strdup(exe_file.c_str());
486 abc_argv[1] = strdup("-s");
487 abc_argv[2] = strdup("-f");
488 abc_argv[3] = strdup(tmp_script_name.c_str());
489 abc_argv[4] = 0;
490 int ret = Abc_RealMain(4, abc_argv);
491 free(abc_argv[0]);
492 free(abc_argv[1]);
493 free(abc_argv[2]);
494 free(abc_argv[3]);
495 #endif
496 if (ret != 0)
497 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
498
499 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
500 ifs.open(buffer);
501 if (ifs.fail())
502 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
503
504 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
505 log_assert(!design->module(ID($__abc9__)));
506
507 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
508 reader.parse_xaiger(box_lookup);
509 ifs.close();
510
511 #if 0
512 Pass::call(design, stringf("write_verilog -noexpr -norename"));
513 #endif
514
515 log_header(design, "Re-integrating ABC9 results.\n");
516 RTLIL::Module *mapped_mod = design->module(ID($__abc9__));
517 if (mapped_mod == NULL)
518 log_error("ABC output file does not contain a module `$__abc9__'.\n");
519
520 pool<RTLIL::SigBit> output_bits;
521 for (auto &it : mapped_mod->wires_) {
522 RTLIL::Wire *w = it.second;
523 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
524 if (markgroups) remap_wire->attributes[ID(abcgroup)] = map_autoidx;
525 if (w->port_output) {
526 RTLIL::Wire *wire = module->wire(w->name);
527 log_assert(wire);
528 for (int i = 0; i < GetSize(w); i++)
529 output_bits.insert({wire, i});
530 }
531 }
532
533 for (auto &it : module->connections_) {
534 auto &signal = it.first;
535 auto bits = signal.bits();
536 for (auto &b : bits)
537 if (output_bits.count(b))
538 b = module->addWire(NEW_ID);
539 signal = std::move(bits);
540 }
541
542 dict<IdString, bool> abc_box;
543 vector<RTLIL::Cell*> boxes;
544 for (const auto &it : module->cells_) {
545 auto cell = it.second;
546 if (cell->type.in(ID($_AND_), ID($_NOT_))) {
547 module->remove(cell);
548 continue;
549 }
550 auto jt = abc_box.find(cell->type);
551 if (jt == abc_box.end()) {
552 RTLIL::Module* box_module = design->module(cell->type);
553 jt = abc_box.insert(std::make_pair(cell->type, box_module && box_module->attributes.count(ID(abc_box_id)))).first;
554 }
555 if (jt->second)
556 boxes.emplace_back(cell);
557 }
558
559 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
560 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
561 dict<RTLIL::Cell*,RTLIL::Cell*> not2drivers;
562 dict<SigBit, std::vector<RTLIL::Cell*>> bit2sinks;
563
564 std::map<IdString, int> cell_stats;
565 for (auto c : mapped_mod->cells())
566 {
567 toposort.node(c->name);
568
569 RTLIL::Cell *cell = nullptr;
570 if (c->type == ID($_NOT_)) {
571 RTLIL::SigBit a_bit = c->getPort(ID::A);
572 RTLIL::SigBit y_bit = c->getPort(ID::Y);
573 bit_users[a_bit].insert(c->name);
574 bit_drivers[y_bit].insert(c->name);
575
576 if (!a_bit.wire) {
577 c->setPort(ID::Y, module->addWire(NEW_ID));
578 RTLIL::Wire *wire = module->wire(remap_name(y_bit.wire->name));
579 log_assert(wire);
580 module->connect(RTLIL::SigBit(wire, y_bit.offset), State::S1);
581 }
582 else if (!lut_costs.empty() || !lut_file.empty()) {
583 RTLIL::Cell* driver_lut = nullptr;
584 // ABC can return NOT gates that drive POs
585 if (!a_bit.wire->port_input) {
586 // If it's not a NOT gate that that comes from a PI directly,
587 // find the driver LUT and clone that to guarantee that we won't
588 // increase the max logic depth
589 // (TODO: Optimise by not cloning unless will increase depth)
590 RTLIL::IdString driver_name;
591 if (GetSize(a_bit.wire) == 1)
592 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
593 else
594 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
595 driver_lut = mapped_mod->cell(driver_name);
596 }
597
598 if (!driver_lut) {
599 // If a driver couldn't be found (could be from PI or box CI)
600 // then implement using a LUT
601 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
602 RTLIL::SigBit(module->wires_.at(remap_name(a_bit.wire->name)), a_bit.offset),
603 RTLIL::SigBit(module->wires_.at(remap_name(y_bit.wire->name)), y_bit.offset),
604 RTLIL::Const::from_string("01"));
605 bit2sinks[cell->getPort(ID::A)].push_back(cell);
606 cell_stats[ID($lut)]++;
607 }
608 else
609 not2drivers[c] = driver_lut;
610 continue;
611 }
612 else
613 log_abort();
614 if (cell && markgroups) cell->attributes[ID(abcgroup)] = map_autoidx;
615 continue;
616 }
617 cell_stats[c->type]++;
618
619 RTLIL::Cell *existing_cell = nullptr;
620 if (c->type == ID($lut)) {
621 if (GetSize(c->getPort(ID::A)) == 1 && c->getParam(ID(LUT)) == RTLIL::Const::from_string("01")) {
622 SigSpec my_a = module->wires_.at(remap_name(c->getPort(ID::A).as_wire()->name));
623 SigSpec my_y = module->wires_.at(remap_name(c->getPort(ID::Y).as_wire()->name));
624 module->connect(my_y, my_a);
625 if (markgroups) c->attributes[ID(abcgroup)] = map_autoidx;
626 log_abort();
627 continue;
628 }
629 cell = module->addCell(remap_name(c->name), c->type);
630 }
631 else {
632 existing_cell = module->cell(c->name);
633 log_assert(existing_cell);
634 cell = module->addCell(remap_name(c->name), c->type);
635 module->swap_names(cell, existing_cell);
636 }
637
638 if (markgroups) cell->attributes[ID(abcgroup)] = map_autoidx;
639 if (existing_cell) {
640 cell->parameters = existing_cell->parameters;
641 cell->attributes = existing_cell->attributes;
642 }
643 else {
644 cell->parameters = c->parameters;
645 cell->attributes = c->attributes;
646 }
647 for (auto &conn : c->connections()) {
648 RTLIL::SigSpec newsig;
649 for (auto c : conn.second.chunks()) {
650 if (c.width == 0)
651 continue;
652 //log_assert(c.width == 1);
653 if (c.wire)
654 c.wire = module->wires_.at(remap_name(c.wire->name));
655 newsig.append(c);
656 }
657 cell->setPort(conn.first, newsig);
658
659 if (cell->input(conn.first)) {
660 for (auto i : newsig)
661 bit2sinks[i].push_back(cell);
662 for (auto i : conn.second)
663 bit_users[i].insert(c->name);
664 }
665 if (cell->output(conn.first))
666 for (auto i : conn.second)
667 bit_drivers[i].insert(c->name);
668 }
669 }
670
671 for (auto cell : boxes)
672 module->remove(cell);
673
674 // Copy connections (and rename) from mapped_mod to module
675 for (auto conn : mapped_mod->connections()) {
676 if (!conn.first.is_fully_const()) {
677 auto chunks = conn.first.chunks();
678 for (auto &c : chunks)
679 c.wire = module->wires_.at(remap_name(c.wire->name));
680 conn.first = std::move(chunks);
681 }
682 if (!conn.second.is_fully_const()) {
683 auto chunks = conn.second.chunks();
684 for (auto &c : chunks)
685 if (c.wire)
686 c.wire = module->wires_.at(remap_name(c.wire->name));
687 conn.second = std::move(chunks);
688 }
689 module->connect(conn);
690 }
691
692 for (auto &it : cell_stats)
693 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
694 int in_wires = 0, out_wires = 0;
695
696 // Stitch in mapped_mod's inputs/outputs into module
697 for (auto port : mapped_mod->ports) {
698 RTLIL::Wire *w = mapped_mod->wire(port);
699 RTLIL::Wire *wire = module->wire(port);
700 log_assert(wire);
701 RTLIL::Wire *remap_wire = module->wire(remap_name(port));
702 RTLIL::SigSpec signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
703 log_assert(GetSize(signal) >= GetSize(remap_wire));
704
705 RTLIL::SigSig conn;
706 if (w->port_output) {
707 conn.first = signal;
708 conn.second = remap_wire;
709 out_wires++;
710 module->connect(conn);
711 }
712 else if (w->port_input) {
713 conn.first = remap_wire;
714 conn.second = signal;
715 in_wires++;
716 module->connect(conn);
717 }
718 }
719
720 for (auto &it : bit_users)
721 if (bit_drivers.count(it.first))
722 for (auto driver_cell : bit_drivers.at(it.first))
723 for (auto user_cell : it.second)
724 toposort.edge(driver_cell, user_cell);
725 bool no_loops YS_ATTRIBUTE(unused) = toposort.sort();
726 log_assert(no_loops);
727
728 for (auto ii = toposort.sorted.rbegin(); ii != toposort.sorted.rend(); ii++) {
729 RTLIL::Cell *not_cell = mapped_mod->cell(*ii);
730 log_assert(not_cell);
731 if (not_cell->type != ID($_NOT_))
732 continue;
733 auto it = not2drivers.find(not_cell);
734 if (it == not2drivers.end())
735 continue;
736 RTLIL::Cell *driver_lut = it->second;
737 RTLIL::SigBit a_bit = not_cell->getPort(ID::A);
738 RTLIL::SigBit y_bit = not_cell->getPort(ID::Y);
739 RTLIL::Const driver_mask;
740
741 a_bit.wire = module->wires_.at(remap_name(a_bit.wire->name));
742 y_bit.wire = module->wires_.at(remap_name(y_bit.wire->name));
743
744 auto jt = bit2sinks.find(a_bit);
745 if (jt == bit2sinks.end())
746 goto clone_lut;
747
748 for (auto sink_cell : jt->second)
749 if (sink_cell->type != ID($lut))
750 goto clone_lut;
751
752 // Push downstream LUTs past inverter
753 for (auto sink_cell : jt->second) {
754 SigSpec A = sink_cell->getPort(ID::A);
755 RTLIL::Const mask = sink_cell->getParam(ID(LUT));
756 int index = 0;
757 for (; index < GetSize(A); index++)
758 if (A[index] == a_bit)
759 break;
760 log_assert(index < GetSize(A));
761 int i = 0;
762 while (i < GetSize(mask)) {
763 for (int j = 0; j < (1 << index); j++)
764 std::swap(mask[i+j], mask[i+j+(1 << index)]);
765 i += 1 << (index+1);
766 }
767 A[index] = y_bit;
768 sink_cell->setPort(ID::A, A);
769 sink_cell->setParam(ID(LUT), mask);
770 }
771
772 // Since we have rewritten all sinks (which we know
773 // to be only LUTs) to be after the inverter, we can
774 // go ahead and clone the LUT with the expectation
775 // that the original driving LUT will become dangling
776 // and get cleaned away
777 clone_lut:
778 driver_mask = driver_lut->getParam(ID(LUT));
779 for (auto &b : driver_mask.bits) {
780 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
781 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
782 }
783 auto cell = module->addLut(NEW_ID,
784 driver_lut->getPort(ID::A),
785 y_bit,
786 driver_mask);
787 for (auto &bit : cell->connections_.at(ID::A)) {
788 bit.wire = module->wires_.at(remap_name(bit.wire->name));
789 bit2sinks[bit].push_back(cell);
790 }
791 }
792
793 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
794 log("ABC RESULTS: input signals: %8d\n", in_wires);
795 log("ABC RESULTS: output signals: %8d\n", out_wires);
796
797 design->remove(mapped_mod);
798 }
799 else
800 {
801 log("Don't call ABC as there is nothing to map.\n");
802 }
803
804 if (cleanup)
805 {
806 log("Removing temp directory.\n");
807 remove_directory(tempdir_name);
808 }
809
810 log_pop();
811 }
812
813 struct Abc9Pass : public Pass {
814 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
815 void help() YS_OVERRIDE
816 {
817 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
818 log("\n");
819 log(" abc9 [options] [selection]\n");
820 log("\n");
821 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
822 log("library to a target architecture.\n");
823 log("\n");
824 log(" -exe <command>\n");
825 #ifdef ABCEXTERNAL
826 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
827 #else
828 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
829 #endif
830 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
831 log("\n");
832 log(" -script <file>\n");
833 log(" use the specified ABC script file instead of the default script.\n");
834 log("\n");
835 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
836 log(" string is interpreted as the command string to be passed to ABC. The\n");
837 log(" leading plus sign is removed and all commas (,) in the string are\n");
838 log(" replaced with blanks before the string is passed to ABC.\n");
839 log("\n");
840 log(" if no -script parameter is given, the following scripts are used:\n");
841 log("\n");
842 log(" for -lut/-luts (only one LUT size):\n");
843 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT /*"; lutpack {S}"*/).c_str());
844 log("\n");
845 log(" for -lut/-luts (different LUT sizes):\n");
846 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
847 log("\n");
848 log(" -fast\n");
849 log(" use different default scripts that are slightly faster (at the cost\n");
850 log(" of output quality):\n");
851 log("\n");
852 log(" for -lut/-luts:\n");
853 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
854 log("\n");
855 log(" -D <picoseconds>\n");
856 log(" set delay target. the string {D} in the default scripts above is\n");
857 log(" replaced by this option when used, and an empty string otherwise\n");
858 log(" (indicating best possible delay).\n");
859 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
860 // log(" default scripts above.\n");
861 log("\n");
862 // log(" -S <num>\n");
863 // log(" maximum number of LUT inputs shared.\n");
864 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
865 // log("\n");
866 log(" -lut <width>\n");
867 log(" generate netlist using luts of (max) the specified width.\n");
868 log("\n");
869 log(" -lut <w1>:<w2>\n");
870 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
871 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
872 log(" the area cost doubles with each additional input bit. the delay cost\n");
873 log(" is still constant for all lut widths.\n");
874 log("\n");
875 log(" -lut <file>\n");
876 log(" pass this file with lut library to ABC.\n");
877 log("\n");
878 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
879 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
880 log(" 2, 3, .. inputs.\n");
881 log("\n");
882 // log(" -dff\n");
883 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
884 // log(" clock domains are automatically partitioned in clock domains and each\n");
885 // log(" domain is passed through ABC independently.\n");
886 // log("\n");
887 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
888 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
889 // log(" cells that belong to the specified clock domain are used.\n");
890 // log("\n");
891 // log(" -keepff\n");
892 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
893 // log(" them, for example for equivalence checking.)\n");
894 // log("\n");
895 log(" -nocleanup\n");
896 log(" when this option is used, the temporary files created by this pass\n");
897 log(" are not removed. this is useful for debugging.\n");
898 log("\n");
899 log(" -showtmp\n");
900 log(" print the temp dir name in log. usually this is suppressed so that the\n");
901 log(" command output is identical across runs.\n");
902 log("\n");
903 log(" -markgroups\n");
904 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
905 log(" this attribute is a unique integer for each ABC process started. This\n");
906 log(" is useful for debugging the partitioning of clock domains.\n");
907 log("\n");
908 log(" -box <file>\n");
909 log(" pass this file with box library to ABC. Use with -lut.\n");
910 log("\n");
911 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
912 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
913 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
914 log("output when passing an ABC script that writes a file. Instead write your full\n");
915 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
916 log("you want to use ABC to convert your design into another format.\n");
917 log("\n");
918 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
919 log("\n");
920 }
921 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
922 {
923 log_header(design, "Executing ABC9 pass (technology mapping using ABC9).\n");
924 log_push();
925
926 assign_map.clear();
927
928 #ifdef ABCEXTERNAL
929 std::string exe_file = ABCEXTERNAL;
930 #else
931 std::string exe_file = proc_self_dirname() + "yosys-abc";
932 #endif
933 std::string script_file, clk_str, box_file, lut_file;
934 std::string delay_target, lutin_shared = "-S 1", wire_delay;
935 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
936 bool show_tempdir = false;
937 vector<int> lut_costs;
938 markgroups = false;
939
940 #if 0
941 cleanup = false;
942 show_tempdir = true;
943 #endif
944
945 #ifdef _WIN32
946 #ifndef ABCEXTERNAL
947 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
948 exe_file = proc_self_dirname() + "..\\yosys-abc";
949 #endif
950 #endif
951
952 size_t argidx;
953 char pwd [PATH_MAX];
954 if (!getcwd(pwd, sizeof(pwd))) {
955 log_cmd_error("getcwd failed: %s\n", strerror(errno));
956 log_abort();
957 }
958 for (argidx = 1; argidx < args.size(); argidx++) {
959 std::string arg = args[argidx];
960 if (arg == "-exe" && argidx+1 < args.size()) {
961 exe_file = args[++argidx];
962 continue;
963 }
964 if (arg == "-script" && argidx+1 < args.size()) {
965 script_file = args[++argidx];
966 rewrite_filename(script_file);
967 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
968 script_file = std::string(pwd) + "/" + script_file;
969 continue;
970 }
971 if (arg == "-D" && argidx+1 < args.size()) {
972 delay_target = "-D " + args[++argidx];
973 continue;
974 }
975 //if (arg == "-S" && argidx+1 < args.size()) {
976 // lutin_shared = "-S " + args[++argidx];
977 // continue;
978 //}
979 if (arg == "-lut" && argidx+1 < args.size()) {
980 string arg = args[++argidx];
981 size_t pos = arg.find_first_of(':');
982 int lut_mode = 0, lut_mode2 = 0;
983 if (pos != string::npos) {
984 lut_mode = atoi(arg.substr(0, pos).c_str());
985 lut_mode2 = atoi(arg.substr(pos+1).c_str());
986 } else {
987 pos = arg.find_first_of('.');
988 if (pos != string::npos) {
989 lut_file = arg;
990 rewrite_filename(lut_file);
991 if (!lut_file.empty() && !is_absolute_path(lut_file))
992 lut_file = std::string(pwd) + "/" + lut_file;
993 }
994 else {
995 lut_mode = atoi(arg.c_str());
996 lut_mode2 = lut_mode;
997 }
998 }
999 lut_costs.clear();
1000 for (int i = 0; i < lut_mode; i++)
1001 lut_costs.push_back(1);
1002 for (int i = lut_mode; i < lut_mode2; i++)
1003 lut_costs.push_back(2 << (i - lut_mode));
1004 continue;
1005 }
1006 if (arg == "-luts" && argidx+1 < args.size()) {
1007 lut_costs.clear();
1008 for (auto &tok : split_tokens(args[++argidx], ",")) {
1009 auto parts = split_tokens(tok, ":");
1010 if (GetSize(parts) == 0 && !lut_costs.empty())
1011 lut_costs.push_back(lut_costs.back());
1012 else if (GetSize(parts) == 1)
1013 lut_costs.push_back(atoi(parts.at(0).c_str()));
1014 else if (GetSize(parts) == 2)
1015 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
1016 lut_costs.push_back(atoi(parts.at(1).c_str()));
1017 else
1018 log_cmd_error("Invalid -luts syntax.\n");
1019 }
1020 continue;
1021 }
1022 if (arg == "-fast") {
1023 fast_mode = true;
1024 continue;
1025 }
1026 //if (arg == "-dff") {
1027 // dff_mode = true;
1028 // continue;
1029 //}
1030 //if (arg == "-clk" && argidx+1 < args.size()) {
1031 // clk_str = args[++argidx];
1032 // dff_mode = true;
1033 // continue;
1034 //}
1035 //if (arg == "-keepff") {
1036 // keepff = true;
1037 // continue;
1038 //}
1039 if (arg == "-nocleanup") {
1040 cleanup = false;
1041 continue;
1042 }
1043 if (arg == "-showtmp") {
1044 show_tempdir = true;
1045 continue;
1046 }
1047 if (arg == "-markgroups") {
1048 markgroups = true;
1049 continue;
1050 }
1051 if (arg == "-box" && argidx+1 < args.size()) {
1052 box_file = args[++argidx];
1053 rewrite_filename(box_file);
1054 if (!box_file.empty() && !is_absolute_path(box_file))
1055 box_file = std::string(pwd) + "/" + box_file;
1056 continue;
1057 }
1058 if (arg == "-W" && argidx+1 < args.size()) {
1059 wire_delay = "-W " + args[++argidx];
1060 continue;
1061 }
1062 break;
1063 }
1064 extra_args(args, argidx, design);
1065
1066 dict<int,IdString> box_lookup;
1067 dict<IdString,pool<IdString>> scc_break_inputs;
1068 for (auto m : design->modules()) {
1069 auto it = m->attributes.find(ID(abc_box_id));
1070 if (it == m->attributes.end())
1071 continue;
1072 if (m->name.begins_with("$paramod"))
1073 continue;
1074 auto id = it->second.as_int();
1075 auto r = box_lookup.insert(std::make_pair(id, m->name));
1076 if (!r.second)
1077 log_error("Module '%s' has the same abc_box_id = %d value as '%s'.\n",
1078 log_id(m), id, log_id(r.first->second));
1079 log_assert(r.second);
1080
1081 RTLIL::Wire *carry_in = nullptr, *carry_out = nullptr;
1082 for (auto p : m->ports) {
1083 auto w = m->wire(p);
1084 log_assert(w);
1085 if (w->port_input) {
1086 if (w->attributes.count(ID(abc_scc_break)))
1087 scc_break_inputs[m->name].insert(p);
1088 if (w->attributes.count(ID(abc_carry))) {
1089 if (carry_in)
1090 log_error("Module '%s' contains more than one 'abc_carry' input port.\n", log_id(m));
1091 carry_in = w;
1092 }
1093 }
1094 if (w->port_output) {
1095 if (w->attributes.count(ID(abc_carry))) {
1096 if (carry_out)
1097 log_error("Module '%s' contains more than one 'abc_carry' input port.\n", log_id(m));
1098 carry_out = w;
1099 }
1100 }
1101 }
1102 if (carry_in || carry_out) {
1103 if (carry_in && !carry_out)
1104 log_error("Module '%s' contains an 'abc_carry' input port but no output port.\n", log_id(m));
1105 if (!carry_in && carry_out)
1106 log_error("Module '%s' contains an 'abc_carry' output port but no input port.\n", log_id(m));
1107 // Make carry_in the last PI, and carry_out the last PO
1108 // since ABC requires it this way
1109 auto &ports = m->ports;
1110 for (auto it = ports.begin(); it != ports.end(); ) {
1111 RTLIL::Wire* w = m->wire(*it);
1112 log_assert(w);
1113 if (w == carry_in || w == carry_out) {
1114 it = ports.erase(it);
1115 continue;
1116 }
1117 if (w->port_id > carry_in->port_id)
1118 --w->port_id;
1119 if (w->port_id > carry_out->port_id)
1120 --w->port_id;
1121 log_assert(w->port_input || w->port_output);
1122 log_assert(ports[w->port_id-1] == w->name);
1123 ++it;
1124 }
1125 ports.push_back(carry_in->name);
1126 carry_in->port_id = ports.size();
1127 ports.push_back(carry_out->name);
1128 carry_out->port_id = ports.size();
1129 }
1130 }
1131
1132 for (auto mod : design->selected_modules())
1133 {
1134 if (mod->attributes.count(ID(abc_box_id)))
1135 continue;
1136
1137 if (mod->processes.size() > 0) {
1138 log("Skipping module %s as it contains processes.\n", log_id(mod));
1139 continue;
1140 }
1141
1142 assign_map.set(mod);
1143
1144 if (!dff_mode || !clk_str.empty()) {
1145 abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1146 delay_target, lutin_shared, fast_mode, show_tempdir,
1147 box_file, lut_file, wire_delay, box_lookup, scc_break_inputs);
1148 continue;
1149 }
1150
1151 CellTypes ct(design);
1152
1153 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1154 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1155
1156 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1157 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1158 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1159
1160 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1161 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1162 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1163
1164 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1165 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1166
1167 for (auto cell : all_cells)
1168 {
1169 clkdomain_t key;
1170
1171 for (auto &conn : cell->connections())
1172 for (auto bit : conn.second) {
1173 bit = assign_map(bit);
1174 if (bit.wire != nullptr) {
1175 cell_to_bit[cell].insert(bit);
1176 bit_to_cell[bit].insert(cell);
1177 if (ct.cell_input(cell->type, conn.first)) {
1178 cell_to_bit_up[cell].insert(bit);
1179 bit_to_cell_down[bit].insert(cell);
1180 }
1181 if (ct.cell_output(cell->type, conn.first)) {
1182 cell_to_bit_down[cell].insert(bit);
1183 bit_to_cell_up[bit].insert(cell);
1184 }
1185 }
1186 }
1187
1188 if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_)))
1189 {
1190 key = clkdomain_t(cell->type == ID($_DFF_P_), assign_map(cell->getPort(ID(C))), true, RTLIL::SigSpec());
1191 }
1192 else
1193 if (cell->type.in(ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
1194 {
1195 bool this_clk_pol = cell->type.in(ID($_DFFE_PN_), ID($_DFFE_PP_));
1196 bool this_en_pol = cell->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_));
1197 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort(ID(C))), this_en_pol, assign_map(cell->getPort(ID(E))));
1198 }
1199 else
1200 continue;
1201
1202 unassigned_cells.erase(cell);
1203 expand_queue.insert(cell);
1204 expand_queue_up.insert(cell);
1205 expand_queue_down.insert(cell);
1206
1207 assigned_cells[key].push_back(cell);
1208 assigned_cells_reverse[cell] = key;
1209 }
1210
1211 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1212 {
1213 if (!expand_queue_up.empty())
1214 {
1215 RTLIL::Cell *cell = *expand_queue_up.begin();
1216 clkdomain_t key = assigned_cells_reverse.at(cell);
1217 expand_queue_up.erase(cell);
1218
1219 for (auto bit : cell_to_bit_up[cell])
1220 for (auto c : bit_to_cell_up[bit])
1221 if (unassigned_cells.count(c)) {
1222 unassigned_cells.erase(c);
1223 next_expand_queue_up.insert(c);
1224 assigned_cells[key].push_back(c);
1225 assigned_cells_reverse[c] = key;
1226 expand_queue.insert(c);
1227 }
1228 }
1229
1230 if (!expand_queue_down.empty())
1231 {
1232 RTLIL::Cell *cell = *expand_queue_down.begin();
1233 clkdomain_t key = assigned_cells_reverse.at(cell);
1234 expand_queue_down.erase(cell);
1235
1236 for (auto bit : cell_to_bit_down[cell])
1237 for (auto c : bit_to_cell_down[bit])
1238 if (unassigned_cells.count(c)) {
1239 unassigned_cells.erase(c);
1240 next_expand_queue_up.insert(c);
1241 assigned_cells[key].push_back(c);
1242 assigned_cells_reverse[c] = key;
1243 expand_queue.insert(c);
1244 }
1245 }
1246
1247 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1248 expand_queue_up.swap(next_expand_queue_up);
1249 expand_queue_down.swap(next_expand_queue_down);
1250 }
1251 }
1252
1253 while (!expand_queue.empty())
1254 {
1255 RTLIL::Cell *cell = *expand_queue.begin();
1256 clkdomain_t key = assigned_cells_reverse.at(cell);
1257 expand_queue.erase(cell);
1258
1259 for (auto bit : cell_to_bit.at(cell)) {
1260 for (auto c : bit_to_cell[bit])
1261 if (unassigned_cells.count(c)) {
1262 unassigned_cells.erase(c);
1263 next_expand_queue.insert(c);
1264 assigned_cells[key].push_back(c);
1265 assigned_cells_reverse[c] = key;
1266 }
1267 bit_to_cell[bit].clear();
1268 }
1269
1270 if (expand_queue.empty())
1271 expand_queue.swap(next_expand_queue);
1272 }
1273
1274 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1275 for (auto cell : unassigned_cells) {
1276 assigned_cells[key].push_back(cell);
1277 assigned_cells_reverse[cell] = key;
1278 }
1279
1280 log_header(design, "Summary of detected clock domains:\n");
1281 for (auto &it : assigned_cells)
1282 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1283 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1284 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1285
1286 for (auto &it : assigned_cells) {
1287 clk_polarity = std::get<0>(it.first);
1288 clk_sig = assign_map(std::get<1>(it.first));
1289 en_polarity = std::get<2>(it.first);
1290 en_sig = assign_map(std::get<3>(it.first));
1291 abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1292 keepff, delay_target, lutin_shared, fast_mode, show_tempdir,
1293 box_file, lut_file, wire_delay, box_lookup, scc_break_inputs);
1294 assign_map.set(mod);
1295 }
1296 }
1297
1298 assign_map.clear();
1299
1300 log_pop();
1301 }
1302 } Abc9Pass;
1303
1304 PRIVATE_NAMESPACE_END