Cleanup
[yosys.git] / passes / techmap / abc9_map.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"
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 std::string add_echos_to_abc9_cmd(std::string str)
75 {
76 std::string new_str, token;
77 for (size_t i = 0; i < str.size(); i++) {
78 token += str[i];
79 if (str[i] == ';') {
80 while (i+1 < str.size() && str[i+1] == ' ')
81 i++;
82 new_str += "echo + " + token + " " + token + " ";
83 token.clear();
84 }
85 }
86
87 if (!token.empty()) {
88 if (!new_str.empty())
89 new_str += "echo + " + token + "; ";
90 new_str += token;
91 }
92
93 return new_str;
94 }
95
96 std::string fold_abc9_cmd(std::string str)
97 {
98 std::string token, new_str = " ";
99 int char_counter = 10;
100
101 for (size_t i = 0; i <= str.size(); i++) {
102 if (i < str.size())
103 token += str[i];
104 if (i == str.size() || str[i] == ';') {
105 if (char_counter + token.size() > 75)
106 new_str += "\n ", char_counter = 14;
107 new_str += token, char_counter += token.size();
108 token.clear();
109 }
110 }
111
112 return new_str;
113 }
114
115 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
116 {
117 if (show_tempdir)
118 return text;
119
120 while (1) {
121 size_t pos = text.find(tempdir_name);
122 if (pos == std::string::npos)
123 break;
124 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
125 }
126
127 std::string selfdir_name = proc_self_dirname();
128 if (selfdir_name != "/") {
129 while (1) {
130 size_t pos = text.find(selfdir_name);
131 if (pos == std::string::npos)
132 break;
133 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
134 }
135 }
136
137 return text;
138 }
139
140 struct abc9_output_filter
141 {
142 bool got_cr;
143 int escape_seq_state;
144 std::string linebuf;
145 std::string tempdir_name;
146 bool show_tempdir;
147
148 abc9_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
149 {
150 got_cr = false;
151 escape_seq_state = 0;
152 }
153
154 void next_char(char ch)
155 {
156 if (escape_seq_state == 0 && ch == '\033') {
157 escape_seq_state = 1;
158 return;
159 }
160 if (escape_seq_state == 1) {
161 escape_seq_state = ch == '[' ? 2 : 0;
162 return;
163 }
164 if (escape_seq_state == 2) {
165 if ((ch < '0' || '9' < ch) && ch != ';')
166 escape_seq_state = 0;
167 return;
168 }
169 escape_seq_state = 0;
170 if (ch == '\r') {
171 got_cr = true;
172 return;
173 }
174 if (ch == '\n') {
175 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
176 got_cr = false, linebuf.clear();
177 return;
178 }
179 if (got_cr)
180 got_cr = false, linebuf.clear();
181 linebuf += ch;
182 }
183
184 void next_line(const std::string &line)
185 {
186 //int pi, po;
187 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
188 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
189 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
190 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
191 // return;
192 //}
193
194 for (char ch : line)
195 next_char(ch);
196 }
197 };
198
199 void abc9_module(RTLIL::Design *design, RTLIL::Module *module, std::string script_file, std::string exe_file,
200 vector<int> lut_costs, std::string delay_target, std::string /*lutin_shared*/, bool fast_mode,
201 bool show_tempdir, std::string box_file, std::string lut_file,
202 std::string wire_delay, bool nomfs, std::string tempdir_name
203 )
204 {
205 map_autoidx = autoidx++;
206
207 //FIXME:
208 //log_header(design, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
209 // module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
210
211 std::string abc9_script;
212
213 if (!lut_costs.empty()) {
214 abc9_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
215 if (!box_file.empty())
216 abc9_script += stringf("read_box %s; ", box_file.c_str());
217 }
218 else
219 if (!lut_file.empty()) {
220 abc9_script += stringf("read_lut %s; ", lut_file.c_str());
221 if (!box_file.empty())
222 abc9_script += stringf("read_box %s; ", box_file.c_str());
223 }
224 else
225 log_abort();
226
227 abc9_script += stringf("&read %s/input.xaig; &ps; ", tempdir_name.c_str());
228
229 if (!script_file.empty()) {
230 if (script_file[0] == '+') {
231 for (size_t i = 1; i < script_file.size(); i++)
232 if (script_file[i] == '\'')
233 abc9_script += "'\\''";
234 else if (script_file[i] == ',')
235 abc9_script += " ";
236 else
237 abc9_script += script_file[i];
238 } else
239 abc9_script += stringf("source %s", script_file.c_str());
240 } else if (!lut_costs.empty() || !lut_file.empty()) {
241 abc9_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
242 } else
243 log_abort();
244
245 for (size_t pos = abc9_script.find("{D}"); pos != std::string::npos; pos = abc9_script.find("{D}", pos))
246 abc9_script = abc9_script.substr(0, pos) + delay_target + abc9_script.substr(pos+3);
247
248 //for (size_t pos = abc9_script.find("{S}"); pos != std::string::npos; pos = abc9_script.find("{S}", pos))
249 // abc9_script = abc9_script.substr(0, pos) + lutin_shared + abc9_script.substr(pos+3);
250
251 for (size_t pos = abc9_script.find("{W}"); pos != std::string::npos; pos = abc9_script.find("{W}", pos))
252 abc9_script = abc9_script.substr(0, pos) + wire_delay + abc9_script.substr(pos+3);
253
254 if (nomfs)
255 for (size_t pos = abc9_script.find("&mfs"); pos != std::string::npos; pos = abc9_script.find("&mfs", pos))
256 abc9_script = abc9_script.erase(pos, strlen("&mfs"));
257
258 abc9_script += stringf("; &write -n %s/output.aig", tempdir_name.c_str());
259 abc9_script = add_echos_to_abc9_cmd(abc9_script);
260
261 for (size_t i = 0; i+1 < abc9_script.size(); i++)
262 if (abc9_script[i] == ';' && abc9_script[i+1] == ' ')
263 abc9_script[i+1] = '\n';
264
265 FILE *f = fopen(stringf("%s/abc.script", tempdir_name.c_str()).c_str(), "wt");
266 fprintf(f, "%s\n", abc9_script.c_str());
267 fclose(f);
268
269 int count_outputs = design->scratchpad_get_int("write_xaiger.num_outputs");
270 log("Extracted %d AND gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
271 design->scratchpad_get_int("write_xaiger.num_ands"),
272 design->scratchpad_get_int("write_xaiger.num_wires"),
273 design->scratchpad_get_int("write_xaiger.num_inputs"),
274 count_outputs);
275
276 if (count_outputs > 0) {
277 std::string buffer;
278 std::ifstream ifs;
279 #if 0
280 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.xaig");
281 ifs.open(buffer);
282 if (ifs.fail())
283 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
284 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
285 log_assert(!design->module(ID($__abc9__)));
286 {
287 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
288 reader.parse_xaiger();
289 }
290 ifs.close();
291 Pass::call_on_module(design, design->module(ID($__abc9__)), stringf("write_verilog -noexpr -norename -selected"));
292 design->remove(design->module(ID($__abc9__)));
293 #endif
294
295 log_header(design, "Executing ABC9.\n");
296
297 if (!lut_costs.empty()) {
298 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
299 f = fopen(buffer.c_str(), "wt");
300 if (f == NULL)
301 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
302 for (int i = 0; i < GetSize(lut_costs); i++)
303 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
304 fclose(f);
305 }
306
307 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
308 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
309
310 #ifndef YOSYS_LINK_ABC
311 abc9_output_filter filt(tempdir_name, show_tempdir);
312 int ret = run_command(buffer, std::bind(&abc9_output_filter::next_line, filt, std::placeholders::_1));
313 #else
314 // These needs to be mutable, supposedly due to getopt
315 char *abc9_argv[5];
316 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
317 abc9_argv[0] = strdup(exe_file.c_str());
318 abc9_argv[1] = strdup("-s");
319 abc9_argv[2] = strdup("-f");
320 abc9_argv[3] = strdup(tmp_script_name.c_str());
321 abc9_argv[4] = 0;
322 int ret = Abc_RealMain(4, abc9_argv);
323 free(abc9_argv[0]);
324 free(abc9_argv[1]);
325 free(abc9_argv[2]);
326 free(abc9_argv[3]);
327 #endif
328 if (ret != 0)
329 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
330
331 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.aig");
332 ifs.open(buffer, std::ifstream::binary);
333 if (ifs.fail())
334 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
335
336 buffer = stringf("%s/%s", tempdir_name.c_str(), "input.sym");
337 log_assert(!design->module(ID($__abc9__)));
338
339 AigerReader reader(design, ifs, ID($__abc9__), "" /* clk_name */, buffer.c_str() /* map_filename */, true /* wideports */);
340 reader.parse_xaiger();
341 ifs.close();
342
343 #if 0
344 Pass::call_on_module(design, design->module(ID($__abc9__)), stringf("write_verilog -noexpr -norename -selected"));
345 #endif
346
347 log_header(design, "Re-integrating ABC9 results.\n");
348 RTLIL::Module *mapped_mod = design->module(ID($__abc9__));
349 if (mapped_mod == NULL)
350 log_error("ABC output file does not contain a module `$__abc9__'.\n");
351
352 for (auto &it : mapped_mod->wires_) {
353 RTLIL::Wire *w = it.second;
354 RTLIL::Wire *remap_wire = module->addWire(remap_name(w->name), GetSize(w));
355 if (markgroups) remap_wire->attributes[ID(abcgroup)] = map_autoidx;
356 }
357
358 for (auto it = module->cells_.begin(); it != module->cells_.end(); )
359 if (it->second->type.in(ID($_AND_), ID($_NOT_), ID($__ABC9_FF_)))
360 it = module->cells_.erase(it);
361 else
362 ++it;
363
364 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
365 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
366 dict<RTLIL::Cell*,RTLIL::Cell*> not2drivers;
367 dict<SigBit, std::vector<RTLIL::Cell*>> bit2sinks;
368
369 std::map<IdString, int> cell_stats;
370 for (auto mapped_cell : mapped_mod->cells())
371 {
372 toposort.node(mapped_cell->name);
373
374 RTLIL::Cell *cell = nullptr;
375 if (mapped_cell->type == ID($_NOT_)) {
376 RTLIL::SigBit a_bit = mapped_cell->getPort(ID::A);
377 RTLIL::SigBit y_bit = mapped_cell->getPort(ID::Y);
378 bit_users[a_bit].insert(mapped_cell->name);
379 bit_drivers[y_bit].insert(mapped_cell->name);
380
381 if (!a_bit.wire) {
382 mapped_cell->setPort(ID::Y, module->addWire(NEW_ID));
383 RTLIL::Wire *wire = module->wire(remap_name(y_bit.wire->name));
384 log_assert(wire);
385 module->connect(RTLIL::SigBit(wire, y_bit.offset), State::S1);
386 }
387 else if (!lut_costs.empty() || !lut_file.empty()) {
388 RTLIL::Cell* driver_lut = nullptr;
389 // ABC can return NOT gates that drive POs
390 if (!a_bit.wire->port_input) {
391 // If it's not a NOT gate that that comes from a PI directly,
392 // find the driver LUT and clone that to guarantee that we won't
393 // increase the max logic depth
394 // (TODO: Optimise by not cloning unless will increase depth)
395 RTLIL::IdString driver_name;
396 if (GetSize(a_bit.wire) == 1)
397 driver_name = stringf("%s$lut", a_bit.wire->name.c_str());
398 else
399 driver_name = stringf("%s[%d]$lut", a_bit.wire->name.c_str(), a_bit.offset);
400 driver_lut = mapped_mod->cell(driver_name);
401 }
402
403 if (!driver_lut) {
404 // If a driver couldn't be found (could be from PI or box CI)
405 // then implement using a LUT
406 cell = module->addLut(remap_name(stringf("%s$lut", mapped_cell->name.c_str())),
407 RTLIL::SigBit(module->wires_.at(remap_name(a_bit.wire->name)), a_bit.offset),
408 RTLIL::SigBit(module->wires_.at(remap_name(y_bit.wire->name)), y_bit.offset),
409 RTLIL::Const::from_string("01"));
410 bit2sinks[cell->getPort(ID::A)].push_back(cell);
411 cell_stats[ID($lut)]++;
412 }
413 else
414 not2drivers[mapped_cell] = driver_lut;
415 continue;
416 }
417 else
418 log_abort();
419 if (cell && markgroups) cell->attributes[ID(abcgroup)] = map_autoidx;
420 continue;
421 }
422 cell_stats[mapped_cell->type]++;
423
424 RTLIL::Cell *existing_cell = nullptr;
425 if (mapped_cell->type.in(ID($lut), ID($__ABC9_FF_))) {
426 if (mapped_cell->type == ID($lut) &&
427 GetSize(mapped_cell->getPort(ID::A)) == 1 &&
428 mapped_cell->getParam(ID(LUT)) == RTLIL::Const::from_string("01")) {
429 SigSpec my_a = module->wires_.at(remap_name(mapped_cell->getPort(ID::A).as_wire()->name));
430 SigSpec my_y = module->wires_.at(remap_name(mapped_cell->getPort(ID::Y).as_wire()->name));
431 module->connect(my_y, my_a);
432 if (markgroups) mapped_cell->attributes[ID(abcgroup)] = map_autoidx;
433 log_abort();
434 continue;
435 }
436 cell = module->addCell(remap_name(mapped_cell->name), mapped_cell->type);
437 }
438 else {
439 existing_cell = module->cell(mapped_cell->name);
440 log_assert(existing_cell);
441 cell = module->addCell(remap_name(mapped_cell->name), mapped_cell->type);
442 }
443
444 if (markgroups) cell->attributes[ID(abcgroup)] = map_autoidx;
445 if (existing_cell) {
446 cell->parameters = existing_cell->parameters;
447 cell->attributes = existing_cell->attributes;
448 }
449 else {
450 cell->parameters = mapped_cell->parameters;
451 cell->attributes = mapped_cell->attributes;
452 }
453
454 auto abc9_box = cell->attributes.erase("\\abc9_box_seq");
455 if (abc9_box) {
456 module->swap_names(cell, existing_cell);
457 module->remove(existing_cell);
458 }
459 RTLIL::Module* box_module = design->module(mapped_cell->type);
460 auto abc9_flop = box_module && box_module->attributes.count("\\abc9_flop");
461 for (auto &conn : mapped_cell->connections()) {
462 // Skip entire box ports composed entirely of padding only
463 if (abc9_box && conn.second.is_wire() && conn.second.as_wire()->get_bool_attribute(ID(abc9_padding)))
464 continue;
465
466 RTLIL::SigSpec newsig;
467 for (auto c : conn.second.chunks()) {
468 if (c.width == 0)
469 continue;
470 //log_assert(c.width == 1);
471 if (c.wire)
472 c.wire = module->wires_.at(remap_name(c.wire->name));
473 newsig.append(c);
474 }
475 cell->setPort(conn.first, newsig);
476
477 if (!abc9_flop) {
478 if (cell->input(conn.first)) {
479 for (auto i : newsig)
480 bit2sinks[i].push_back(cell);
481 for (auto i : conn.second)
482 bit_users[i].insert(mapped_cell->name);
483 }
484 if (cell->output(conn.first))
485 for (auto i : conn.second)
486 bit_drivers[i].insert(mapped_cell->name);
487 }
488 }
489 }
490
491 // Copy connections (and rename) from mapped_mod to module
492 for (auto conn : mapped_mod->connections()) {
493 if (!conn.first.is_fully_const()) {
494 auto chunks = conn.first.chunks();
495 for (auto &c : chunks)
496 c.wire = module->wires_.at(remap_name(c.wire->name));
497 conn.first = std::move(chunks);
498 }
499 if (!conn.second.is_fully_const()) {
500 auto chunks = conn.second.chunks();
501 for (auto &c : chunks)
502 if (c.wire)
503 c.wire = module->wires_.at(remap_name(c.wire->name));
504 conn.second = std::move(chunks);
505 }
506 module->connect(conn);
507 }
508
509 for (auto &it : cell_stats)
510 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
511 int in_wires = 0, out_wires = 0;
512
513 // Stitch in mapped_mod's inputs/outputs into module
514 for (auto port : mapped_mod->ports) {
515 RTLIL::Wire *w = mapped_mod->wire(port);
516 RTLIL::Wire *wire = module->wire(port);
517 log_assert(wire);
518 RTLIL::Wire *remap_wire = module->wire(remap_name(port));
519 RTLIL::SigSpec signal = RTLIL::SigSpec(wire, 0, GetSize(remap_wire));
520 log_assert(GetSize(signal) >= GetSize(remap_wire));
521
522 RTLIL::SigSig conn;
523 if (w->port_output) {
524 conn.first = signal;
525 conn.second = remap_wire;
526 out_wires++;
527 module->connect(conn);
528 }
529 else if (w->port_input) {
530 conn.first = remap_wire;
531 conn.second = signal;
532 in_wires++;
533 module->connect(conn);
534 }
535 }
536
537 for (auto &it : bit_users)
538 if (bit_drivers.count(it.first))
539 for (auto driver_cell : bit_drivers.at(it.first))
540 for (auto user_cell : it.second)
541 toposort.edge(driver_cell, user_cell);
542 bool no_loops YS_ATTRIBUTE(unused) = toposort.sort();
543 log_assert(no_loops);
544
545 for (auto ii = toposort.sorted.rbegin(); ii != toposort.sorted.rend(); ii++) {
546 RTLIL::Cell *not_cell = mapped_mod->cell(*ii);
547 log_assert(not_cell);
548 if (not_cell->type != ID($_NOT_))
549 continue;
550 auto it = not2drivers.find(not_cell);
551 if (it == not2drivers.end())
552 continue;
553 RTLIL::Cell *driver_lut = it->second;
554 RTLIL::SigBit a_bit = not_cell->getPort(ID::A);
555 RTLIL::SigBit y_bit = not_cell->getPort(ID::Y);
556 RTLIL::Const driver_mask;
557
558 a_bit.wire = module->wires_.at(remap_name(a_bit.wire->name));
559 y_bit.wire = module->wires_.at(remap_name(y_bit.wire->name));
560
561 auto jt = bit2sinks.find(a_bit);
562 if (jt == bit2sinks.end())
563 goto clone_lut;
564
565 for (auto sink_cell : jt->second)
566 if (sink_cell->type != ID($lut))
567 goto clone_lut;
568
569 // Push downstream LUTs past inverter
570 for (auto sink_cell : jt->second) {
571 SigSpec A = sink_cell->getPort(ID::A);
572 RTLIL::Const mask = sink_cell->getParam(ID(LUT));
573 int index = 0;
574 for (; index < GetSize(A); index++)
575 if (A[index] == a_bit)
576 break;
577 log_assert(index < GetSize(A));
578 int i = 0;
579 while (i < GetSize(mask)) {
580 for (int j = 0; j < (1 << index); j++)
581 std::swap(mask[i+j], mask[i+j+(1 << index)]);
582 i += 1 << (index+1);
583 }
584 A[index] = y_bit;
585 sink_cell->setPort(ID::A, A);
586 sink_cell->setParam(ID(LUT), mask);
587 }
588
589 // Since we have rewritten all sinks (which we know
590 // to be only LUTs) to be after the inverter, we can
591 // go ahead and clone the LUT with the expectation
592 // that the original driving LUT will become dangling
593 // and get cleaned away
594 clone_lut:
595 driver_mask = driver_lut->getParam(ID(LUT));
596 for (auto &b : driver_mask.bits) {
597 if (b == RTLIL::State::S0) b = RTLIL::State::S1;
598 else if (b == RTLIL::State::S1) b = RTLIL::State::S0;
599 }
600 auto cell = module->addLut(NEW_ID,
601 driver_lut->getPort(ID::A),
602 y_bit,
603 driver_mask);
604 for (auto &bit : cell->connections_.at(ID::A)) {
605 bit.wire = module->wires_.at(remap_name(bit.wire->name));
606 bit2sinks[bit].push_back(cell);
607 }
608 }
609
610 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
611 log("ABC RESULTS: input signals: %8d\n", in_wires);
612 log("ABC RESULTS: output signals: %8d\n", out_wires);
613
614 design->remove(mapped_mod);
615 }
616 //else
617 //{
618 // log("Don't call ABC as there is nothing to map.\n");
619 //}
620 }
621
622 struct Abc9MapPass : public Pass {
623 Abc9MapPass() : Pass("abc9_map", "use ABC9 for technology mapping") { }
624 void help() YS_OVERRIDE
625 {
626 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
627 log("\n");
628 log(" abc9_map [options] [selection]\n");
629 log("\n");
630 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
631 log("library to a target architecture.\n");
632 log("\n");
633 log(" -exe <command>\n");
634 #ifdef ABCEXTERNAL
635 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
636 #else
637 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
638 #endif
639 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
640 log("\n");
641 log(" -script <file>\n");
642 log(" use the specified ABC script file instead of the default script.\n");
643 log("\n");
644 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
645 log(" string is interpreted as the command string to be passed to ABC. The\n");
646 log(" leading plus sign is removed and all commas (,) in the string are\n");
647 log(" replaced with blanks before the string is passed to ABC.\n");
648 log("\n");
649 log(" if no -script parameter is given, the following scripts are used:\n");
650 log("\n");
651 log(" for -lut/-luts (only one LUT size):\n");
652 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT /*"; lutpack {S}"*/).c_str());
653 log("\n");
654 log(" for -lut/-luts (different LUT sizes):\n");
655 log("%s\n", fold_abc9_cmd(ABC_COMMAND_LUT).c_str());
656 log("\n");
657 log(" -fast\n");
658 log(" use different default scripts that are slightly faster (at the cost\n");
659 log(" of output quality):\n");
660 log("\n");
661 log(" for -lut/-luts:\n");
662 log("%s\n", fold_abc9_cmd(ABC_FAST_COMMAND_LUT).c_str());
663 log("\n");
664 log(" -D <picoseconds>\n");
665 log(" set delay target. the string {D} in the default scripts above is\n");
666 log(" replaced by this option when used, and an empty string otherwise\n");
667 log(" (indicating best possible delay).\n");
668 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
669 // log(" default scripts above.\n");
670 log("\n");
671 // log(" -S <num>\n");
672 // log(" maximum number of LUT inputs shared.\n");
673 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
674 // log("\n");
675 log(" -lut <width>\n");
676 log(" generate netlist using luts of (max) the specified width.\n");
677 log("\n");
678 log(" -lut <w1>:<w2>\n");
679 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
680 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
681 log(" the area cost doubles with each additional input bit. the delay cost\n");
682 log(" is still constant for all lut widths.\n");
683 log("\n");
684 log(" -lut <file>\n");
685 log(" pass this file with lut library to ABC.\n");
686 log("\n");
687 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
688 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
689 log(" 2, 3, .. inputs.\n");
690 log("\n");
691 // log(" -dff\n");
692 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
693 // log(" clock domains are automatically partitioned in clock domains and each\n");
694 // log(" domain is passed through ABC independently.\n");
695 // log("\n");
696 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
697 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
698 // log(" cells that belong to the specified clock domain are used.\n");
699 // log("\n");
700 // log(" -keepff\n");
701 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
702 // log(" them, for example for equivalence checking.)\n");
703 // log("\n");
704 log(" -showtmp\n");
705 log(" print the temp dir name in log. usually this is suppressed so that the\n");
706 log(" command output is identical across runs.\n");
707 log("\n");
708 log(" -markgroups\n");
709 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
710 log(" this attribute is a unique integer for each ABC process started. This\n");
711 log(" is useful for debugging the partitioning of clock domains.\n");
712 log("\n");
713 log(" -box <file>\n");
714 log(" pass this file with box library to ABC. Use with -lut.\n");
715 log("\n");
716 log(" -tempdir <dir>\n");
717 log(" use this as the temp dir.\n");
718 log("\n");
719 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
720 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
721 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
722 log("output when passing an ABC script that writes a file. Instead write your full\n");
723 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
724 log("you want to use ABC to convert your design into another format.\n");
725 log("\n");
726 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
727 log("\n");
728 }
729 void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
730 {
731 log_header(design, "Executing ABC9_MAP pass (technology mapping using ABC9).\n");
732
733 #ifdef ABCEXTERNAL
734 std::string exe_file = ABCEXTERNAL;
735 #else
736 std::string exe_file = proc_self_dirname() + "yosys-abc";
737 #endif
738 std::string script_file, clk_str, box_file, lut_file;
739 std::string delay_target, lutin_shared = "-S 1", wire_delay;
740 std::string tempdir_name;
741 bool fast_mode = false;
742 bool show_tempdir = false;
743 bool nomfs = false;
744 vector<int> lut_costs;
745 markgroups = false;
746
747 #if 0
748 cleanup = false;
749 show_tempdir = true;
750 #endif
751
752 #ifdef _WIN32
753 #ifndef ABCEXTERNAL
754 if (!check_file_exists(exe_file + ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
755 exe_file = proc_self_dirname() + "..\\yosys-abc";
756 #endif
757 #endif
758
759 size_t argidx;
760 char pwd [PATH_MAX];
761 if (!getcwd(pwd, sizeof(pwd))) {
762 log_cmd_error("getcwd failed: %s\n", strerror(errno));
763 log_abort();
764 }
765 for (argidx = 1; argidx < args.size(); argidx++) {
766 std::string arg = args[argidx];
767 if (arg == "-exe" && argidx+1 < args.size()) {
768 exe_file = args[++argidx];
769 continue;
770 }
771 if (arg == "-script" && argidx+1 < args.size()) {
772 script_file = args[++argidx];
773 rewrite_filename(script_file);
774 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
775 script_file = std::string(pwd) + "/" + script_file;
776 continue;
777 }
778 if (arg == "-D" && argidx+1 < args.size()) {
779 delay_target = "-D " + args[++argidx];
780 continue;
781 }
782 //if (arg == "-S" && argidx+1 < args.size()) {
783 // lutin_shared = "-S " + args[++argidx];
784 // continue;
785 //}
786 if (arg == "-lut" && argidx+1 < args.size()) {
787 string arg = args[++argidx];
788 if (arg.find_first_not_of("0123456789:") == std::string::npos) {
789 size_t pos = arg.find_first_of(':');
790 int lut_mode = 0, lut_mode2 = 0;
791 if (pos != string::npos) {
792 lut_mode = atoi(arg.substr(0, pos).c_str());
793 lut_mode2 = atoi(arg.substr(pos+1).c_str());
794 } else {
795 lut_mode = atoi(arg.c_str());
796 lut_mode2 = lut_mode;
797 }
798 lut_costs.clear();
799 for (int i = 0; i < lut_mode; i++)
800 lut_costs.push_back(1);
801 for (int i = lut_mode; i < lut_mode2; i++)
802 lut_costs.push_back(2 << (i - lut_mode));
803 }
804 else {
805 lut_file = arg;
806 rewrite_filename(lut_file);
807 if (!lut_file.empty() && !is_absolute_path(lut_file) && lut_file[0] != '+')
808 lut_file = std::string(pwd) + "/" + lut_file;
809 }
810 continue;
811 }
812 if (arg == "-luts" && argidx+1 < args.size()) {
813 lut_costs.clear();
814 for (auto &tok : split_tokens(args[++argidx], ",")) {
815 auto parts = split_tokens(tok, ":");
816 if (GetSize(parts) == 0 && !lut_costs.empty())
817 lut_costs.push_back(lut_costs.back());
818 else if (GetSize(parts) == 1)
819 lut_costs.push_back(atoi(parts.at(0).c_str()));
820 else if (GetSize(parts) == 2)
821 while (GetSize(lut_costs) < atoi(parts.at(0).c_str()))
822 lut_costs.push_back(atoi(parts.at(1).c_str()));
823 else
824 log_cmd_error("Invalid -luts syntax.\n");
825 }
826 continue;
827 }
828 if (arg == "-fast") {
829 fast_mode = true;
830 continue;
831 }
832 if (arg == "-showtmp") {
833 show_tempdir = true;
834 continue;
835 }
836 if (arg == "-markgroups") {
837 markgroups = true;
838 continue;
839 }
840 if (arg == "-box" && argidx+1 < args.size()) {
841 box_file = args[++argidx];
842 continue;
843 }
844 if (arg == "-W" && argidx+1 < args.size()) {
845 wire_delay = "-W " + args[++argidx];
846 continue;
847 }
848 if (arg == "-nomfs") {
849 nomfs = true;
850 continue;
851 }
852 if (arg == "-tempdir" && argidx+1 < args.size()) {
853 tempdir_name = args[++argidx];
854 continue;
855 }
856 break;
857 }
858 extra_args(args, argidx, design);
859
860 // ABC expects a box file for XAIG
861 if (box_file.empty())
862 box_file = "+/dummy.box";
863
864 rewrite_filename(box_file);
865 if (!box_file.empty() && !is_absolute_path(box_file) && box_file[0] != '+')
866 box_file = std::string(pwd) + "/" + box_file;
867
868 if (tempdir_name.empty())
869 log_cmd_error("abc9_map '-tempdir' option is mandatory.\n");
870
871
872 for (auto mod : design->selected_modules())
873 {
874 if (mod->processes.size() > 0) {
875 log("Skipping module %s as it contains processes.\n", log_id(mod));
876 continue;
877 }
878
879 abc9_module(design, mod, script_file, exe_file, lut_costs,
880 delay_target, lutin_shared, fast_mode, show_tempdir,
881 box_file, lut_file, wire_delay, nomfs, tempdir_name);
882 }
883 }
884 } Abc9MapPass;
885
886 PRIVATE_NAMESPACE_END