Optimise some more
[yosys.git] / passes / techmap / abc9.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * 2019 Eddie Hung <eddie@fpgeh.com>
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 */
20
21 // [[CITE]] ABC
22 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
23 // http://www.eecs.berkeley.edu/~alanmi/abc/
24
25 #define ABC_COMMAND_LUT "&st; &sweep; &scorr; "/*"&dc2; "*/"&retime; &dch -f; &ps -l; &if {W} -v; "/*"&mfs; "*/"&ps -l"
26
27 #define ABC_FAST_COMMAND_LUT "&st; &retime; &if {W}"
28
29 #include "kernel/register.h"
30 #include "kernel/sigtools.h"
31 #include "kernel/celltypes.h"
32 #include "kernel/cost.h"
33 #include "kernel/log.h"
34 #include <stdlib.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <cerrno>
38 #include <sstream>
39 #include <climits>
40
41 #ifndef _WIN32
42 # include <unistd.h>
43 # include <dirent.h>
44 #endif
45
46 #include "frontends/aiger/aigerparse.h"
47
48 #ifdef YOSYS_LINK_ABC
49 extern "C" int Abc_RealMain(int argc, char *argv[]);
50 #endif
51
52 USING_YOSYS_NAMESPACE
53 PRIVATE_NAMESPACE_BEGIN
54
55 bool map_mux4;
56 bool map_mux8;
57 bool map_mux16;
58
59 bool markgroups;
60 int map_autoidx;
61 SigMap assign_map;
62 RTLIL::Module *module;
63 std::map<RTLIL::SigBit, int> signal_map;
64 std::map<RTLIL::SigBit, RTLIL::State> signal_init;
65 pool<std::string> enabled_gates;
66 bool recover_init;
67
68 bool clk_polarity, en_polarity;
69 RTLIL::SigSpec clk_sig, en_sig;
70 dict<int, std::string> pi_map, po_map;
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 const std::vector<RTLIL::Cell*> &cells, bool show_tempdir, bool sop_mode, std::string box_file, std::string lut_file,
244 std::string wire_delay)
245 {
246 module = current_module;
247 map_autoidx = autoidx++;
248
249 signal_map.clear();
250 pi_map.clear();
251 po_map.clear();
252 recover_init = false;
253
254 if (clk_str != "$")
255 {
256 clk_polarity = true;
257 clk_sig = RTLIL::SigSpec();
258
259 en_polarity = true;
260 en_sig = RTLIL::SigSpec();
261 }
262
263 if (!clk_str.empty() && clk_str != "$")
264 {
265 if (clk_str.find(',') != std::string::npos) {
266 int pos = clk_str.find(',');
267 std::string en_str = clk_str.substr(pos+1);
268 clk_str = clk_str.substr(0, pos);
269 if (en_str[0] == '!') {
270 en_polarity = false;
271 en_str = en_str.substr(1);
272 }
273 if (module->wires_.count(RTLIL::escape_id(en_str)) != 0)
274 en_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(en_str)), 0));
275 }
276 if (clk_str[0] == '!') {
277 clk_polarity = false;
278 clk_str = clk_str.substr(1);
279 }
280 if (module->wires_.count(RTLIL::escape_id(clk_str)) != 0)
281 clk_sig = assign_map(RTLIL::SigSpec(module->wires_.at(RTLIL::escape_id(clk_str)), 0));
282 }
283
284 if (dff_mode && clk_sig.empty())
285 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
286
287 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
288 if (!cleanup)
289 tempdir_name[0] = tempdir_name[4] = '_';
290 tempdir_name = make_temp_dir(tempdir_name);
291 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
292 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
293
294 std::string abc_script;
295
296 if (!lut_costs.empty()) {
297 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
298 if (!box_file.empty())
299 abc_script += stringf("read_box -v %s; ", box_file.c_str());
300 }
301 else
302 if (!lut_file.empty()) {
303 abc_script += stringf("read_lut %s; ", lut_file.c_str());
304 if (!box_file.empty())
305 abc_script += stringf("read_box -v %s; ", box_file.c_str());
306 }
307 else
308 log_abort();
309
310 abc_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
311
312 if (!script_file.empty()) {
313 if (script_file[0] == '+') {
314 for (size_t i = 1; i < script_file.size(); i++)
315 if (script_file[i] == '\'')
316 abc_script += "'\\''";
317 else if (script_file[i] == ',')
318 abc_script += " ";
319 else
320 abc_script += script_file[i];
321 } else
322 abc_script += stringf("source %s", script_file.c_str());
323 } else if (!lut_costs.empty() || !lut_file.empty()) {
324 //bool all_luts_cost_same = true;
325 //for (int this_cost : lut_costs)
326 // if (this_cost != lut_costs.front())
327 // all_luts_cost_same = false;
328 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
329 //if (all_luts_cost_same && !fast_mode)
330 // abc_script += "; lutpack {S}";
331 } else
332 log_abort();
333
334 if (script_file.empty() && !delay_target.empty())
335 for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
336 abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
337
338 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
339 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
340
341 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
342 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
343
344 for (size_t pos = abc_script.find("{W}"); pos != std::string::npos; pos = abc_script.find("{W}", pos))
345 abc_script = abc_script.substr(0, pos) + wire_delay + abc_script.substr(pos+3);
346
347 abc_script += stringf("; &write %s/output.aig", tempdir_name.c_str());
348 abc_script = add_echos_to_abc_cmd(abc_script);
349
350 for (size_t i = 0; i+1 < abc_script.size(); i++)
351 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
352 abc_script[i+1] = '\n';
353
354 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
355 fprintf(f, "%s\n", abc_script.c_str());
356 fclose(f);
357
358 if (dff_mode || !clk_str.empty())
359 {
360 if (clk_sig.size() == 0)
361 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
362 else {
363 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
364 if (en_sig.size() != 0)
365 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
366 log("\n");
367 }
368 }
369
370 bool count_output = false;
371 for (auto port_name : module->ports) {
372 RTLIL::Wire *port_wire = module->wire(port_name);
373 log_assert(port_wire);
374 if (port_wire->port_output) {
375 count_output = true;
376 break;
377 }
378 }
379
380 log_push();
381
382 if (count_output)
383 {
384 design->selection_stack.emplace_back(false);
385 RTLIL::Selection& sel = design->selection_stack.back();
386 sel.select(module);
387
388 // Behave as for "abc" where BLIF writer implicitly outputs all undef as zero
389 Pass::call(design, "setundef -zero");
390
391 Pass::call(design, "aigmap");
392
393 handle_loops(design);
394
395 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
396 // count_gates, GetSize(signal_list), count_input, count_output);
397
398 Pass::call(design, stringf("write_xaiger -map %s/input.sym %s/input.xaig; ", tempdir_name.c_str(), tempdir_name.c_str()));
399
400 std::string buffer;
401 std::ifstream ifs;
402 #if 0
403 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
404 ifs.open(buffer);
405 if (ifs.fail())
406 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
407 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
408 log_assert(!design->module("$__abc9__"));
409 {
410 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
411 reader.parse_xaiger();
412 }
413 ifs.close();
414 Pass::call(design, stringf("write_verilog -noexpr -norename %s/%s", tempdir_name.c_str(), "input.v"));
415 design->remove(design->module("$__abc9__"));
416 #endif
417
418 design->selection_stack.pop_back();
419
420 // Now 'unexpose' those wires by undoing
421 // the expose operation -- remove them from PO/PI
422 // and re-connecting them back together
423 for (auto wire : module->wires()) {
424 auto it = wire->attributes.find("\\abc_scc_break");
425 if (it != wire->attributes.end()) {
426 wire->attributes.erase(it);
427 log_assert(wire->port_output);
428 wire->port_output = false;
429 RTLIL::Wire *i_wire = module->wire(wire->name.str() + ".abci");
430 log_assert(i_wire);
431 log_assert(i_wire->port_input);
432 i_wire->port_input = false;
433 module->connect(i_wire, wire);
434 }
435 }
436 module->fixup_ports();
437
438
439 log_header(design, "Executing ABC9.\n");
440
441 if (!lut_costs.empty()) {
442 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
443 f = fopen(buffer.c_str(), "wt");
444 if (f == NULL)
445 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
446 for (int i = 0; i < GetSize(lut_costs); i++)
447 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
448 fclose(f);
449 }
450
451 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
452 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
453
454 #ifndef YOSYS_LINK_ABC
455 abc_output_filter filt(tempdir_name, show_tempdir);
456 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
457 #else
458 // These needs to be mutable, supposedly due to getopt
459 char *abc_argv[5];
460 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
461 abc_argv[0] = strdup(exe_file.c_str());
462 abc_argv[1] = strdup("-s");
463 abc_argv[2] = strdup("-f");
464 abc_argv[3] = strdup(tmp_script_name.c_str());
465 abc_argv[4] = 0;
466 int ret = Abc_RealMain(4, abc_argv);
467 free(abc_argv[0]);
468 free(abc_argv[1]);
469 free(abc_argv[2]);
470 free(abc_argv[3]);
471 #endif
472 if (ret != 0)
473 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
474
475 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
476 ifs.open(buffer);
477 if (ifs.fail())
478 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
479
480 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
481 log_assert(!design->module("$__abc9__"));
482 AigerReader reader(design, ifs, "$__abc9__", "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
483 reader.parse_xaiger();
484 ifs.close();
485
486 #if 0
487 Pass::call(design, stringf("write_verilog -noexpr -norename %s/%s", tempdir_name.c_str(), "output.v"));
488 #endif
489
490 log_header(design, "Re-integrating ABC9 results.\n");
491 RTLIL::Module *mapped_mod = design->module("$__abc9__");
492 if (mapped_mod == NULL)
493 log_error("ABC output file does not contain a module `$__abc9__'.\n");
494
495 pool<RTLIL::SigBit> output_bits;
496 for (auto &it : mapped_mod->wires_) {
497 RTLIL::Wire *w = it.second;
498 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
499 if (markgroups) remap_wire->attributes["\\abcgroup"] = map_autoidx;
500 if (w->port_output) {
501 RTLIL::Wire *wire = module->wire(w->name);
502 log_assert(wire);
503 for (int i = 0; i < GetSize(wire); i++)
504 output_bits.insert({wire, i});
505 }
506 }
507
508 // Remove all AND, NOT, and ABC box instances
509 // in preparation for stitching mapped_mod in
510 dict<IdString, decltype(RTLIL::Cell::parameters)> erased_boxes;
511 for (auto it = module->cells_.begin(); it != module->cells_.end(); ) {
512 RTLIL::Cell* cell = it->second;
513 if (cell->type.in("$_AND_", "$_NOT_")) {
514 it = module->cells_.erase(it);
515 continue;
516 }
517 RTLIL::Module* box_module = design->module(cell->type);
518 if (box_module && box_module->attributes.count("\\abc_box_id")) {
519 erased_boxes.insert(std::make_pair(it->first, std::move(cell->parameters)));
520 it = module->cells_.erase(it);
521 continue;
522 }
523 ++it;
524 }
525 // Do the same for module connections
526 for (auto &it : module->connections_) {
527 auto &signal = it.first;
528 auto bits = signal.bits();
529 for (auto &b : bits)
530 if (output_bits.count(b))
531 b = module->addWire(NEW_ID);
532 signal = std::move(bits);
533 }
534
535 std::map<std::string, int> cell_stats;
536 for (auto c : mapped_mod->cells())
537 {
538 if (c->type == "$_NOT_") {
539 RTLIL::Cell *cell;
540 RTLIL::SigBit a_bit = c->getPort("\\A").as_bit();
541 RTLIL::SigBit y_bit = c->getPort("\\Y").as_bit();
542 if (!a_bit.wire) {
543 c->setPort("\\Y", module->addWire(NEW_ID));
544 RTLIL::Wire *wire = module->wire(remap_name(y_bit.wire->name));
545 log_assert(wire);
546 module->connect(RTLIL::SigBit(wire, y_bit.offset), RTLIL::S1);
547 }
548 else if (!lut_costs.empty() || !lut_file.empty()) {
549 RTLIL::Cell* driving_lut = nullptr;
550 // ABC can return NOT gates that drive POs
551 if (!a_bit.wire->port_input) {
552 // If it's not a NOT gate that that comes from a PI directly,
553 // find the driving LUT and clone that to guarantee that we won't
554 // increase the max logic depth
555 // (TODO: Optimise by not cloning unless will increase depth)
556 RTLIL::IdString driver_name;
557 if (GetSize(a_bit.wire) == 1)
558 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
559 else
560 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
561 driving_lut = mapped_mod->cell(driver_name);
562 }
563
564 if (!driving_lut) {
565 // If a driver couldn't be found (could be from PI,
566 // or from a box) then implement using a LUT
567 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
568 RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset),
569 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
570 1);
571 }
572 else {
573 auto driver_a = driving_lut->getPort("\\A").chunks();
574 for (auto &chunk : driver_a)
575 chunk.wire = module->wires_[remap_name(chunk.wire->name)];
576 RTLIL::Const driver_lut = driving_lut->getParam("\\LUT");
577 for (auto &b : driver_lut.bits) {
578 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
579 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
580 }
581 cell = module->addLut(remap_name(stringf("%s$lut", c->name.c_str())),
582 driver_a,
583 RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset),
584 driver_lut);
585 }
586 }
587 else {
588 cell = module->addCell(remap_name(c->name), "$_NOT_");
589 cell->setPort("\\A", RTLIL::SigBit(module->wires_[remap_name(a_bit.wire->name)], a_bit.offset));
590 cell->setPort("\\Y", RTLIL::SigBit(module->wires_[remap_name(y_bit.wire->name)], y_bit.offset));
591 cell_stats[RTLIL::unescape_id(c->type)]++;
592 }
593 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
594 continue;
595 }
596 cell_stats[RTLIL::unescape_id(c->type)]++;
597
598 if (c->type == "$lut") {
599 if (GetSize(c->getPort("\\A")) == 1 && c->getParam("\\LUT").as_int() == 2) {
600 SigSpec my_a = module->wires_[remap_name(c->getPort("\\A").as_wire()->name)];
601 SigSpec my_y = module->wires_[remap_name(c->getPort("\\Y").as_wire()->name)];
602 module->connect(my_y, my_a);
603 continue;
604 }
605 }
606 else {
607 auto it = erased_boxes.find(c->name);
608 log_assert(it != erased_boxes.end());
609 c->parameters = std::move(it->second);
610 }
611
612 RTLIL::Cell* cell = module->addCell(remap_name(c->name), c->type);
613 if (markgroups) cell->attributes["\\abcgroup"] = map_autoidx;
614 cell->parameters = c->parameters;
615 for (auto &conn : c->connections()) {
616 RTLIL::SigSpec newsig;
617 for (auto c : conn.second.chunks()) {
618 if (c.width == 0)
619 continue;
620 //log_assert(c.width == 1);
621 if (c.wire)
622 c.wire = module->wires_[remap_name(c.wire->name)];
623 newsig.append(c);
624 }
625 cell->setPort(conn.first, newsig);
626 }
627 }
628
629 // Copy connections (and rename) from mapped_mod to module
630 for (auto conn : mapped_mod->connections()) {
631 if (!conn.first.is_fully_const()) {
632 auto chunks = conn.first.chunks();
633 for (auto &c : chunks)
634 c.wire = module->wires_[remap_name(c.wire->name)];
635 conn.first = std::move(chunks);
636 }
637 if (!conn.second.is_fully_const()) {
638 auto chunks = conn.second.chunks();
639 for (auto &c : chunks)
640 if (c.wire)
641 c.wire = module->wires_[remap_name(c.wire->name)];
642 conn.second = std::move(chunks);
643 }
644 module->connect(conn);
645 }
646
647 if (recover_init)
648 for (auto wire : mapped_mod->wires()) {
649 if (wire->attributes.count("\\init")) {
650 Wire *w = module->wires_[remap_name(wire->name)];
651 log_assert(w->attributes.count("\\init") == 0);
652 w->attributes["\\init"] = wire->attributes.at("\\init");
653 }
654 }
655
656 for (auto &it : cell_stats)
657 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
658 int in_wires = 0, out_wires = 0;
659
660 // Stitch in mapped_mod's inputs/outputs into module
661 for (auto &it : mapped_mod->wires_) {
662 RTLIL::Wire *w = it.second;
663 if (!w->port_input && !w->port_output)
664 continue;
665 RTLIL::Wire *wire = module->wire(w->name);
666 log_assert(wire);
667 RTLIL::Wire *remap_wire = module->wire(remap_name(w->name));
668 RTLIL::SigSpec signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
669 log_assert(GetSize(signal) >= GetSize(remap_wire));
670
671 log_assert(w->port_input || w->port_output);
672 RTLIL::SigSig conn;
673 if (w->port_input) {
674 conn.first = remap_wire;
675 conn.second = signal;
676 in_wires++;
677 module->connect(conn);
678 }
679 if (w->port_output) {
680 conn.first = signal;
681 conn.second = remap_wire;
682 out_wires++;
683 module->connect(conn);
684 }
685 }
686
687 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
688 log("ABC RESULTS: input signals: %8d\n", in_wires);
689 log("ABC RESULTS: output signals: %8d\n", out_wires);
690
691 design->remove(mapped_mod);
692 }
693 else
694 {
695 log("Don't call ABC as there is nothing to map.\n");
696 }
697
698 if (cleanup)
699 {
700 log("Removing temp directory.\n");
701 remove_directory(tempdir_name);
702 }
703
704 log_pop();
705 }
706
707 struct Abc9Pass : public Pass {
708 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
709 void help() YS_OVERRIDE
710 {
711 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
712 log("\n");
713 log(" abc9 [options] [selection]\n");
714 log("\n");
715 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
716 log("library to a target architecture.\n");
717 log("\n");
718 log(" -exe <command>\n");
719 #ifdef ABCEXTERNAL
720 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
721 #else
722 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
723 #endif
724 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
725 log("\n");
726 log(" -script <file>\n");
727 log(" use the specified ABC script file instead of the default script.\n");
728 log("\n");
729 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
730 log(" string is interpreted as the command string to be passed to ABC. The\n");
731 log(" leading plus sign is removed and all commas (,) in the string are\n");
732 log(" replaced with blanks before the string is passed to ABC.\n");
733 log("\n");
734 log(" if no -script parameter is given, the following scripts are used:\n");
735 log("\n");
736 log(" for -lut/-luts (only one LUT size):\n");
737 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT /*"; lutpack {S}"*/).c_str());
738 log("\n");
739 log(" for -lut/-luts (different LUT sizes):\n");
740 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
741 log("\n");
742 log(" -fast\n");
743 log(" use different default scripts that are slightly faster (at the cost\n");
744 log(" of output quality):\n");
745 log("\n");
746 log(" for -lut/-luts:\n");
747 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
748 log("\n");
749 // log(" -D <picoseconds>\n");
750 // log(" set delay target. the string {D} in the default scripts above is\n");
751 // log(" replaced by this option when used, and an empty string otherwise.\n");
752 // log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
753 // log(" default scripts above.\n");
754 // log("\n");
755 // log(" -S <num>\n");
756 // log(" maximum number of LUT inputs shared.\n");
757 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
758 // log("\n");
759 log(" -lut <width>\n");
760 log(" generate netlist using luts of (max) the specified width.\n");
761 log("\n");
762 log(" -lut <w1>:<w2>\n");
763 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
764 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
765 log(" the area cost doubles with each additional input bit. the delay cost\n");
766 log(" is still constant for all lut widths.\n");
767 log("\n");
768 log(" -lut <file>\n");
769 log(" pass this file with lut library to ABC.\n");
770 log("\n");
771 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
772 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
773 log(" 2, 3, .. inputs.\n");
774 log("\n");
775 // log(" -dff\n");
776 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
777 // log(" clock domains are automatically partitioned in clock domains and each\n");
778 // log(" domain is passed through ABC independently.\n");
779 // log("\n");
780 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
781 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
782 // log(" cells that belong to the specified clock domain are used.\n");
783 // log("\n");
784 // log(" -keepff\n");
785 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
786 // log(" them, for example for equivalence checking.)\n");
787 // log("\n");
788 log(" -nocleanup\n");
789 log(" when this option is used, the temporary files created by this pass\n");
790 log(" are not removed. this is useful for debugging.\n");
791 log("\n");
792 log(" -showtmp\n");
793 log(" print the temp dir name in log. usually this is suppressed so that the\n");
794 log(" command output is identical across runs.\n");
795 log("\n");
796 log(" -markgroups\n");
797 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
798 log(" this attribute is a unique integer for each ABC process started. This\n");
799 log(" is useful for debugging the partitioning of clock domains.\n");
800 log("\n");
801 log(" -box <file>\n");
802 log(" pass this file with box library to ABC. Use with -lut.\n");
803 log("\n");
804 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
805 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
806 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
807 log("output when passing an ABC script that writes a file. Instead write your full\n");
808 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
809 log("you want to use ABC to convert your design into another format.\n");
810 log("\n");
811 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
812 log("\n");
813 }
814 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
815 {
816 log_header(design, "Executing ABC9 pass (technology mapping using ABC9).\n");
817 log_push();
818
819 assign_map.clear();
820 signal_map.clear();
821 signal_init.clear();
822 pi_map.clear();
823 po_map.clear();
824
825 #ifdef ABCEXTERNAL
826 std::string exe_file = ABCEXTERNAL;
827 #else
828 std::string exe_file = proc_self_dirname() + "yosys-abc";
829 #endif
830 std::string script_file, clk_str, box_file, lut_file;
831 std::string delay_target, lutin_shared = "-S 1", wire_delay;
832 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
833 bool show_tempdir = false, sop_mode = false;
834 vector<int> lut_costs;
835 markgroups = false;
836
837 #if 0
838 cleanup = false;
839 show_tempdir = true;
840 #endif
841
842 map_mux4 = false;
843 map_mux8 = false;
844 map_mux16 = false;
845 enabled_gates.clear();
846
847 #ifdef _WIN32
848 #ifndef ABCEXTERNAL
849 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
850 exe_file = proc_self_dirname() + "..\\yosys-abc";
851 #endif
852 #endif
853
854 size_t argidx;
855 char pwd [PATH_MAX];
856 if (!getcwd(pwd, sizeof(pwd))) {
857 log_cmd_error("getcwd failed: %s\n", strerror(errno));
858 log_abort();
859 }
860 for (argidx = 1; argidx < args.size(); argidx++) {
861 std::string arg = args[argidx];
862 if (arg == "-exe" && argidx+1 < args.size()) {
863 exe_file = args[++argidx];
864 continue;
865 }
866 if (arg == "-script" && argidx+1 < args.size()) {
867 script_file = args[++argidx];
868 rewrite_filename(script_file);
869 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
870 script_file = std::string(pwd) + "/" + script_file;
871 continue;
872 }
873 if (arg == "-D" && argidx+1 < args.size()) {
874 delay_target = "-D " + args[++argidx];
875 continue;
876 }
877 //if (arg == "-S" && argidx+1 < args.size()) {
878 // lutin_shared = "-S " + args[++argidx];
879 // continue;
880 //}
881 if (arg == "-lut" && argidx+1 < args.size()) {
882 string arg = args[++argidx];
883 size_t pos = arg.find_first_of(':');
884 int lut_mode = 0, lut_mode2 = 0;
885 if (pos != string::npos) {
886 lut_mode = atoi(arg.substr(0, pos).c_str());
887 lut_mode2 = atoi(arg.substr(pos+1).c_str());
888 } else {
889 pos = arg.find_first_of('.');
890 if (pos != string::npos) {
891 lut_file = arg;
892 rewrite_filename(lut_file);
893 if (!lut_file.empty() && !is_absolute_path(lut_file))
894 lut_file = std::string(pwd) + "/" + lut_file;
895 }
896 else {
897 lut_mode = atoi(arg.c_str());
898 lut_mode2 = lut_mode;
899 }
900 }
901 lut_costs.clear();
902 for (int i = 0; i < lut_mode; i++)
903 lut_costs.push_back(1);
904 for (int i = lut_mode; i < lut_mode2; i++)
905 lut_costs.push_back(2 << (i - lut_mode));
906 continue;
907 }
908 if (arg == "-luts" && argidx+1 < args.size()) {
909 lut_costs.clear();
910 for (auto &tok : split_tokens(args[++argidx], ",")) {
911 auto parts = split_tokens(tok, ":");
912 if (GetSize(parts) == 0 && !lut_costs.empty())
913 lut_costs.push_back(lut_costs.back());
914 else if (GetSize(parts) == 1)
915 lut_costs.push_back(atoi(parts.at(0).c_str()));
916 else if (GetSize(parts) == 2)
917 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
918 lut_costs.push_back(atoi(parts.at(1).c_str()));
919 else
920 log_cmd_error("Invalid -luts syntax.\n");
921 }
922 continue;
923 }
924 if (arg == "-fast") {
925 fast_mode = true;
926 continue;
927 }
928 //if (arg == "-dff") {
929 // dff_mode = true;
930 // continue;
931 //}
932 //if (arg == "-clk" && argidx+1 < args.size()) {
933 // clk_str = args[++argidx];
934 // dff_mode = true;
935 // continue;
936 //}
937 //if (arg == "-keepff") {
938 // keepff = true;
939 // continue;
940 //}
941 if (arg == "-nocleanup") {
942 cleanup = false;
943 continue;
944 }
945 if (arg == "-showtmp") {
946 show_tempdir = true;
947 continue;
948 }
949 if (arg == "-markgroups") {
950 markgroups = true;
951 continue;
952 }
953 if (arg == "-box" && argidx+1 < args.size()) {
954 box_file = args[++argidx];
955 rewrite_filename(box_file);
956 if (!box_file.empty() && !is_absolute_path(box_file))
957 box_file = std::string(pwd) + "/" + box_file;
958 continue;
959 }
960 if (arg == "-W" && argidx+1 < args.size()) {
961 wire_delay = "-W " + args[++argidx];
962 continue;
963 }
964 break;
965 }
966 extra_args(args, argidx, design);
967
968 for (auto mod : design->selected_modules())
969 {
970 if (mod->attributes.count("\\abc_box_id"))
971 continue;
972
973 if (mod->processes.size() > 0) {
974 log("Skipping module %s as it contains processes.\n", log_id(mod));
975 continue;
976 }
977
978 assign_map.set(mod);
979 signal_init.clear();
980
981 for (Wire *wire : mod->wires())
982 if (wire->attributes.count("\\init")) {
983 SigSpec initsig = assign_map(wire);
984 Const initval = wire->attributes.at("\\init");
985 for (int i = 0; i < GetSize(initsig) && i < GetSize(initval); i++)
986 switch (initval[i]) {
987 case State::S0:
988 signal_init[initsig[i]] = State::S0;
989 break;
990 case State::S1:
991 signal_init[initsig[i]] = State::S0;
992 break;
993 default:
994 break;
995 }
996 }
997
998 if (!dff_mode || !clk_str.empty()) {
999 abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1000 delay_target, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode,
1001 box_file, lut_file, wire_delay);
1002 continue;
1003 }
1004
1005 CellTypes ct(design);
1006
1007 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1008 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1009
1010 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1011 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1012 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1013
1014 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1015 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1016 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1017
1018 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1019 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1020
1021 for (auto cell : all_cells)
1022 {
1023 clkdomain_t key;
1024
1025 for (auto &conn : cell->connections())
1026 for (auto bit : conn.second) {
1027 bit = assign_map(bit);
1028 if (bit.wire != nullptr) {
1029 cell_to_bit[cell].insert(bit);
1030 bit_to_cell[bit].insert(cell);
1031 if (ct.cell_input(cell->type, conn.first)) {
1032 cell_to_bit_up[cell].insert(bit);
1033 bit_to_cell_down[bit].insert(cell);
1034 }
1035 if (ct.cell_output(cell->type, conn.first)) {
1036 cell_to_bit_down[cell].insert(bit);
1037 bit_to_cell_up[bit].insert(cell);
1038 }
1039 }
1040 }
1041
1042 if (cell->type == "$_DFF_N_" || cell->type == "$_DFF_P_")
1043 {
1044 key = clkdomain_t(cell->type == "$_DFF_P_", assign_map(cell->getPort("\\C")), true, RTLIL::SigSpec());
1045 }
1046 else
1047 if (cell->type == "$_DFFE_NN_" || cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_")
1048 {
1049 bool this_clk_pol = cell->type == "$_DFFE_PN_" || cell->type == "$_DFFE_PP_";
1050 bool this_en_pol = cell->type == "$_DFFE_NP_" || cell->type == "$_DFFE_PP_";
1051 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort("\\C")), this_en_pol, assign_map(cell->getPort("\\E")));
1052 }
1053 else
1054 continue;
1055
1056 unassigned_cells.erase(cell);
1057 expand_queue.insert(cell);
1058 expand_queue_up.insert(cell);
1059 expand_queue_down.insert(cell);
1060
1061 assigned_cells[key].push_back(cell);
1062 assigned_cells_reverse[cell] = key;
1063 }
1064
1065 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1066 {
1067 if (!expand_queue_up.empty())
1068 {
1069 RTLIL::Cell *cell = *expand_queue_up.begin();
1070 clkdomain_t key = assigned_cells_reverse.at(cell);
1071 expand_queue_up.erase(cell);
1072
1073 for (auto bit : cell_to_bit_up[cell])
1074 for (auto c : bit_to_cell_up[bit])
1075 if (unassigned_cells.count(c)) {
1076 unassigned_cells.erase(c);
1077 next_expand_queue_up.insert(c);
1078 assigned_cells[key].push_back(c);
1079 assigned_cells_reverse[c] = key;
1080 expand_queue.insert(c);
1081 }
1082 }
1083
1084 if (!expand_queue_down.empty())
1085 {
1086 RTLIL::Cell *cell = *expand_queue_down.begin();
1087 clkdomain_t key = assigned_cells_reverse.at(cell);
1088 expand_queue_down.erase(cell);
1089
1090 for (auto bit : cell_to_bit_down[cell])
1091 for (auto c : bit_to_cell_down[bit])
1092 if (unassigned_cells.count(c)) {
1093 unassigned_cells.erase(c);
1094 next_expand_queue_up.insert(c);
1095 assigned_cells[key].push_back(c);
1096 assigned_cells_reverse[c] = key;
1097 expand_queue.insert(c);
1098 }
1099 }
1100
1101 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1102 expand_queue_up.swap(next_expand_queue_up);
1103 expand_queue_down.swap(next_expand_queue_down);
1104 }
1105 }
1106
1107 while (!expand_queue.empty())
1108 {
1109 RTLIL::Cell *cell = *expand_queue.begin();
1110 clkdomain_t key = assigned_cells_reverse.at(cell);
1111 expand_queue.erase(cell);
1112
1113 for (auto bit : cell_to_bit.at(cell)) {
1114 for (auto c : bit_to_cell[bit])
1115 if (unassigned_cells.count(c)) {
1116 unassigned_cells.erase(c);
1117 next_expand_queue.insert(c);
1118 assigned_cells[key].push_back(c);
1119 assigned_cells_reverse[c] = key;
1120 }
1121 bit_to_cell[bit].clear();
1122 }
1123
1124 if (expand_queue.empty())
1125 expand_queue.swap(next_expand_queue);
1126 }
1127
1128 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1129 for (auto cell : unassigned_cells) {
1130 assigned_cells[key].push_back(cell);
1131 assigned_cells_reverse[cell] = key;
1132 }
1133
1134 log_header(design, "Summary of detected clock domains:\n");
1135 for (auto &it : assigned_cells)
1136 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
1137 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
1138 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
1139
1140 for (auto &it : assigned_cells) {
1141 clk_polarity = std::get<0>(it.first);
1142 clk_sig = assign_map(std::get<1>(it.first));
1143 en_polarity = std::get<2>(it.first);
1144 en_sig = assign_map(std::get<3>(it.first));
1145 abc9_module(design, mod, script_file, exe_file, cleanup, lut_costs, !clk_sig.empty(), "$",
1146 keepff, delay_target, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode,
1147 box_file, lut_file, wire_delay);
1148 assign_map.set(mod);
1149 }
1150 }
1151
1152 Pass::call(design, "clean");
1153
1154 assign_map.clear();
1155 signal_map.clear();
1156 signal_init.clear();
1157 pi_map.clear();
1158 po_map.clear();
1159
1160 log_pop();
1161 }
1162 } Abc9Pass;
1163
1164 PRIVATE_NAMESPACE_END