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