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