Add assertion
[yosys.git] / passes / techmap / abc9.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * 2019 Eddie Hung <eddie@fpgeh.com>
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 */
20
21 // [[CITE]] ABC
22 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
23 // http://www.eecs.berkeley.edu/~alanmi/abc/
24
25 #if 0
26 // Based on &flow3 - better QoR but more experimental
27 #define ABC_COMMAND_LUT "&st; &ps -l; &sweep -v; &scorr; " \
28 "&st; &if {W}; &save; &st; &syn2; &if {W} -v; &save; &load; "\
29 "&st; &if -g -K 6; &dch -f; &if {W} -v; &save; &load; "\
30 "&st; &if -g -K 6; &synch2; &if {W} -v; &save; &load; "\
31 "&mfs; &ps -l"
32 #else
33 #define ABC_COMMAND_LUT "&st; &scorr; &sweep; &dc2; &st; &dch -f; &ps; &if {W} {D} -v; &mfs; &ps -l; time"
34 #endif
35
36
37 #define ABC_FAST_COMMAND_LUT "&st; &if {W} {D}"
38
39 #include "kernel/register.h"
40 #include "kernel/sigtools.h"
41 #include "kernel/celltypes.h"
42 #include "kernel/cost.h"
43 #include "kernel/log.h"
44 #include <stdlib.h>
45 #include <stdio.h>
46 #include <string.h>
47 #include <cerrno>
48 #include <sstream>
49 #include <climits>
50
51 #ifndef _WIN32
52 # include <unistd.h>
53 # include <dirent.h>
54 #endif
55
56 #include "frontends/aiger/aigerparse.h"
57 #include "kernel/utils.h"
58
59 #ifdef YOSYS_LINK_ABC
60 extern "C" int Abc_RealMain(int argc, char *argv[]);
61 #endif
62
63 USING_YOSYS_NAMESPACE
64 PRIVATE_NAMESPACE_BEGIN
65
66 bool markgroups;
67 int map_autoidx;
68
69 inline std::string remap_name(RTLIL::IdString abc9_name)
70 {
71 return stringf("$abc$%d$%s", map_autoidx, abc9_name.c_str()+1);
72 }
73
74 void handle_loops(RTLIL::Design *design, RTLIL::Module *module)
75 {
76 Pass::call(design, "scc -set_attr abc9_scc_id {} % w:*");
77
78 // For every unique SCC found, (arbitrarily) find the first
79 // cell in the component, and select (and mark) all its output
80 // wires
81 pool<RTLIL::Const> ids_seen;
82 for (auto cell : module->cells()) {
83 auto it = cell->attributes.find(ID(abc9_scc_id));
84 if (it != cell->attributes.end()) {
85 auto r = ids_seen.insert(it->second);
86 if (r.second) {
87 for (auto &c : cell->connections_) {
88 if (c.second.is_fully_const()) continue;
89 if (cell->output(c.first)) {
90 SigBit b = c.second.as_bit();
91 Wire *w = b.wire;
92 log_assert(!w->port_input);
93 w->port_input = true;
94 w = module->wire(stringf("%s.abci", w->name.c_str()));
95 if (!w) {
96 w = module->addWire(stringf("%s.abci", b.wire->name.c_str()), GetSize(b.wire));
97 w->port_output = true;
98 }
99 else {
100 log_assert(w->port_input);
101 log_assert(b.offset < GetSize(w));
102 }
103 w->set_bool_attribute(ID(abc9_scc_break));
104 module->swap_names(b.wire, w);
105 c.second = RTLIL::SigBit(w, b.offset);
106 }
107 }
108 }
109 cell->attributes.erase(it);
110 }
111 }
112
113 module->fixup_ports();
114 }
115
116 std::string add_echos_to_abc9_cmd(std::string str)
117 {
118 std::string new_str, token;
119 for (size_t i = 0; i < str.size(); i++) {
120 token += str[i];
121 if (str[i] == ';') {
122 while (i+1 < str.size() && str[i+1] == ' ')
123 i++;
124 new_str += "echo + " + token + " " + token + " ";
125 token.clear();
126 }
127 }
128
129 if (!token.empty()) {
130 if (!new_str.empty())
131 new_str += "echo + " + token + "; ";
132 new_str += token;
133 }
134
135 return new_str;
136 }
137
138 std::string fold_abc9_cmd(std::string str)
139 {
140 std::string token, new_str = " ";
141 int char_counter = 10;
142
143 for (size_t i = 0; i <= str.size(); i++) {
144 if (i < str.size())
145 token += str[i];
146 if (i == str.size() || str[i] == ';') {
147 if (char_counter + token.size() > 75)
148 new_str += "\n ", char_counter = 14;
149 new_str += token, char_counter += token.size();
150 token.clear();
151 }
152 }
153
154 return new_str;
155 }
156
157 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
158 {
159 if (show_tempdir)
160 return text;
161
162 while (1) {
163 size_t pos = text.find(tempdir_name);
164 if (pos == std::string::npos)
165 break;
166 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
167 }
168
169 std::string selfdir_name = proc_self_dirname();
170 if (selfdir_name != "/") {
171 while (1) {
172 size_t pos = text.find(selfdir_name);
173 if (pos == std::string::npos)
174 break;
175 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
176 }
177 }
178
179 return text;
180 }
181
182 struct abc9_output_filter
183 {
184 bool got_cr;
185 int escape_seq_state;
186 std::string linebuf;
187 std::string tempdir_name;
188 bool show_tempdir;
189
190 abc9_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
191 {
192 got_cr = false;
193 escape_seq_state = 0;
194 }
195
196 void next_char(char ch)
197 {
198 if (escape_seq_state == 0 && ch == '\033') {
199 escape_seq_state = 1;
200 return;
201 }
202 if (escape_seq_state == 1) {
203 escape_seq_state = ch == '[' ? 2 : 0;
204 return;
205 }
206 if (escape_seq_state == 2) {
207 if ((ch < '0' || '9' < ch) && ch != ';')
208 escape_seq_state = 0;
209 return;
210 }
211 escape_seq_state = 0;
212 if (ch == '\r') {
213 got_cr = true;
214 return;
215 }
216 if (ch == '\n') {
217 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
218 got_cr = false, linebuf.clear();
219 return;
220 }
221 if (got_cr)
222 got_cr = false, linebuf.clear();
223 linebuf += ch;
224 }
225
226 void next_line(const std::string &line)
227 {
228 //int pi, po;
229 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
230 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
231 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
232 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
233 // return;
234 //}
235
236 for (char ch : line)
237 next_char(ch);
238 }
239 };
240
241 void abc9_module(RTLIL::Design *design, RTLIL::Module *module, std::string script_file, std::string exe_file,
242 bool cleanup, vector<int> lut_costs, bool /*dff_mode*/, std::string /*clk_str*/,
243 bool /*keepff*/, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode,
244 bool show_tempdir, std::string box_file, std::string lut_file,
245 std::string wire_delay, const dict<int,IdString> &box_lookup, bool nomfs
246 )
247 {
248 map_autoidx = autoidx++;
249
250 std::string tempdir_name = "/tmp/yosys-abc-XXXXXX";
251 if (!cleanup)
252 tempdir_name[0] = tempdir_name[4] = '_';
253 tempdir_name = make_temp_dir(tempdir_name);
254 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
255 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
256
257 std::string abc9_script;
258
259 if (!lut_costs.empty()) {
260 abc9_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
261 if (!box_file.empty())
262 abc9_script += stringf("read_box -v %s; ", box_file.c_str());
263 }
264 else
265 if (!lut_file.empty()) {
266 abc9_script += stringf("read_lut %s; ", lut_file.c_str());
267 if (!box_file.empty())
268 abc9_script += stringf("read_box -v %s; ", box_file.c_str());
269 }
270 else
271 log_abort();
272
273 abc9_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
274
275 if (!script_file.empty()) {
276 if (script_file[0] == '+') {
277 for (size_t i = 1; i < script_file.size(); i++)
278 if (script_file[i] == '\'')
279 abc9_script += "'\\''";
280 else if (script_file[i] == ',')
281 abc9_script += " ";
282 else
283 abc9_script += script_file[i];
284 } else
285 abc9_script += stringf("source %s", script_file.c_str());
286 } else if (!lut_costs.empty() || !lut_file.empty()) {
287 //bool all_luts_cost_same = true;
288 //for (int this_cost : lut_costs)
289 // if (this_cost != lut_costs.front())
290 // all_luts_cost_same = false;
291 abc9_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
292 //if (all_luts_cost_same && !fast_mode)
293 // abc9_script += "; lutpack {S}";
294 } else
295 log_abort();
296
297 //if (script_file.empty() && !delay_target.empty())
298 // for (size_t pos = abc9_script.find("dretime;"); pos != std::string::npos; pos = abc9_script.find("dretime;", pos+1))
299 // abc9_script = abc9_script.substr(0, pos) + "dretime; retime -o {D};" + abc9_script.substr(pos+8);
300
301 for (size_t pos = abc9_script.find("{D}"); pos != std::string::npos; pos = abc9_script.find("{D}", pos))
302 abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos+3);
303
304 //for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos))
305 // abc9_script = abc9_script.substr(0, pos) + lutin_shared + abc9_script.substr(pos+3);
306
307 for (size_t pos = abc9_script.find("{W}"); pos != std::string::npos; pos = abc9_script.find("{W}", pos))
308 abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos+3);
309
310 if (nomfs)
311 for (size_t pos = abc9_script.find("&mfs"); pos != std::string::npos; pos = abc9_script.find("&mfs", pos))
312 abc9_script = abc9_script.erase(pos, strlen("&mfs"));
313
314 abc9_script += stringf("; &write %s/output.aig", tempdir_name.c_str());
315 abc9_script = add_echos_to_abc9_cmd(abc9_script);
316
317 for (size_t i = 0; i+1 < abc9_script.size(); i++)
318 if (abc9_script[i] == ';' && abc9_script[i+1] == ' ')
319 abc9_script[i+1] = '\n';
320
321 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
322 fprintf(f, "%s\n", abc9_script.c_str());
323 fclose(f);
324
325 //bool count_output = false;
326 log_push();
327
328 //if (count_output)
329 {
330 handle_loops(design, module);
331
332 Pass::call(design, "aigmap -select");
333
334 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
335 // count_gates, GetSize(signal_list), count_input, count_output);
336
337 Pass::call(design, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name.c_str(), tempdir_name.c_str()));
338
339 std::string buffer;
340 std::ifstream ifs;
341 #if 0
342 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
343 ifs.open(buffer);
344 if (ifs.fail())
345 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
346 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
347 log_assert(!design->module(ID($__abc9__)));
348 {
349 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
350 reader.parse_xaiger(box_lookup);
351 }
352 ifs.close();
353 Pass::call_on_module(design, design->module(ID($__abc9__)), stringf("write_verilog -noexpr -norename -selected"));
354 design->remove(design->module(ID($__abc9__)));
355 #endif
356
357 // Now 'unexpose' those wires by undoing
358 // the expose operation -- remove them from PO/PI
359 // and re-connecting them back together
360 for (auto wire : module->wires()) {
361 auto it = wire->attributes.find(ID(abc9_scc_break));
362 if (it != wire->attributes.end()) {
363 wire->attributes.erase(it);
364 log_assert(wire->port_output);
365 wire->port_output = false;
366 RTLIL::Wire *i_wire = module->wire(wire->name.str() + ".abci");
367 log_assert(i_wire);
368 log_assert(i_wire->port_input);
369 i_wire->port_input = false;
370 module->connect(i_wire, wire);
371 }
372 }
373 module->fixup_ports();
374
375 log_header(design, "Executing ABC9.\n");
376
377 if (!lut_costs.empty()) {
378 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
379 f = fopen(buffer.c_str(), "wt");
380 if (f == NULL)
381 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
382 for (int i = 0; i < GetSize(lut_costs); i++)
383 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
384 fclose(f);
385 }
386
387 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
388 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
389
390 #ifndef YOSYS_LINK_ABC
391 abc9_output_filter filt(tempdir_name, show_tempdir);
392 int ret = run_command(buffer, std::bind(&abc9_output_filter::next_line, filt, std::placeholders::_1));
393 #else
394 // These needs to be mutable, supposedly due to getopt
395 char *abc9_argv[5];
396 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
397 abc9_argv[0] = strdup(exe_file.c_str());
398 abc9_argv[1] = strdup("-s");
399 abc9_argv[2] = strdup("-f");
400 abc9_argv[3] = strdup(tmp_script_name.c_str());
401 abc9_argv[4] = 0;
402 int ret = Abc_RealMain(4, abc9_argv);
403 free(abc9_argv[0]);
404 free(abc9_argv[1]);
405 free(abc9_argv[2]);
406 free(abc9_argv[3]);
407 #endif
408 if (ret != 0)
409 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
410
411 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
412 ifs.open(buffer, std::ifstream::binary);
413 if (ifs.fail())
414 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
415
416 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
417 log_assert(!design->module(ID($__abc9__)));
418
419 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
420 reader.parse_xaiger(box_lookup);
421 ifs.close();
422
423 #if 0
424 Pass::call_on_module(design, design->module(ID($__abc9__)), stringf("write_verilog -noexpr -norename -selected"));
425 #endif
426
427 log_header(design, "Re-integrating ABC9 results.\n");
428 RTLIL::Module *mapped_mod = design->module(ID($__abc9__));
429 if (mapped_mod == NULL)
430 log_error("ABC output file does not contain a module `$__abc9__'.\n");
431
432 pool<RTLIL::SigBit> output_bits;
433 for (auto &it : mapped_mod->wires_) {
434 RTLIL::Wire *w = it.second;
435 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
436 if (markgroups) remap_wire->attributes[ID(abcgroup)] = map_autoidx;
437 if (w->port_output) {
438 RTLIL::Wire *wire = module->wire(w->name);
439 log_assert(wire);
440 for (int i = 0; i < GetSize(w); i++)
441 output_bits.insert({wire, i});
442 }
443 }
444
445 for (auto &it : module->connections_) {
446 auto &signal = it.first;
447 auto bits = signal.bits();
448 for (auto &b : bits)
449 if (output_bits.count(b))
450 b = module->addWire(NEW_ID);
451 signal = std::move(bits);
452 }
453
454 dict<IdString, bool> abc9_box;
455 vector<RTLIL::Cell*> boxes;
456 for (auto cell : module->selected_cells()) {
457 if (cell->type.in(ID($_AND_), ID($_NOT_), ID($__ABC9_FF_))) {
458 module->remove(cell);
459 continue;
460 }
461 auto jt = abc9_box.find(cell->type);
462 if (jt == abc9_box.end()) {
463 RTLIL::Module* box_module = design->module(cell->type);
464 jt = abc9_box.insert(std::make_pair(cell->type, box_module && box_module->attributes.count(ID(abc9_box_id)))).first;
465 }
466 if (jt->second)
467 boxes.emplace_back(cell);
468 }
469
470 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
471 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
472 dict<RTLIL::Cell*,RTLIL::Cell*> not2drivers;
473 dict<SigBit, std::vector<RTLIL::Cell*>> bit2sinks;
474
475 std::map<IdString, int> cell_stats;
476 for (auto mapped_cell : mapped_mod->cells())
477 {
478 toposort.node(mapped_cell->name);
479
480 RTLIL::Cell *cell = nullptr;
481 if (mapped_cell->type == ID($_NOT_)) {
482 RTLIL::SigBit a_bit = mapped_cell->getPort(ID::A);
483 RTLIL::SigBit y_bit = mapped_cell->getPort(ID::Y);
484 bit_users[a_bit].insert(mapped_cell->name);
485 bit_drivers[y_bit].insert(mapped_cell->name);
486
487 if (!a_bit.wire) {
488 mapped_cell->setPort(ID::Y, module->addWire(NEW_ID));
489 RTLIL::Wire *wire = module->wire(remap_name(y_bit.wire->name));
490 log_assert(wire);
491 module->connect(RTLIL::SigBit(wire, y_bit.offset), State::S1);
492 }
493 else if (!lut_costs.empty() || !lut_file.empty()) {
494 RTLIL::Cell* driver_lut = nullptr;
495 // ABC can return NOT gates that drive POs
496 if (!a_bit.wire->port_input) {
497 // If it's not a NOT gate that that comes from a PI directly,
498 // find the driver LUT and clone that to guarantee that we won't
499 // increase the max logic depth
500 // (TODO: Optimise by not cloning unless will increase depth)
501 RTLIL::IdString driver_name;
502 if (GetSize(a_bit.wire) == 1)
503 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
504 else
505 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
506 driver_lut = mapped_mod->cell(driver_name);
507 }
508
509 if (!driver_lut) {
510 // If a driver couldn't be found (could be from PI or box CI)
511 // then implement using a LUT
512 cell = module->addLut(remap_name(stringf("%s$lut", mapped_cell->name.c_str())),
513 RTLIL::SigBit(module->wires_.at(remap_name(a_bit.wire->name)), a_bit.offset),
514 RTLIL::SigBit(module->wires_.at(remap_name(y_bit.wire->name)), y_bit.offset),
515 RTLIL::Const::from_string("01"));
516 bit2sinks[cell->getPort(ID::A)].push_back(cell);
517 cell_stats[ID($lut)]++;
518 }
519 else
520 not2drivers[mapped_cell] = driver_lut;
521 continue;
522 }
523 else
524 log_abort();
525 if (cell && markgroups) cell->attributes[ID(abcgroup)] = map_autoidx;
526 continue;
527 }
528 cell_stats[mapped_cell->type]++;
529
530 RTLIL::Cell *existing_cell = nullptr;
531 if (mapped_cell->type.in(ID($lut), ID($__ABC9_FF_))) {
532 if (mapped_cell->type == ID($lut) &&
533 GetSize(mapped_cell->getPort(ID::A)) == 1 &&
534 mapped_cell->getParam(ID(LUT)) == RTLIL::Const::from_string("01")) {
535 SigSpec my_a = module->wires_.at(remap_name(mapped_cell->getPort(ID::A).as_wire()->name));
536 SigSpec my_y = module->wires_.at(remap_name(mapped_cell->getPort(ID::Y).as_wire()->name));
537 module->connect(my_y, my_a);
538 if (markgroups) mapped_cell->attributes[ID(abcgroup)] = map_autoidx;
539 log_abort();
540 continue;
541 }
542 cell = module->addCell(remap_name(mapped_cell->name), mapped_cell->type);
543 }
544 else {
545 existing_cell = module->cell(mapped_cell->name);
546 log_assert(existing_cell);
547 cell = module->addCell(remap_name(mapped_cell->name), mapped_cell->type);
548 }
549
550 if (markgroups) cell->attributes[ID(abcgroup)] = map_autoidx;
551 if (existing_cell) {
552 cell->parameters = existing_cell->parameters;
553 cell->attributes = existing_cell->attributes;
554 }
555 else {
556 cell->parameters = mapped_cell->parameters;
557 cell->attributes = mapped_cell->attributes;
558 }
559
560 RTLIL::Module* box_module = design->module(mapped_cell->type);
561 auto abc9_flop = box_module && box_module->attributes.count("\\abc9_flop");
562 for (auto &conn : mapped_cell->connections()) {
563 RTLIL::SigSpec newsig;
564 for (auto c : conn.second.chunks()) {
565 if (c.width == 0)
566 continue;
567 //log_assert(c.width == 1);
568 if (c.wire)
569 c.wire = module->wires_.at(remap_name(c.wire->name));
570 newsig.append(c);
571 }
572 cell->setPort(conn.first, newsig);
573
574 if (!abc9_flop) {
575 if (cell->input(conn.first)) {
576 for (auto i : newsig)
577 bit2sinks[i].push_back(cell);
578 for (auto i : conn.second)
579 bit_users[i].insert(mapped_cell->name);
580 }
581 if (cell->output(conn.first))
582 for (auto i : conn.second)
583 bit_drivers[i].insert(mapped_cell->name);
584 }
585 }
586 }
587
588 for (auto existing_cell : boxes) {
589 Cell *cell = module->cell(remap_name(existing_cell->name));
590 if (cell) {
591 for (auto &conn : existing_cell->connections()) {
592 if (!conn.second.is_wire())
593 continue;
594 Wire *wire = conn.second.as_wire();
595 if (!wire->get_bool_attribute(ID(abc9_padding)))
596 continue;
597 cell->unsetPort(conn.first);
598 log_debug("Dropping padded port connection for %s (%s) .%s (%s )\n", log_id(cell), cell->type.c_str(), log_id(conn.first), log_signal(conn.second));
599 }
600 module->swap_names(cell, existing_cell);
601 }
602 module->remove(existing_cell);
603 }
604
605 // Copy connections (and rename) from mapped_mod to module
606 for (auto conn : mapped_mod->connections()) {
607 if (!conn.first.is_fully_const()) {
608 auto chunks = conn.first.chunks();
609 for (auto &c : chunks)
610 c.wire = module->wires_.at(remap_name(c.wire->name));
611 conn.first = std::move(chunks);
612 }
613 if (!conn.second.is_fully_const()) {
614 auto chunks = conn.second.chunks();
615 for (auto &c : chunks)
616 if (c.wire)
617 c.wire = module->wires_.at(remap_name(c.wire->name));
618 conn.second = std::move(chunks);
619 }
620 module->connect(conn);
621 }
622
623 for (auto &it : cell_stats)
624 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
625 int in_wires = 0, out_wires = 0;
626
627 // Stitch in mapped_mod's inputs/outputs into module
628 for (auto port : mapped_mod->ports) {
629 RTLIL::Wire *w = mapped_mod->wire(port);
630 RTLIL::Wire *wire = module->wire(port);
631 log_assert(wire);
632 RTLIL::Wire *remap_wire = module->wire(remap_name(port));
633 RTLIL::SigSpec signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
634 log_assert(GetSize(signal) >= GetSize(remap_wire));
635
636 RTLIL::SigSig conn;
637 if (w->port_output) {
638 conn.first = signal;
639 conn.second = remap_wire;
640 out_wires++;
641 module->connect(conn);
642 }
643 else if (w->port_input) {
644 conn.first = remap_wire;
645 conn.second = signal;
646 in_wires++;
647 module->connect(conn);
648 }
649 }
650
651 for (auto &it : bit_users)
652 if (bit_drivers.count(it.first))
653 for (auto driver_cell : bit_drivers.at(it.first))
654 for (auto user_cell : it.second)
655 toposort.edge(driver_cell, user_cell);
656 bool no_loops YS_ATTRIBUTE(unused) = toposort.sort();
657 log_assert(no_loops);
658
659 for (auto ii = toposort.sorted.rbegin(); ii != toposort.sorted.rend(); ii++) {
660 RTLIL::Cell *not_cell = mapped_mod->cell(*ii);
661 log_assert(not_cell);
662 if (not_cell->type != ID($_NOT_))
663 continue;
664 auto it = not2drivers.find(not_cell);
665 if (it == not2drivers.end())
666 continue;
667 RTLIL::Cell *driver_lut = it->second;
668 RTLIL::SigBit a_bit = not_cell->getPort(ID::A);
669 RTLIL::SigBit y_bit = not_cell->getPort(ID::Y);
670 RTLIL::Const driver_mask;
671
672 a_bit.wire = module->wires_.at(remap_name(a_bit.wire->name));
673 y_bit.wire = module->wires_.at(remap_name(y_bit.wire->name));
674
675 auto jt = bit2sinks.find(a_bit);
676 if (jt == bit2sinks.end())
677 goto clone_lut;
678
679 for (auto sink_cell : jt->second)
680 if (sink_cell->type != ID($lut))
681 goto clone_lut;
682
683 // Push downstream LUTs past inverter
684 for (auto sink_cell : jt->second) {
685 SigSpec A = sink_cell->getPort(ID::A);
686 RTLIL::Const mask = sink_cell->getParam(ID(LUT));
687 int index = 0;
688 for (; index < GetSize(A); index++)
689 if (A[index] == a_bit)
690 break;
691 log_assert(index < GetSize(A));
692 int i = 0;
693 while (i < GetSize(mask)) {
694 for (int j = 0; j < (1 << index); j++)
695 std::swap(mask[i+j], mask[i+j+(1 << index)]);
696 i += 1 << (index+1);
697 }
698 A[index] = y_bit;
699 sink_cell->setPort(ID::A, A);
700 sink_cell->setParam(ID(LUT), mask);
701 }
702
703 // Since we have rewritten all sinks (which we know
704 // to be only LUTs) to be after the inverter, we can
705 // go ahead and clone the LUT with the expectation
706 // that the original driving LUT will become dangling
707 // and get cleaned away
708 clone_lut:
709 driver_mask = driver_lut->getParam(ID(LUT));
710 for (auto &b : driver_mask.bits) {
711 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
712 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
713 }
714 auto cell = module->addLut(NEW_ID,
715 driver_lut->getPort(ID::A),
716 y_bit,
717 driver_mask);
718 for (auto &bit : cell->connections_.at(ID::A)) {
719 bit.wire = module->wires_.at(remap_name(bit.wire->name));
720 bit2sinks[bit].push_back(cell);
721 }
722 }
723
724 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
725 log("ABC RESULTS: input signals: %8d\n", in_wires);
726 log("ABC RESULTS: output signals: %8d\n", out_wires);
727
728 design->remove(mapped_mod);
729 }
730 //else
731 //{
732 // log("Don't call ABC as there is nothing to map.\n");
733 //}
734
735 if (cleanup)
736 {
737 log("Removing temp directory.\n");
738 remove_directory(tempdir_name);
739 }
740
741 log_pop();
742 }
743
744 struct Abc9Pass : public Pass {
745 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
746 void help() YS_OVERRIDE
747 {
748 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
749 log("\n");
750 log(" abc9 [options] [selection]\n");
751 log("\n");
752 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
753 log("library to a target architecture.\n");
754 log("\n");
755 log("Selection must only contain fully selected modules. It is assumed that such\n");
756 log("modules contain only cells belonging to the same clock domain, as produced by\n");
757 log("the 'clkpart' command.\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_abc9_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_abc9_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_abc9_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 an XAIGER file with write_xaiger and then load that into ABC externally\n");
851 log("if you want to use ABC to convert your design into another format.\n");
852 log("\n");
853 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
854 log("Delay targets can also be specified on a per clock basis by attaching a\n");
855 log("'(* abc9_period = <int> *)' attribute onto clock wires (specifically, onto wires\n");
856 log("that appear inside any special '$abc9_clock' wires inserted by abc9_map.v). This\n");
857 log("can be achieved by modifying the source directly, or through a `setattr`\n");
858 log("invocation. Since such attributes cannot yet be propagated through a\n");
859 log("hierarchical design (whether or not it has been uniquified) it is recommended\n");
860 log("that the design be flattened when using this feature.\n");
861 log("\n");
862 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
863 log("\n");
864 }
865 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
866 {
867 log_header(design, "Executing ABC9 pass (technology mapping using ABC9).\n");
868 log_push();
869
870 #ifdef ABCEXTERNAL
871 std::string exe_file = ABCEXTERNAL;
872 #else
873 std::string exe_file = proc_self_dirname() + "yosys-abc";
874 #endif
875 std::string script_file, clk_str, box_file, lut_file;
876 std::string delay_target, lutin_shared = "-S 1", wire_delay;
877 bool fast_mode = false, /*dff_mode = false,*/ keepff = false, cleanup = true;
878 bool show_tempdir = false;
879 bool nomfs = false;
880 vector<int> lut_costs;
881 markgroups = false;
882
883 #if 0
884 cleanup = false;
885 show_tempdir = true;
886 #endif
887
888 #ifdef _WIN32
889 #ifndef ABCEXTERNAL
890 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
891 exe_file = proc_self_dirname() + "..\\yosys-abc";
892 #endif
893 #endif
894
895 size_t argidx;
896 char pwd [PATH_MAX];
897 if (!getcwd(pwd, sizeof(pwd))) {
898 log_cmd_error("getcwd failed: %s\n", strerror(errno));
899 log_abort();
900 }
901 for (argidx = 1; argidx < args.size(); argidx++) {
902 std::string arg = args[argidx];
903 if (arg == "-exe" && argidx+1 < args.size()) {
904 exe_file = args[++argidx];
905 continue;
906 }
907 if (arg == "-script" && argidx+1 < args.size()) {
908 script_file = args[++argidx];
909 rewrite_filename(script_file);
910 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
911 script_file = std::string(pwd) + "/" + script_file;
912 continue;
913 }
914 if (arg == "-D" && argidx+1 < args.size()) {
915 delay_target = "-D " + args[++argidx];
916 continue;
917 }
918 //if (arg == "-S" && argidx+1 < args.size()) {
919 // lutin_shared = "-S " + args[++argidx];
920 // continue;
921 //}
922 if (arg == "-lut" && argidx+1 < args.size()) {
923 string arg = args[++argidx];
924 size_t pos = arg.find_first_of(':');
925 int lut_mode = 0, lut_mode2 = 0;
926 if (pos != string::npos) {
927 lut_mode = atoi(arg.substr(0, pos).c_str());
928 lut_mode2 = atoi(arg.substr(pos+1).c_str());
929 } else {
930 pos = arg.find_first_of('.');
931 if (pos != string::npos) {
932 lut_file = arg;
933 rewrite_filename(lut_file);
934 if (!lut_file.empty() && !is_absolute_path(lut_file))
935 lut_file = std::string(pwd) + "/" + lut_file;
936 }
937 else {
938 lut_mode = atoi(arg.c_str());
939 lut_mode2 = lut_mode;
940 }
941 }
942 lut_costs.clear();
943 for (int i = 0; i < lut_mode; i++)
944 lut_costs.push_back(1);
945 for (int i = lut_mode; i < lut_mode2; i++)
946 lut_costs.push_back(2 << (i - lut_mode));
947 continue;
948 }
949 if (arg == "-luts" && argidx+1 < args.size()) {
950 lut_costs.clear();
951 for (auto &tok : split_tokens(args[++argidx], ",")) {
952 auto parts = split_tokens(tok, ":");
953 if (GetSize(parts) == 0 && !lut_costs.empty())
954 lut_costs.push_back(lut_costs.back());
955 else if (GetSize(parts) == 1)
956 lut_costs.push_back(atoi(parts.at(0).c_str()));
957 else if (GetSize(parts) == 2)
958 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
959 lut_costs.push_back(atoi(parts.at(1).c_str()));
960 else
961 log_cmd_error("Invalid -luts syntax.\n");
962 }
963 continue;
964 }
965 if (arg == "-fast") {
966 fast_mode = true;
967 continue;
968 }
969 //if (arg == "-dff") {
970 // dff_mode = true;
971 // continue;
972 //}
973 //if (arg == "-clk" && argidx+1 < args.size()) {
974 // clk_str = args[++argidx];
975 // dff_mode = true;
976 // continue;
977 //}
978 //if (arg == "-keepff") {
979 // keepff = true;
980 // continue;
981 //}
982 if (arg == "-nocleanup") {
983 cleanup = false;
984 continue;
985 }
986 if (arg == "-showtmp") {
987 show_tempdir = true;
988 continue;
989 }
990 if (arg == "-markgroups") {
991 markgroups = true;
992 continue;
993 }
994 if (arg == "-box" && argidx+1 < args.size()) {
995 box_file = args[++argidx];
996 continue;
997 }
998 if (arg == "-W" && argidx+1 < args.size()) {
999 wire_delay = "-W " + args[++argidx];
1000 continue;
1001 }
1002 if (arg == "-nomfs") {
1003 nomfs = true;
1004 continue;
1005 }
1006 break;
1007 }
1008 extra_args(args, argidx, design);
1009
1010 // ABC expects a box file for XAIG
1011 if (box_file.empty())
1012 box_file = "+/dummy.box";
1013
1014 rewrite_filename(box_file);
1015 if (!box_file.empty() && !is_absolute_path(box_file))
1016 box_file = std::string(pwd) + "/" + box_file;
1017
1018 dict<int,IdString> box_lookup;
1019 for (auto m : design->modules()) {
1020 auto it = m->attributes.find(ID(abc9_box_id));
1021 if (it == m->attributes.end())
1022 continue;
1023 if (m->name.begins_with("$paramod"))
1024 continue;
1025 auto id = it->second.as_int();
1026 auto r = box_lookup.insert(std::make_pair(id, m->name));
1027 if (!r.second)
1028 log_error("Module '%s' has the same abc9_box_id = %d value as '%s'.\n",
1029 log_id(m), id, log_id(r.first->second));
1030 log_assert(r.second);
1031
1032 RTLIL::Wire *carry_in = nullptr, *carry_out = nullptr;
1033 for (auto p : m->ports) {
1034 auto w = m->wire(p);
1035 log_assert(w);
1036 if (w->attributes.count(ID(abc9_carry))) {
1037 if (w->port_input) {
1038 if (carry_in)
1039 log_error("Module '%s' contains more than one 'abc9_carry' input port.\n", log_id(m));
1040 carry_in = w;
1041 }
1042 else if (w->port_output) {
1043 if (carry_out)
1044 log_error("Module '%s' contains more than one 'abc9_carry' input port.\n", log_id(m));
1045 carry_out = w;
1046 }
1047 }
1048 }
1049 if (carry_in || carry_out) {
1050 if (carry_in && !carry_out)
1051 log_error("Module '%s' contains an 'abc9_carry' input port but no output port.\n", log_id(m));
1052 if (!carry_in && carry_out)
1053 log_error("Module '%s' contains an 'abc9_carry' output port but no input port.\n", log_id(m));
1054 // Make carry_in the last PI, and carry_out the last PO
1055 // since ABC requires it this way
1056 auto &ports = m->ports;
1057 for (auto it = ports.begin(); it != ports.end(); ) {
1058 RTLIL::Wire* w = m->wire(*it);
1059 log_assert(w);
1060 if (w == carry_in || w == carry_out) {
1061 it = ports.erase(it);
1062 continue;
1063 }
1064 if (w->port_id > carry_in->port_id)
1065 --w->port_id;
1066 if (w->port_id > carry_out->port_id)
1067 --w->port_id;
1068 log_assert(w->port_input || w->port_output);
1069 log_assert(ports[w->port_id-1] == w->name);
1070 ++it;
1071 }
1072 ports.push_back(carry_in->name);
1073 carry_in->port_id = ports.size();
1074 ports.push_back(carry_out->name);
1075 carry_out->port_id = ports.size();
1076 }
1077 }
1078
1079 for (auto module : design->selected_modules())
1080 {
1081 if (module->attributes.count(ID(abc9_box_id)))
1082 continue;
1083
1084 if (module->processes.size() > 0) {
1085 log("Skipping module %s as it contains processes.\n", log_id(module));
1086 continue;
1087 }
1088
1089 if (!design->selected_whole_module(module)) {
1090 log("Skipping module %s as it is partially selected.\n", log_id(module));
1091 continue;
1092 }
1093
1094 SigMap sigmap(module);
1095
1096 typedef std::pair<IdString, SigSpec> ctrldomain_t;
1097 std::map<ctrldomain_t, int> mergeability_class;
1098 pool<Wire*> clocks;
1099 std::string target = delay_target;
1100
1101 for (auto cell : module->cells()) {
1102 auto inst_module = design->module(cell->type);
1103 if (!inst_module || !inst_module->attributes.count("\\abc9_flop"))
1104 continue;
1105
1106 if (delay_target.empty()) {
1107 Wire *abc9_clock_wire = module->wire(stringf("%s.$abc9_clock", cell->name.c_str()));
1108 if (abc9_clock_wire == NULL)
1109 log_error("'%s.$abc9_clock' is not a wire present in module '%s'.\n", cell->name.c_str(), log_id(module));
1110 log_assert(GetSize(abc9_clock_wire) == 1);
1111 SigBit abc9_clock = sigmap(abc9_clock_wire);
1112 auto r = clocks.insert(abc9_clock.wire);
1113 if (r.second) {
1114 auto it = abc9_clock.wire->attributes.find("\\abc9_period");
1115 if (it != abc9_clock.wire->attributes.end()) {
1116 int period = it->second.as_int();
1117 log("Identified target period = %d ps for clock %s\n", period, log_signal(abc9_clock));
1118 target = stringf("-D %d", period);
1119 }
1120 }
1121 }
1122
1123 Wire *abc9_control_wire = module->wire(stringf("%s.$abc9_control", cell->name.c_str()));
1124 if (abc9_control_wire == NULL)
1125 log_error("'%s.$abc9_control' is not a wire present in module '%s'.\n", cell->name.c_str(), log_id(module));
1126 SigSpec abc9_control = sigmap(abc9_control_wire);
1127
1128 ctrldomain_t key(cell->type, abc9_control);
1129 auto r = mergeability_class.emplace(key, mergeability_class.size() + 1);
1130 auto YS_ATTRIBUTE(unused) r2 = cell->attributes.insert(std::make_pair(ID(abc9_mergeability), r.first->second));
1131 log_assert(r2.second);
1132
1133 Wire *abc9_init_wire = module->wire(stringf("%s.$abc9_init", cell->name.c_str()));
1134 if (abc9_init_wire == NULL)
1135 log_error("'%s.$abc9_init' is not a wire present in module '%s'.\n", cell->name.c_str(), log_id(module));
1136 log_assert(GetSize(abc9_init_wire) == 1);
1137 SigSpec abc9_init = sigmap(abc9_init_wire);
1138 if (!abc9_init.is_fully_const())
1139 log_error("'%s.$abc9_init' is not a constant wire present in module '%s'.\n", cell->name.c_str(), log_id(module));
1140 r2 = cell->attributes.insert(std::make_pair(ID(abc9_init), abc9_init.as_const()));
1141 log_assert(r2.second);
1142 }
1143
1144 design->selected_active_module = module->name.str();
1145 abc9_module(design, module, script_file, exe_file, cleanup, lut_costs, false, "$",
1146 keepff, target, lutin_shared, fast_mode, show_tempdir,
1147 box_file, lut_file, wire_delay, box_lookup, nomfs);
1148 design->selected_active_module.clear();
1149 }
1150
1151 log_pop();
1152 }
1153 } Abc9Pass;
1154
1155 PRIVATE_NAMESPACE_END