2 * yosys -- Yosys Open SYnthesis Suite
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * 2019 Eddie Hung <eddie@fpgeh.com>
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.
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.
22 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
23 // http://www.eecs.berkeley.edu/~alanmi/abc/
26 // Based on &flow3 - better QoR but more experimental
27 #define ABC_COMMAND_LUT "&st; &ps -l; "/*"&sweep -v;"*/" &scorr; " \
28 "&st; &if {W}; &save; &st; &syn2; &if {W}; &save; &load; "\
29 "&st; &if -g -K 6; &dch -f; &if {W}; &save; &load; "\
30 "&st; &if -g -K 6; &synch2; &if {W}; &save; &load"
32 #define ABC_COMMAND_LUT "&st; &scorr; &sweep; &dc2; &st; &dch -f; &ps -l; &if {W} {D} -v; "/*"&mfs; "*/"&ps -l"
36 #define ABC_FAST_COMMAND_LUT "&st; &retime; &if {W}"
38 #include "kernel/register.h"
39 #include "kernel/sigtools.h"
40 #include "kernel/celltypes.h"
41 #include "kernel/cost.h"
42 #include "kernel/log.h"
55 #include "frontends/aiger/aigerparse.h"
58 extern "C" int Abc_RealMain(int argc
, char *argv
[]);
62 PRIVATE_NAMESPACE_BEGIN
67 RTLIL::Module
*module
;
69 bool clk_polarity
, en_polarity
;
70 RTLIL::SigSpec clk_sig
, en_sig
;
72 std::string
remap_name(RTLIL::IdString abc_name
)
74 std::stringstream sstr
;
75 sstr
<< "$abc$" << map_autoidx
<< "$" << abc_name
.substr(1);
79 void handle_loops(RTLIL::Design
*design
)
81 Pass::call(design
, "scc -set_attr abc_scc_id {}");
83 // For every unique SCC found, (arbitrarily) find the first
84 // cell in the component, and select (and mark) all its output
86 pool
<RTLIL::Const
> ids_seen
;
87 for (auto cell
: module
->cells()) {
88 auto it
= cell
->attributes
.find("\\abc_scc_id");
89 if (it
!= cell
->attributes
.end()) {
90 auto r
= ids_seen
.insert(it
->second
);
92 for (auto &c
: cell
->connections_
) {
93 if (c
.second
.is_fully_const()) continue;
94 if (cell
->output(c
.first
)) {
95 SigBit b
= c
.second
.as_bit();
97 log_assert(!w
->port_input
);
99 w
= module
->wire(stringf("%s.abci", log_id(w
->name
)));
101 w
= module
->addWire(stringf("%s.abci", log_id(b
.wire
->name
)), GetSize(b
.wire
));
102 log_assert(b
.offset
< GetSize(w
));
103 w
->port_output
= true;
104 w
->set_bool_attribute("\\abc_scc_break");
105 module
->swap_names(b
.wire
, w
);
106 c
.second
= RTLIL::SigBit(w
, b
.offset
);
110 cell
->attributes
.erase(it
);
112 RTLIL::Module
* box_module
= design
->module(cell
->type
);
114 auto jt
= box_module
->attributes
.find("\\abc_scc_break");
115 if (jt
!= box_module
->attributes
.end()) {
116 auto it
= cell
->connections_
.find(RTLIL::escape_id(jt
->second
.decode_string()));
117 log_assert(it
!= cell
->connections_
.end());
119 SigBit b
= cell
->getPort(RTLIL::escape_id(jt
->second
.decode_string()));
121 log_assert(!w
->port_output
);
122 w
->port_output
= true;
123 w
->set_bool_attribute("\\abc_scc_break");
124 w
= module
->wire(stringf("%s.abci", log_id(w
->name
)));
126 w
= module
->addWire(stringf("%s.abci", log_id(b
.wire
->name
)), GetSize(b
.wire
));
127 log_assert(b
.offset
< GetSize(w
));
128 w
->port_input
= true;
129 c
.second
= RTLIL::SigBit(w
, b
.offset
);
134 module
->fixup_ports();
137 std::string
add_echos_to_abc_cmd(std::string str
)
139 std::string new_str
, token
;
140 for (size_t i
= 0; i
< str
.size(); i
++) {
143 while (i
+1 < str
.size() && str
[i
+1] == ' ')
145 new_str
+= "echo + " + token
+ " " + token
+ " ";
150 if (!token
.empty()) {
151 if (!new_str
.empty())
152 new_str
+= "echo + " + token
+ "; ";
159 std::string
fold_abc_cmd(std::string str
)
161 std::string token
, new_str
= " ";
162 int char_counter
= 10;
164 for (size_t i
= 0; i
<= str
.size(); i
++) {
167 if (i
== str
.size() || str
[i
] == ';') {
168 if (char_counter
+ token
.size() > 75)
169 new_str
+= "\n ", char_counter
= 14;
170 new_str
+= token
, char_counter
+= token
.size();
178 std::string
replace_tempdir(std::string text
, std::string tempdir_name
, bool show_tempdir
)
184 size_t pos
= text
.find(tempdir_name
);
185 if (pos
== std::string::npos
)
187 text
= text
.substr(0, pos
) + "<abc-temp-dir>" + text
.substr(pos
+ GetSize(tempdir_name
));
190 std::string selfdir_name
= proc_self_dirname();
191 if (selfdir_name
!= "/") {
193 size_t pos
= text
.find(selfdir_name
);
194 if (pos
== std::string::npos
)
196 text
= text
.substr(0, pos
) + "<yosys-exe-dir>/" + text
.substr(pos
+ GetSize(selfdir_name
));
203 struct abc_output_filter
206 int escape_seq_state
;
208 std::string tempdir_name
;
211 abc_output_filter(std::string tempdir_name
, bool show_tempdir
) : tempdir_name(tempdir_name
), show_tempdir(show_tempdir
)
214 escape_seq_state
= 0;
217 void next_char(char ch
)
219 if (escape_seq_state
== 0 && ch
== '\033') {
220 escape_seq_state
= 1;
223 if (escape_seq_state
== 1) {
224 escape_seq_state
= ch
== '[' ? 2 : 0;
227 if (escape_seq_state
== 2) {
228 if ((ch
< '0' || '9' < ch
) && ch
!= ';')
229 escape_seq_state
= 0;
232 escape_seq_state
= 0;
238 log("ABC: %s\n", replace_tempdir(linebuf
, tempdir_name
, show_tempdir
).c_str());
239 got_cr
= false, linebuf
.clear();
243 got_cr
= false, linebuf
.clear();
247 void next_line(const std::string
&line
)
250 //if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
251 // log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
252 // pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
253 // po, po_map.count(po) ? po_map.at(po).c_str() : "???");
262 void abc9_module(RTLIL::Design
*design
, RTLIL::Module
*current_module
, std::string script_file
, std::string exe_file
,
263 bool cleanup
, vector
<int> lut_costs
, bool dff_mode
, std::string clk_str
,
264 bool /*keepff*/, std::string delay_target
, std::string
/*lutin_shared*/, bool fast_mode
,
265 bool show_tempdir
, std::string box_file
, std::string lut_file
,
266 std::string wire_delay
)
268 module
= current_module
;
269 map_autoidx
= autoidx
++;
274 clk_sig
= RTLIL::SigSpec();
277 en_sig
= RTLIL::SigSpec();
280 if (!clk_str
.empty() && clk_str
!= "$")
282 if (clk_str
.find(',') != std::string::npos
) {
283 int pos
= clk_str
.find(',');
284 std::string en_str
= clk_str
.substr(pos
+1);
285 clk_str
= clk_str
.substr(0, pos
);
286 if (en_str
[0] == '!') {
288 en_str
= en_str
.substr(1);
290 if (module
->wires_
.count(RTLIL::escape_id(en_str
)) != 0)
291 en_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(en_str
)), 0));
293 if (clk_str
[0] == '!') {
294 clk_polarity
= false;
295 clk_str
= clk_str
.substr(1);
297 if (module
->wires_
.count(RTLIL::escape_id(clk_str
)) != 0)
298 clk_sig
= assign_map(RTLIL::SigSpec(module
->wires_
.at(RTLIL::escape_id(clk_str
)), 0));
301 if (dff_mode
&& clk_sig
.empty())
302 log_cmd_error("Clock domain %s not found.\n", clk_str
.c_str());
304 std::string tempdir_name
= "/tmp/yosys-abc-XXXXXX";
306 tempdir_name
[0] = tempdir_name
[4] = '_';
307 tempdir_name
= make_temp_dir(tempdir_name
);
308 log_header(design
, "Extracting gate netlist of module `%s' to `%s/input.xaig'..\n",
309 module
->name
.c_str(), replace_tempdir(tempdir_name
, tempdir_name
, show_tempdir
).c_str());
311 std::string abc_script
;
313 if (!lut_costs
.empty()) {
314 abc_script
+= stringf("read_lut %s/lutdefs.txt; ", tempdir_name
.c_str());
315 if (!box_file
.empty())
316 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
319 if (!lut_file
.empty()) {
320 abc_script
+= stringf("read_lut %s; ", lut_file
.c_str());
321 if (!box_file
.empty())
322 abc_script
+= stringf("read_box -v %s; ", box_file
.c_str());
327 abc_script
+= stringf("&read %s/input.xaig; &ps; ", tempdir_name
.c_str());
329 if (!script_file
.empty()) {
330 if (script_file
[0] == '+') {
331 for (size_t i
= 1; i
< script_file
.size(); i
++)
332 if (script_file
[i
] == '\'')
333 abc_script
+= "'\\''";
334 else if (script_file
[i
] == ',')
337 abc_script
+= script_file
[i
];
339 abc_script
+= stringf("source %s", script_file
.c_str());
340 } else if (!lut_costs
.empty() || !lut_file
.empty()) {
341 //bool all_luts_cost_same = true;
342 //for (int this_cost : lut_costs)
343 // if (this_cost != lut_costs.front())
344 // all_luts_cost_same = false;
345 abc_script
+= fast_mode
? ABC_FAST_COMMAND_LUT
: ABC_COMMAND_LUT
;
346 //if (all_luts_cost_same && !fast_mode)
347 // abc_script += "; lutpack {S}";
351 //if (script_file.empty() && !delay_target.empty())
352 // for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
353 // abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
355 for (size_t pos
= abc_script
.find("{D}"); pos
!= std::string::npos
; pos
= abc_script
.find("{D}", pos
))
356 abc_script
= abc_script
.substr(0, pos
) + delay_target
+ abc_script
.substr(pos
+3);
358 //for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
359 // abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
361 for (size_t pos
= abc_script
.find("{W}"); pos
!= std::string::npos
; pos
= abc_script
.find("{W}", pos
))
362 abc_script
= abc_script
.substr(0, pos
) + wire_delay
+ abc_script
.substr(pos
+3);
364 abc_script
+= stringf("; &write %s/output.aig", tempdir_name
.c_str());
365 abc_script
= add_echos_to_abc_cmd(abc_script
);
367 for (size_t i
= 0; i
+1 < abc_script
.size(); i
++)
368 if (abc_script
[i
] == ';' && abc_script
[i
+1] == ' ')
369 abc_script
[i
+1] = '\n';
371 FILE *f
= fopen(stringf("%s/abc.script", tempdir_name
.c_str()).c_str(), "wt");
372 fprintf(f
, "%s\n", abc_script
.c_str());
375 if (dff_mode
|| !clk_str
.empty())
377 if (clk_sig
.size() == 0)
378 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str
.empty() ? "" : " matching");
380 log("Found%s %s clock domain: %s", clk_str
.empty() ? "" : " matching", clk_polarity
? "posedge" : "negedge", log_signal(clk_sig
));
381 if (en_sig
.size() != 0)
382 log(", enabled by %s%s", en_polarity
? "" : "!", log_signal(en_sig
));
387 bool count_output
= false;
388 for (auto port_name
: module
->ports
) {
389 RTLIL::Wire
*port_wire
= module
->wire(port_name
);
390 log_assert(port_wire
);
391 if (port_wire
->port_output
) {
401 design
->selection_stack
.emplace_back(false);
402 RTLIL::Selection
& sel
= design
->selection_stack
.back();
405 Pass::call(design
, "aigmap");
407 handle_loops(design
);
409 //log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
410 // count_gates, GetSize(signal_list), count_input, count_output);
412 Pass::call(design
, stringf("write_xaiger -map %s/input.sym %s/input.xaig", tempdir_name
.c_str(), tempdir_name
.c_str()));
417 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.xaig");
420 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
421 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
422 log_assert(!design
->module("$__abc9__"));
424 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
425 reader
.parse_xaiger();
428 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
429 design
->remove(design
->module("$__abc9__"));
432 design
->selection_stack
.pop_back();
434 // Now 'unexpose' those wires by undoing
435 // the expose operation -- remove them from PO/PI
436 // and re-connecting them back together
437 for (auto wire
: module
->wires()) {
438 auto it
= wire
->attributes
.find("\\abc_scc_break");
439 if (it
!= wire
->attributes
.end()) {
440 wire
->attributes
.erase(it
);
441 log_assert(wire
->port_output
);
442 wire
->port_output
= false;
443 RTLIL::Wire
*i_wire
= module
->wire(wire
->name
.str() + ".abci");
445 log_assert(i_wire
->port_input
);
446 i_wire
->port_input
= false;
447 module
->connect(i_wire
, wire
);
450 module
->fixup_ports();
453 log_header(design
, "Executing ABC9.\n");
455 if (!lut_costs
.empty()) {
456 buffer
= stringf("%s/lutdefs.txt", tempdir_name
.c_str());
457 f
= fopen(buffer
.c_str(), "wt");
459 log_error("Opening %s for writing failed: %s\n", buffer
.c_str(), strerror(errno
));
460 for (int i
= 0; i
< GetSize(lut_costs
); i
++)
461 fprintf(f
, "%d %d.00 1.00\n", i
+1, lut_costs
.at(i
));
465 buffer
= stringf("%s -s -f %s/abc.script 2>&1", exe_file
.c_str(), tempdir_name
.c_str());
466 log("Running ABC command: %s\n", replace_tempdir(buffer
, tempdir_name
, show_tempdir
).c_str());
468 #ifndef YOSYS_LINK_ABC
469 abc_output_filter
filt(tempdir_name
, show_tempdir
);
470 int ret
= run_command(buffer
, std::bind(&abc_output_filter::next_line
, filt
, std::placeholders::_1
));
472 // These needs to be mutable, supposedly due to getopt
474 string tmp_script_name
= stringf("%s/abc.script", tempdir_name
.c_str());
475 abc_argv
[0] = strdup(exe_file
.c_str());
476 abc_argv
[1] = strdup("-s");
477 abc_argv
[2] = strdup("-f");
478 abc_argv
[3] = strdup(tmp_script_name
.c_str());
480 int ret
= Abc_RealMain(4, abc_argv
);
487 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer
.c_str(), ret
);
489 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "output.aig");
492 log_error("Can't open ABC output file `%s'.\n", buffer
.c_str());
494 buffer
= stringf("%s/%s", tempdir_name
.c_str(), "input.sym");
495 log_assert(!design
->module("$__abc9__"));
496 AigerReader
reader(design
, ifs
, "$__abc9__", "" /* clk_name */, buffer
.c_str() /* map_filename */, true /* wideports */);
497 reader
.parse_xaiger();
501 Pass::call(design
, stringf("write_verilog -noexpr -norename"));
504 log_header(design
, "Re-integrating ABC9 results.\n");
505 RTLIL::Module
*mapped_mod
= design
->module("$__abc9__");
506 if (mapped_mod
== NULL
)
507 log_error("ABC output file does not contain a module `$__abc9__'.\n");
509 pool
<RTLIL::SigBit
> output_bits
;
510 for (auto &it
: mapped_mod
->wires_
) {
511 RTLIL::Wire
*w
= it
.second
;
512 RTLIL::Wire
*remap_wire
= module
->addWire(remap_name(w
->name
), GetSize(w
));
513 if (markgroups
) remap_wire
->attributes
["\\abcgroup"] = map_autoidx
;
514 if (w
->port_output
) {
515 RTLIL::Wire
*wire
= module
->wire(w
->name
);
517 for (int i
= 0; i
< GetSize(w
); i
++)
518 output_bits
.insert({wire
, i
});
522 for (auto &it
: module
->connections_
) {
523 auto &signal
= it
.first
;
524 auto bits
= signal
.bits();
526 if (output_bits
.count(b
))
527 b
= module
->addWire(NEW_ID
);
528 signal
= std::move(bits
);
531 vector
<RTLIL::Cell
*> boxes
;
532 for (auto it
= module
->cells_
.begin(); it
!= module
->cells_
.end(); ) {
533 RTLIL::Cell
* cell
= it
->second
;
534 if (cell
->type
.in("$_AND_", "$_NOT_", "$__ABC_FF_")) {
535 it
= module
->remove(it
);
538 RTLIL::Module
* box_module
= design
->module(cell
->type
);
539 if (box_module
&& box_module
->attributes
.count("\\abc_box_id"))
540 boxes
.emplace_back(it
->second
);
544 std::map
<std::string
, int> cell_stats
;
545 for (auto c
: mapped_mod
->cells())
547 RTLIL::Cell
*cell
= nullptr;
548 if (c
->type
== "$_NOT_") {
549 RTLIL::SigBit a_bit
= c
->getPort("\\A").as_bit();
550 RTLIL::SigBit y_bit
= c
->getPort("\\Y").as_bit();
552 c
->setPort("\\Y", module
->addWire(NEW_ID
));
553 RTLIL::Wire
*wire
= module
->wire(remap_name(y_bit
.wire
->name
));
555 module
->connect(RTLIL::SigBit(wire
, y_bit
.offset
), RTLIL::S1
);
557 else if (!lut_costs
.empty() || !lut_file
.empty()) {
558 RTLIL::Cell
* driving_lut
= nullptr;
559 // ABC can return NOT gates that drive POs
560 if (!a_bit
.wire
->port_input
) {
561 // If it's not a NOT gate that that comes from a PI directly,
562 // find the driving LUT and clone that to guarantee that we won't
563 // increase the max logic depth
564 // (TODO: Optimise by not cloning unless will increase depth)
565 RTLIL::IdString driver_name
;
566 if (GetSize(a_bit
.wire
) == 1)
567 driver_name
= stringf("%s$lut", a_bit
.wire
->name
.c_str());
569 driver_name
= stringf("%s[%d]$lut", a_bit
.wire
->name
.c_str(), a_bit
.offset
);
570 driving_lut
= mapped_mod
->cell(driver_name
);
574 // If a driver couldn't be found (could be from PI,
575 // or from a box) then implement using a LUT
576 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
577 RTLIL::SigBit(module
->wires_
[remap_name(a_bit
.wire
->name
)], a_bit
.offset
),
578 RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
),
582 auto driver_a
= driving_lut
->getPort("\\A").chunks();
583 for (auto &chunk
: driver_a
)
584 chunk
.wire
= module
->wires_
[remap_name(chunk
.wire
->name
)];
585 RTLIL::Const driver_lut
= driving_lut
->getParam("\\LUT");
586 for (auto &b
: driver_lut
.bits
) {
587 if (b
== RTLIL::State::S0
) b
= RTLIL::State::S1
;
588 else if (b
== RTLIL::State::S1
) b
= RTLIL::State::S0
;
590 cell
= module
->addLut(remap_name(stringf("%s$lut", c
->name
.c_str())),
592 RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
),
597 cell
= module
->addCell(remap_name(c
->name
), "$_NOT_");
598 cell
->setPort("\\A", RTLIL::SigBit(module
->wires_
[remap_name(a_bit
.wire
->name
)], a_bit
.offset
));
599 cell
->setPort("\\Y", RTLIL::SigBit(module
->wires_
[remap_name(y_bit
.wire
->name
)], y_bit
.offset
));
600 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
602 if (cell
&& markgroups
) cell
->attributes
["\\abcgroup"] = map_autoidx
;
605 cell_stats
[RTLIL::unescape_id(c
->type
)]++;
607 RTLIL::Cell
*existing_cell
= nullptr;
608 if (c
->type
== "$lut") {
609 if (GetSize(c
->getPort("\\A")) == 1 && c
->getParam("\\LUT").as_int() == 2) {
610 SigSpec my_a
= module
->wires_
[remap_name(c
->getPort("\\A").as_wire()->name
)];
611 SigSpec my_y
= module
->wires_
[remap_name(c
->getPort("\\Y").as_wire()->name
)];
612 module
->connect(my_y
, my_a
);
613 if (markgroups
) c
->attributes
["\\abcgroup"] = map_autoidx
;
616 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
619 existing_cell
= module
->cell(c
->name
);
620 cell
= module
->addCell(remap_name(c
->name
), c
->type
);
621 module
->swap_names(cell
, existing_cell
);
624 if (markgroups
) cell
->attributes
["\\abcgroup"] = map_autoidx
;
626 cell
->parameters
= existing_cell
->parameters
;
627 cell
->attributes
= existing_cell
->attributes
;
630 cell
->parameters
= c
->parameters
;
631 cell
->attributes
= c
->attributes
;
633 for (auto &conn
: c
->connections()) {
634 RTLIL::SigSpec newsig
;
635 for (auto c
: conn
.second
.chunks()) {
638 //log_assert(c.width == 1);
640 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
643 cell
->setPort(conn
.first
, newsig
);
647 for (auto cell
: boxes
)
648 module
->remove(cell
);
650 // Copy connections (and rename) from mapped_mod to module
651 for (auto conn
: mapped_mod
->connections()) {
652 if (!conn
.first
.is_fully_const()) {
653 auto chunks
= conn
.first
.chunks();
654 for (auto &c
: chunks
)
655 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
656 conn
.first
= std::move(chunks
);
658 if (!conn
.second
.is_fully_const()) {
659 auto chunks
= conn
.second
.chunks();
660 for (auto &c
: chunks
)
662 c
.wire
= module
->wires_
[remap_name(c
.wire
->name
)];
663 conn
.second
= std::move(chunks
);
665 module
->connect(conn
);
668 for (auto &it
: cell_stats
)
669 log("ABC RESULTS: %15s cells: %8d\n", it
.first
.c_str(), it
.second
);
670 int in_wires
= 0, out_wires
= 0;
672 // Stitch in mapped_mod's inputs/outputs into module
673 for (auto &it
: mapped_mod
->wires_
) {
674 RTLIL::Wire
*w
= it
.second
;
675 if (!w
->port_input
&& !w
->port_output
)
677 RTLIL::Wire
*wire
= module
->wire(w
->name
);
679 RTLIL::Wire
*remap_wire
= module
->wire(remap_name(w
->name
));
680 RTLIL::SigSpec signal
= RTLIL::SigSpec(wire
, 0, GetSize(remap_wire
));
681 log_assert(GetSize(signal
) >= GetSize(remap_wire
));
683 log_assert(w
->port_input
|| w
->port_output
);
686 conn
.first
= remap_wire
;
687 conn
.second
= signal
;
689 module
->connect(conn
);
691 if (w
->port_output
) {
693 conn
.second
= remap_wire
;
695 module
->connect(conn
);
699 //log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
700 log("ABC RESULTS: input signals: %8d\n", in_wires
);
701 log("ABC RESULTS: output signals: %8d\n", out_wires
);
703 design
->remove(mapped_mod
);
707 log("Don't call ABC as there is nothing to map.\n");
712 log("Removing temp directory.\n");
713 remove_directory(tempdir_name
);
719 struct Abc9Pass
: public Pass
{
720 Abc9Pass() : Pass("abc9", "use ABC9 for technology mapping") { }
721 void help() YS_OVERRIDE
723 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
725 log(" abc9 [options] [selection]\n");
727 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
728 log("library to a target architecture.\n");
730 log(" -exe <command>\n");
732 log(" use the specified command instead of \"" ABCEXTERNAL
"\" to execute ABC.\n");
734 log(" use the specified command instead of \"<yosys-bindir>/yosys-abc\" to execute ABC.\n");
736 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
738 log(" -script <file>\n");
739 log(" use the specified ABC script file instead of the default script.\n");
741 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
742 log(" string is interpreted as the command string to be passed to ABC. The\n");
743 log(" leading plus sign is removed and all commas (,) in the string are\n");
744 log(" replaced with blanks before the string is passed to ABC.\n");
746 log(" if no -script parameter is given, the following scripts are used:\n");
748 log(" for -lut/-luts (only one LUT size):\n");
749 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
/*"; lutpack {S}"*/).c_str());
751 log(" for -lut/-luts (different LUT sizes):\n");
752 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT
).c_str());
755 log(" use different default scripts that are slightly faster (at the cost\n");
756 log(" of output quality):\n");
758 log(" for -lut/-luts:\n");
759 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT
).c_str());
761 log(" -D <picoseconds>\n");
762 log(" set delay target. the string {D} in the default scripts above is\n");
763 log(" replaced by this option when used, and an empty string otherwise\n");
764 log(" (indicating best possible delay).\n");
765 // log(" This also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
766 // log(" default scripts above.\n");
768 // log(" -S <num>\n");
769 // log(" maximum number of LUT inputs shared.\n");
770 // log(" (replaces {S} in the default scripts above, default: -S 1)\n");
772 log(" -lut <width>\n");
773 log(" generate netlist using luts of (max) the specified width.\n");
775 log(" -lut <w1>:<w2>\n");
776 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
777 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
778 log(" the area cost doubles with each additional input bit. the delay cost\n");
779 log(" is still constant for all lut widths.\n");
781 log(" -lut <file>\n");
782 log(" pass this file with lut library to ABC.\n");
784 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
785 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
786 log(" 2, 3, .. inputs.\n");
789 // log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
790 // log(" clock domains are automatically partitioned in clock domains and each\n");
791 // log(" domain is passed through ABC independently.\n");
793 // log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
794 // log(" use only the specified clock domain. this is like -dff, but only FF\n");
795 // log(" cells that belong to the specified clock domain are used.\n");
797 // log(" -keepff\n");
798 // log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
799 // log(" them, for example for equivalence checking.)\n");
801 log(" -nocleanup\n");
802 log(" when this option is used, the temporary files created by this pass\n");
803 log(" are not removed. this is useful for debugging.\n");
806 log(" print the temp dir name in log. usually this is suppressed so that the\n");
807 log(" command output is identical across runs.\n");
809 log(" -markgroups\n");
810 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
811 log(" this attribute is a unique integer for each ABC process started. This\n");
812 log(" is useful for debugging the partitioning of clock domains.\n");
814 log(" -box <file>\n");
815 log(" pass this file with box library to ABC. Use with -lut.\n");
817 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
818 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
819 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
820 log("output when passing an ABC script that writes a file. Instead write your full\n");
821 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
822 log("you want to use ABC to convert your design into another format.\n");
824 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
827 void execute(std::vector
<std::string
> args
, RTLIL::Design
*design
) YS_OVERRIDE
829 log_header(design
, "Executing ABC9 pass (technology mapping using ABC9).\n");
835 std::string exe_file
= ABCEXTERNAL
;
837 std::string exe_file
= proc_self_dirname() + "yosys-abc";
839 std::string script_file
, clk_str
, box_file
, lut_file
;
840 std::string delay_target
, lutin_shared
= "-S 1", wire_delay
;
841 bool fast_mode
= false, dff_mode
= false, keepff
= false, cleanup
= true;
842 bool show_tempdir
= false;
843 vector
<int> lut_costs
;
853 if (!check_file_exists(exe_file
+ ".exe") && check_file_exists(proc_self_dirname() + "..\\yosys-abc.exe"))
854 exe_file
= proc_self_dirname() + "..\\yosys-abc";
860 if (!getcwd(pwd
, sizeof(pwd
))) {
861 log_cmd_error("getcwd failed: %s\n", strerror(errno
));
864 for (argidx
= 1; argidx
< args
.size(); argidx
++) {
865 std::string arg
= args
[argidx
];
866 if (arg
== "-exe" && argidx
+1 < args
.size()) {
867 exe_file
= args
[++argidx
];
870 if (arg
== "-script" && argidx
+1 < args
.size()) {
871 script_file
= args
[++argidx
];
872 rewrite_filename(script_file
);
873 if (!script_file
.empty() && !is_absolute_path(script_file
) && script_file
[0] != '+')
874 script_file
= std::string(pwd
) + "/" + script_file
;
877 if (arg
== "-D" && argidx
+1 < args
.size()) {
878 delay_target
= "-D " + args
[++argidx
];
881 //if (arg == "-S" && argidx+1 < args.size()) {
882 // lutin_shared = "-S " + args[++argidx];
885 if (arg
== "-lut" && argidx
+1 < args
.size()) {
886 string arg
= args
[++argidx
];
887 size_t pos
= arg
.find_first_of(':');
888 int lut_mode
= 0, lut_mode2
= 0;
889 if (pos
!= string::npos
) {
890 lut_mode
= atoi(arg
.substr(0, pos
).c_str());
891 lut_mode2
= atoi(arg
.substr(pos
+1).c_str());
893 pos
= arg
.find_first_of('.');
894 if (pos
!= string::npos
) {
896 rewrite_filename(lut_file
);
897 if (!lut_file
.empty() && !is_absolute_path(lut_file
))
898 lut_file
= std::string(pwd
) + "/" + lut_file
;
901 lut_mode
= atoi(arg
.c_str());
902 lut_mode2
= lut_mode
;
906 for (int i
= 0; i
< lut_mode
; i
++)
907 lut_costs
.push_back(1);
908 for (int i
= lut_mode
; i
< lut_mode2
; i
++)
909 lut_costs
.push_back(2 << (i
- lut_mode
));
912 if (arg
== "-luts" && argidx
+1 < args
.size()) {
914 for (auto &tok
: split_tokens(args
[++argidx
], ",")) {
915 auto parts
= split_tokens(tok
, ":");
916 if (GetSize(parts
) == 0 && !lut_costs
.empty())
917 lut_costs
.push_back(lut_costs
.back());
918 else if (GetSize(parts
) == 1)
919 lut_costs
.push_back(atoi(parts
.at(0).c_str()));
920 else if (GetSize(parts
) == 2)
921 while (GetSize(lut_costs
) < atoi(parts
.at(0).c_str()))
922 lut_costs
.push_back(atoi(parts
.at(1).c_str()));
924 log_cmd_error("Invalid -luts syntax.\n");
928 if (arg
== "-fast") {
932 //if (arg == "-dff") {
936 //if (arg == "-clk" && argidx+1 < args.size()) {
937 // clk_str = args[++argidx];
941 //if (arg == "-keepff") {
945 if (arg
== "-nocleanup") {
949 if (arg
== "-showtmp") {
953 if (arg
== "-markgroups") {
957 if (arg
== "-box" && argidx
+1 < args
.size()) {
958 box_file
= args
[++argidx
];
959 rewrite_filename(box_file
);
960 if (!box_file
.empty() && !is_absolute_path(box_file
))
961 box_file
= std::string(pwd
) + "/" + box_file
;
964 if (arg
== "-W" && argidx
+1 < args
.size()) {
965 wire_delay
= "-W " + args
[++argidx
];
970 extra_args(args
, argidx
, design
);
972 for (auto mod
: design
->selected_modules())
974 if (mod
->attributes
.count("\\abc_box_id"))
977 if (mod
->processes
.size() > 0) {
978 log("Skipping module %s as it contains processes.\n", log_id(mod
));
984 if (!dff_mode
|| !clk_str
.empty()) {
985 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, dff_mode
, clk_str
, keepff
,
986 delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
987 box_file
, lut_file
, wire_delay
);
991 CellTypes
ct(design
);
993 std::vector
<RTLIL::Cell
*> all_cells
= mod
->selected_cells();
994 std::set
<RTLIL::Cell
*> unassigned_cells(all_cells
.begin(), all_cells
.end());
996 std::set
<RTLIL::Cell
*> expand_queue
, next_expand_queue
;
997 std::set
<RTLIL::Cell
*> expand_queue_up
, next_expand_queue_up
;
998 std::set
<RTLIL::Cell
*> expand_queue_down
, next_expand_queue_down
;
1000 typedef tuple
<bool, RTLIL::SigSpec
, bool, RTLIL::SigSpec
> clkdomain_t
;
1001 std::map
<clkdomain_t
, std::vector
<RTLIL::Cell
*>> assigned_cells
;
1002 std::map
<RTLIL::Cell
*, clkdomain_t
> assigned_cells_reverse
;
1004 std::map
<RTLIL::Cell
*, std::set
<RTLIL::SigBit
>> cell_to_bit
, cell_to_bit_up
, cell_to_bit_down
;
1005 std::map
<RTLIL::SigBit
, std::set
<RTLIL::Cell
*>> bit_to_cell
, bit_to_cell_up
, bit_to_cell_down
;
1007 for (auto cell
: all_cells
)
1011 for (auto &conn
: cell
->connections())
1012 for (auto bit
: conn
.second
) {
1013 bit
= assign_map(bit
);
1014 if (bit
.wire
!= nullptr) {
1015 cell_to_bit
[cell
].insert(bit
);
1016 bit_to_cell
[bit
].insert(cell
);
1017 if (ct
.cell_input(cell
->type
, conn
.first
)) {
1018 cell_to_bit_up
[cell
].insert(bit
);
1019 bit_to_cell_down
[bit
].insert(cell
);
1021 if (ct
.cell_output(cell
->type
, conn
.first
)) {
1022 cell_to_bit_down
[cell
].insert(bit
);
1023 bit_to_cell_up
[bit
].insert(cell
);
1028 if (cell
->type
== "$_DFF_N_" || cell
->type
== "$_DFF_P_")
1030 key
= clkdomain_t(cell
->type
== "$_DFF_P_", assign_map(cell
->getPort("\\C")), true, RTLIL::SigSpec());
1033 if (cell
->type
== "$_DFFE_NN_" || cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_")
1035 bool this_clk_pol
= cell
->type
== "$_DFFE_PN_" || cell
->type
== "$_DFFE_PP_";
1036 bool this_en_pol
= cell
->type
== "$_DFFE_NP_" || cell
->type
== "$_DFFE_PP_";
1037 key
= clkdomain_t(this_clk_pol
, assign_map(cell
->getPort("\\C")), this_en_pol
, assign_map(cell
->getPort("\\E")));
1042 unassigned_cells
.erase(cell
);
1043 expand_queue
.insert(cell
);
1044 expand_queue_up
.insert(cell
);
1045 expand_queue_down
.insert(cell
);
1047 assigned_cells
[key
].push_back(cell
);
1048 assigned_cells_reverse
[cell
] = key
;
1051 while (!expand_queue_up
.empty() || !expand_queue_down
.empty())
1053 if (!expand_queue_up
.empty())
1055 RTLIL::Cell
*cell
= *expand_queue_up
.begin();
1056 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1057 expand_queue_up
.erase(cell
);
1059 for (auto bit
: cell_to_bit_up
[cell
])
1060 for (auto c
: bit_to_cell_up
[bit
])
1061 if (unassigned_cells
.count(c
)) {
1062 unassigned_cells
.erase(c
);
1063 next_expand_queue_up
.insert(c
);
1064 assigned_cells
[key
].push_back(c
);
1065 assigned_cells_reverse
[c
] = key
;
1066 expand_queue
.insert(c
);
1070 if (!expand_queue_down
.empty())
1072 RTLIL::Cell
*cell
= *expand_queue_down
.begin();
1073 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1074 expand_queue_down
.erase(cell
);
1076 for (auto bit
: cell_to_bit_down
[cell
])
1077 for (auto c
: bit_to_cell_down
[bit
])
1078 if (unassigned_cells
.count(c
)) {
1079 unassigned_cells
.erase(c
);
1080 next_expand_queue_up
.insert(c
);
1081 assigned_cells
[key
].push_back(c
);
1082 assigned_cells_reverse
[c
] = key
;
1083 expand_queue
.insert(c
);
1087 if (expand_queue_up
.empty() && expand_queue_down
.empty()) {
1088 expand_queue_up
.swap(next_expand_queue_up
);
1089 expand_queue_down
.swap(next_expand_queue_down
);
1093 while (!expand_queue
.empty())
1095 RTLIL::Cell
*cell
= *expand_queue
.begin();
1096 clkdomain_t key
= assigned_cells_reverse
.at(cell
);
1097 expand_queue
.erase(cell
);
1099 for (auto bit
: cell_to_bit
.at(cell
)) {
1100 for (auto c
: bit_to_cell
[bit
])
1101 if (unassigned_cells
.count(c
)) {
1102 unassigned_cells
.erase(c
);
1103 next_expand_queue
.insert(c
);
1104 assigned_cells
[key
].push_back(c
);
1105 assigned_cells_reverse
[c
] = key
;
1107 bit_to_cell
[bit
].clear();
1110 if (expand_queue
.empty())
1111 expand_queue
.swap(next_expand_queue
);
1114 clkdomain_t
key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
1115 for (auto cell
: unassigned_cells
) {
1116 assigned_cells
[key
].push_back(cell
);
1117 assigned_cells_reverse
[cell
] = key
;
1120 log_header(design
, "Summary of detected clock domains:\n");
1121 for (auto &it
: assigned_cells
)
1122 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it
.second
),
1123 std::get
<0>(it
.first
) ? "" : "!", log_signal(std::get
<1>(it
.first
)),
1124 std::get
<2>(it
.first
) ? "" : "!", log_signal(std::get
<3>(it
.first
)));
1126 for (auto &it
: assigned_cells
) {
1127 clk_polarity
= std::get
<0>(it
.first
);
1128 clk_sig
= assign_map(std::get
<1>(it
.first
));
1129 en_polarity
= std::get
<2>(it
.first
);
1130 en_sig
= assign_map(std::get
<3>(it
.first
));
1131 abc9_module(design
, mod
, script_file
, exe_file
, cleanup
, lut_costs
, !clk_sig
.empty(), "$",
1132 keepff
, delay_target
, lutin_shared
, fast_mode
, show_tempdir
,
1133 box_file
, lut_file
, wire_delay
);
1134 assign_map
.set(mod
);
1138 Pass::call(design
, "clean");
1146 PRIVATE_NAMESPACE_END