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