1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Claire Xenia Wolf <claire@yosyshq.com>
5 *
6 * Permission to use, copy, modify, and/or distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 *
18 */
19
20 // [[CITE]] ABC
21 // Berkeley Logic Synthesis and Verification Group, ABC: A System for Sequential Synthesis and Verification
22 // http://www.eecs.berkeley.edu/~alanmi/abc/
23
24 // [[CITE]] Berkeley Logic Interchange Format (BLIF)
25 // University of California. Berkeley. July 28, 1992
26 // http://www.ece.cmu.edu/~ee760/760docs/blif.pdf
27
28 // [[CITE]] Kahn's Topological sorting algorithm
29 // Kahn, Arthur B. (1962), "Topological sorting of large networks", Communications of the ACM 5 (11): 558-562, doi:10.1145/368996.369025
30 // http://en.wikipedia.org/wiki/Topological_sorting
31
32 #define ABC_COMMAND_LIB "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
33 #define ABC_COMMAND_CTR "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put; buffer; upsize {D}; dnsize {D}; stime -p"
34 #define ABC_COMMAND_LUT "strash; ifraig; scorr; dc2; dretime; strash; dch -f; if; mfs2"
35 #define ABC_COMMAND_SOP "strash; ifraig; scorr; dc2; dretime; strash; dch -f; cover {I} {P}"
36 #define ABC_COMMAND_DFL "strash; ifraig; scorr; dc2; dretime; strash; &get -n; &dch -f; &nf {D}; &put"
37
38 #define ABC_FAST_COMMAND_LIB "strash; dretime; map {D}"
39 #define ABC_FAST_COMMAND_CTR "strash; dretime; map {D}; buffer; upsize {D}; dnsize {D}; stime -p"
40 #define ABC_FAST_COMMAND_LUT "strash; dretime; if"
41 #define ABC_FAST_COMMAND_SOP "strash; dretime; cover {I} {P}"
42 #define ABC_FAST_COMMAND_DFL "strash; dretime; map"
43
44 #include "kernel/register.h"
45 #include "kernel/sigtools.h"
46 #include "kernel/celltypes.h"
47 #include "kernel/ffinit.h"
48 #include "kernel/cost.h"
49 #include "kernel/log.h"
50 #include <stdlib.h>
51 #include <stdio.h>
52 #include <string.h>
53 #include <cctype>
54 #include <cerrno>
55 #include <sstream>
56 #include <climits>
57 #include <vector>
58
59 #ifndef _WIN32
60 # include <unistd.h>
61 # include <dirent.h>
62 #endif
63
64 #include "frontends/blif/blifparse.h"
65
66 #ifdef YOSYS_LINK_ABC
67 extern "C" int Abc_RealMain(int argc, char *argv[]);
68 #endif
69
70 USING_YOSYS_NAMESPACE
71 PRIVATE_NAMESPACE_BEGIN
72
73 enum class gate_type_t {
74 G_NONE,
75 G_FF,
76 G_BUF,
77 G_NOT,
78 G_AND,
79 G_NAND,
80 G_OR,
81 G_NOR,
82 G_XOR,
83 G_XNOR,
84 G_ANDNOT,
85 G_ORNOT,
86 G_MUX,
87 G_NMUX,
88 G_AOI3,
89 G_OAI3,
90 G_AOI4,
91 G_OAI4
92 };
93
94 #define G(_name) gate_type_t::G_ ## _name
95
96 struct gate_t
97 {
98 int id;
99 gate_type_t type;
100 int in1, in2, in3, in4;
101 bool is_port;
102 RTLIL::SigBit bit;
103 RTLIL::State init;
104 };
105
106 bool map_mux4;
107 bool map_mux8;
108 bool map_mux16;
109
110 bool markgroups;
111 int map_autoidx;
112 SigMap assign_map;
113 RTLIL::Module *module;
114 std::vector<gate_t> signal_list;
115 std::map<RTLIL::SigBit, int> signal_map;
116 FfInitVals initvals;
117 pool<std::string> enabled_gates;
118 bool recover_init, cmos_cost;
119
120 bool clk_polarity, en_polarity;
121 RTLIL::SigSpec clk_sig, en_sig;
122 dict<int, std::string> pi_map, po_map;
123
map_signal(RTLIL::SigBit bit,gate_type_t gate_type=G (NONE),int in1=-1,int in2=-1,int in3=-1,int in4=-1)124 int map_signal(RTLIL::SigBit bit, gate_type_t gate_type = G(NONE), int in1 = -1, int in2 = -1, int in3 = -1, int in4 = -1)
125 {
126 assign_map.apply(bit);
127
128 if (signal_map.count(bit) == 0) {
129 gate_t gate;
130 gate.id = signal_list.size();
131 gate.type = G(NONE);
132 gate.in1 = -1;
133 gate.in2 = -1;
134 gate.in3 = -1;
135 gate.in4 = -1;
136 gate.is_port = false;
137 gate.bit = bit;
138 gate.init = initvals(bit);
139 signal_list.push_back(gate);
140 signal_map[bit] = gate.id;
141 }
142
143 gate_t &gate = signal_list[signal_map[bit]];
144
145 if (gate_type != G(NONE))
146 gate.type = gate_type;
147 if (in1 >= 0)
148 gate.in1 = in1;
149 if (in2 >= 0)
150 gate.in2 = in2;
151 if (in3 >= 0)
152 gate.in3 = in3;
153 if (in4 >= 0)
154 gate.in4 = in4;
155
156 return gate.id;
157 }
158
mark_port(RTLIL::SigSpec sig)159 void mark_port(RTLIL::SigSpec sig)
160 {
161 for (auto &bit : assign_map(sig))
162 if (bit.wire != nullptr && signal_map.count(bit) > 0)
163 signal_list[signal_map[bit]].is_port = true;
164 }
165
extract_cell(RTLIL::Cell * cell,bool keepff)166 void extract_cell(RTLIL::Cell *cell, bool keepff)
167 {
168 if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_)))
169 {
170 if (clk_polarity != (cell->type == ID($_DFF_P_)))
171 return;
172 if (clk_sig != assign_map(cell->getPort(ID::C)))
173 return;
174 if (GetSize(en_sig) != 0)
175 return;
176 goto matching_dff;
177 }
178
179 if (cell->type.in(ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
180 {
181 if (clk_polarity != cell->type.in(ID($_DFFE_PN_), ID($_DFFE_PP_)))
182 return;
183 if (en_polarity != cell->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
184 return;
185 if (clk_sig != assign_map(cell->getPort(ID::C)))
186 return;
187 if (en_sig != assign_map(cell->getPort(ID::E)))
188 return;
189 goto matching_dff;
190 }
191
192 if (0) {
193 matching_dff:
194 RTLIL::SigSpec sig_d = cell->getPort(ID::D);
195 RTLIL::SigSpec sig_q = cell->getPort(ID::Q);
196
197 if (keepff)
198 for (auto &c : sig_q.chunks())
199 if (c.wire != nullptr)
200 c.wire->attributes[ID::keep] = 1;
201
202 assign_map.apply(sig_d);
203 assign_map.apply(sig_q);
204
205 map_signal(sig_q, G(FF), map_signal(sig_d));
206
207 module->remove(cell);
208 return;
209 }
210
211 if (cell->type.in(ID($_BUF_), ID($_NOT_)))
212 {
213 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
214 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
215
216 assign_map.apply(sig_a);
217 assign_map.apply(sig_y);
218
219 map_signal(sig_y, cell->type == ID($_BUF_) ? G(BUF) : G(NOT), map_signal(sig_a));
220
221 module->remove(cell);
222 return;
223 }
224
225 if (cell->type.in(ID($_AND_), ID($_NAND_), ID($_OR_), ID($_NOR_), ID($_XOR_), ID($_XNOR_), ID($_ANDNOT_), ID($_ORNOT_)))
226 {
227 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
228 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
229 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
230
231 assign_map.apply(sig_a);
232 assign_map.apply(sig_b);
233 assign_map.apply(sig_y);
234
235 int mapped_a = map_signal(sig_a);
236 int mapped_b = map_signal(sig_b);
237
238 if (cell->type == ID($_AND_))
239 map_signal(sig_y, G(AND), mapped_a, mapped_b);
240 else if (cell->type == ID($_NAND_))
241 map_signal(sig_y, G(NAND), mapped_a, mapped_b);
242 else if (cell->type == ID($_OR_))
243 map_signal(sig_y, G(OR), mapped_a, mapped_b);
244 else if (cell->type == ID($_NOR_))
245 map_signal(sig_y, G(NOR), mapped_a, mapped_b);
246 else if (cell->type == ID($_XOR_))
247 map_signal(sig_y, G(XOR), mapped_a, mapped_b);
248 else if (cell->type == ID($_XNOR_))
249 map_signal(sig_y, G(XNOR), mapped_a, mapped_b);
250 else if (cell->type == ID($_ANDNOT_))
251 map_signal(sig_y, G(ANDNOT), mapped_a, mapped_b);
252 else if (cell->type == ID($_ORNOT_))
253 map_signal(sig_y, G(ORNOT), mapped_a, mapped_b);
254 else
255 log_abort();
256
257 module->remove(cell);
258 return;
259 }
260
261 if (cell->type.in(ID($_MUX_), ID($_NMUX_)))
262 {
263 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
264 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
265 RTLIL::SigSpec sig_s = cell->getPort(ID::S);
266 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
267
268 assign_map.apply(sig_a);
269 assign_map.apply(sig_b);
270 assign_map.apply(sig_s);
271 assign_map.apply(sig_y);
272
273 int mapped_a = map_signal(sig_a);
274 int mapped_b = map_signal(sig_b);
275 int mapped_s = map_signal(sig_s);
276
277 map_signal(sig_y, cell->type == ID($_MUX_) ? G(MUX) : G(NMUX), mapped_a, mapped_b, mapped_s);
278
279 module->remove(cell);
280 return;
281 }
282
283 if (cell->type.in(ID($_AOI3_), ID($_OAI3_)))
284 {
285 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
286 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
287 RTLIL::SigSpec sig_c = cell->getPort(ID::C);
288 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
289
290 assign_map.apply(sig_a);
291 assign_map.apply(sig_b);
292 assign_map.apply(sig_c);
293 assign_map.apply(sig_y);
294
295 int mapped_a = map_signal(sig_a);
296 int mapped_b = map_signal(sig_b);
297 int mapped_c = map_signal(sig_c);
298
299 map_signal(sig_y, cell->type == ID($_AOI3_) ? G(AOI3) : G(OAI3), mapped_a, mapped_b, mapped_c);
300
301 module->remove(cell);
302 return;
303 }
304
305 if (cell->type.in(ID($_AOI4_), ID($_OAI4_)))
306 {
307 RTLIL::SigSpec sig_a = cell->getPort(ID::A);
308 RTLIL::SigSpec sig_b = cell->getPort(ID::B);
309 RTLIL::SigSpec sig_c = cell->getPort(ID::C);
310 RTLIL::SigSpec sig_d = cell->getPort(ID::D);
311 RTLIL::SigSpec sig_y = cell->getPort(ID::Y);
312
313 assign_map.apply(sig_a);
314 assign_map.apply(sig_b);
315 assign_map.apply(sig_c);
316 assign_map.apply(sig_d);
317 assign_map.apply(sig_y);
318
319 int mapped_a = map_signal(sig_a);
320 int mapped_b = map_signal(sig_b);
321 int mapped_c = map_signal(sig_c);
322 int mapped_d = map_signal(sig_d);
323
324 map_signal(sig_y, cell->type == ID($_AOI4_) ? G(AOI4) : G(OAI4), mapped_a, mapped_b, mapped_c, mapped_d);
325
326 module->remove(cell);
327 return;
328 }
329 }
330
remap_name(RTLIL::IdString abc_name,RTLIL::Wire ** orig_wire=nullptr)331 std::string remap_name(RTLIL::IdString abc_name, RTLIL::Wire **orig_wire = nullptr)
332 {
333 std::string abc_sname = abc_name.substr(1);
334 bool isnew = false;
335 if (abc_sname.compare(0, 4, "new_") == 0)
336 {
337 abc_sname.erase(0, 4);
338 isnew = true;
339 }
340 if (abc_sname.compare(0, 5, "ys__n") == 0)
341 {
342 abc_sname.erase(0, 5);
343 if (std::isdigit(abc_sname.at(0)))
344 {
345 int sid = std::atoi(abc_sname.c_str());
346 size_t postfix_start = abc_sname.find_first_not_of("0123456789");
347 std::string postfix = postfix_start != std::string::npos ? abc_sname.substr(postfix_start) : "";
348
349 if (sid < GetSize(signal_list))
350 {
351 auto sig = signal_list.at(sid);
352 if (sig.bit.wire != nullptr)
353 {
354 std::string s = stringf("$abc$%d$%s", map_autoidx, sig.bit.wire->name.c_str()+1);
355 if (sig.bit.wire->width != 1)
356 s += stringf("[%d]", sig.bit.offset);
357 if (isnew)
358 s += "_new";
359 s += postfix;
360 if (orig_wire != nullptr)
361 *orig_wire = sig.bit.wire;
362 return s;
363 }
364 }
365 }
366 }
367 return stringf("$abc$%d$%s", map_autoidx, abc_name.c_str()+1);
368 }
369
dump_loop_graph(FILE * f,int & nr,std::map<int,std::set<int>> & edges,std::set<int> & workpool,std::vector<int> & in_counts)370 void dump_loop_graph(FILE *f, int &nr, std::map<int, std::set<int>> &edges, std::set<int> &workpool, std::vector<int> &in_counts)
371 {
372 if (f == nullptr)
373 return;
374
375 log("Dumping loop state graph to slide %d.\n", ++nr);
376
377 fprintf(f, "digraph \"slide%d\" {\n", nr);
378 fprintf(f, " label=\"slide%d\";\n", nr);
379 fprintf(f, " rankdir=\"TD\";\n");
380
381 std::set<int> nodes;
382 for (auto &e : edges) {
383 nodes.insert(e.first);
384 for (auto n : e.second)
385 nodes.insert(n);
386 }
387
388 for (auto n : nodes)
389 fprintf(f, " ys__n%d [label=\"%s\\nid=%d, count=%d\"%s];\n", n, log_signal(signal_list[n].bit),
390 n, in_counts[n], workpool.count(n) ? ", shape=box" : "");
391
392 for (auto &e : edges)
393 for (auto n : e.second)
394 fprintf(f, " ys__n%d -> ys__n%d;\n", e.first, n);
395
396 fprintf(f, "}\n");
397 }
398
handle_loops()399 void handle_loops()
400 {
401 // http://en.wikipedia.org/wiki/Topological_sorting
402 // (Kahn, Arthur B. (1962), "Topological sorting of large networks")
403
404 std::map<int, std::set<int>> edges;
405 std::vector<int> in_edges_count(signal_list.size());
406 std::set<int> workpool;
407
408 FILE *dot_f = nullptr;
409 int dot_nr = 0;
410
411 // uncomment for troubleshooting the loop detection code
412 // dot_f = fopen("test.dot", "w");
413
414 for (auto &g : signal_list) {
415 if (g.type == G(NONE) || g.type == G(FF)) {
416 workpool.insert(g.id);
417 } else {
418 if (g.in1 >= 0) {
419 edges[g.in1].insert(g.id);
420 in_edges_count[g.id]++;
421 }
422 if (g.in2 >= 0 && g.in2 != g.in1) {
423 edges[g.in2].insert(g.id);
424 in_edges_count[g.id]++;
425 }
426 if (g.in3 >= 0 && g.in3 != g.in2 && g.in3 != g.in1) {
427 edges[g.in3].insert(g.id);
428 in_edges_count[g.id]++;
429 }
430 if (g.in4 >= 0 && g.in4 != g.in3 && g.in4 != g.in2 && g.in4 != g.in1) {
431 edges[g.in4].insert(g.id);
432 in_edges_count[g.id]++;
433 }
434 }
435 }
436
437 dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);
438
439 while (workpool.size() > 0)
440 {
441 int id = *workpool.begin();
442 workpool.erase(id);
443
444 // log("Removing non-loop node %d from graph: %s\n", id, log_signal(signal_list[id].bit));
445
446 for (int id2 : edges[id]) {
447 log_assert(in_edges_count[id2] > 0);
448 if (--in_edges_count[id2] == 0)
449 workpool.insert(id2);
450 }
451 edges.erase(id);
452
453 dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);
454
455 while (workpool.size() == 0)
456 {
457 if (edges.size() == 0)
458 break;
459
460 int id1 = edges.begin()->first;
461
462 for (auto &edge_it : edges) {
463 int id2 = edge_it.first;
464 RTLIL::Wire *w1 = signal_list[id1].bit.wire;
465 RTLIL::Wire *w2 = signal_list[id2].bit.wire;
466 if (w1 == nullptr)
467 id1 = id2;
468 else if (w2 == nullptr)
469 continue;
470 else if (w1->name[0] == '$' && w2->name[0] == '\\')
471 id1 = id2;
472 else if (w1->name[0] == '\\' && w2->name[0] == '$')
473 continue;
474 else if (edges[id1].size() < edges[id2].size())
475 id1 = id2;
476 else if (edges[id1].size() > edges[id2].size())
477 continue;
478 else if (w2->name.str() < w1->name.str())
479 id1 = id2;
480 }
481
482 if (edges[id1].size() == 0) {
483 edges.erase(id1);
484 continue;
485 }
486
487 log_assert(signal_list[id1].bit.wire != nullptr);
488
489 std::stringstream sstr;
490 sstr << "$abcloop$" << (autoidx++);
491 RTLIL::Wire *wire = module->addWire(sstr.str());
492
493 bool first_line = true;
494 for (int id2 : edges[id1]) {
495 if (first_line)
496 log("Breaking loop using new signal %s: %s -> %s\n", log_signal(RTLIL::SigSpec(wire)),
497 log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit));
498 else
499 log(" %*s %s -> %s\n", int(strlen(log_signal(RTLIL::SigSpec(wire)))), "",
500 log_signal(signal_list[id1].bit), log_signal(signal_list[id2].bit));
501 first_line = false;
502 }
503
504 int id3 = map_signal(RTLIL::SigSpec(wire));
505 signal_list[id1].is_port = true;
506 signal_list[id3].is_port = true;
507 log_assert(id3 == int(in_edges_count.size()));
508 in_edges_count.push_back(0);
509 workpool.insert(id3);
510
511 for (int id2 : edges[id1]) {
512 if (signal_list[id2].in1 == id1)
513 signal_list[id2].in1 = id3;
514 if (signal_list[id2].in2 == id1)
515 signal_list[id2].in2 = id3;
516 if (signal_list[id2].in3 == id1)
517 signal_list[id2].in3 = id3;
518 if (signal_list[id2].in4 == id1)
519 signal_list[id2].in4 = id3;
520 }
521 edges[id1].swap(edges[id3]);
522
523 module->connect(RTLIL::SigSig(signal_list[id3].bit, signal_list[id1].bit));
524 dump_loop_graph(dot_f, dot_nr, edges, workpool, in_edges_count);
525 }
526 }
527
528 if (dot_f != nullptr)
529 fclose(dot_f);
530 }
531
add_echos_to_abc_cmd(std::string str)532 std::string add_echos_to_abc_cmd(std::string str)
533 {
534 std::string new_str, token;
535 for (size_t i = 0; i < str.size(); i++) {
536 token += str[i];
537 if (str[i] == ';') {
538 while (i+1 < str.size() && str[i+1] == ' ')
539 i++;
540 new_str += "echo + " + token + " " + token + " ";
541 token.clear();
542 }
543 }
544
545 if (!token.empty()) {
546 if (!new_str.empty())
547 new_str += "echo + " + token + "; ";
548 new_str += token;
549 }
550
551 return new_str;
552 }
553
fold_abc_cmd(std::string str)554 std::string fold_abc_cmd(std::string str)
555 {
556 std::string token, new_str = " ";
557 int char_counter = 10;
558
559 for (size_t i = 0; i <= str.size(); i++) {
560 if (i < str.size())
561 token += str[i];
562 if (i == str.size() || str[i] == ';') {
563 if (char_counter + token.size() > 75)
564 new_str += "\n ", char_counter = 14;
565 new_str += token, char_counter += token.size();
566 token.clear();
567 }
568 }
569
570 return new_str;
571 }
572
replace_tempdir(std::string text,std::string tempdir_name,bool show_tempdir)573 std::string replace_tempdir(std::string text, std::string tempdir_name, bool show_tempdir)
574 {
575 if (show_tempdir)
576 return text;
577
578 while (1) {
579 size_t pos = text.find(tempdir_name);
580 if (pos == std::string::npos)
581 break;
582 text = text.substr(0, pos) + "<abc-temp-dir>" + text.substr(pos + GetSize(tempdir_name));
583 }
584
585 std::string selfdir_name = proc_self_dirname();
586 if (selfdir_name != "/") {
587 while (1) {
588 size_t pos = text.find(selfdir_name);
589 if (pos == std::string::npos)
590 break;
591 text = text.substr(0, pos) + "<yosys-exe-dir>/" + text.substr(pos + GetSize(selfdir_name));
592 }
593 }
594
595 return text;
596 }
597
598 struct abc_output_filter
599 {
600 bool got_cr;
601 int escape_seq_state;
602 std::string linebuf;
603 std::string tempdir_name;
604 bool show_tempdir;
605
abc_output_filterabc_output_filter606 abc_output_filter(std::string tempdir_name, bool show_tempdir) : tempdir_name(tempdir_name), show_tempdir(show_tempdir)
607 {
608 got_cr = false;
609 escape_seq_state = 0;
610 }
611
next_charabc_output_filter612 void next_char(char ch)
613 {
614 if (escape_seq_state == 0 && ch == '\033') {
615 escape_seq_state = 1;
616 return;
617 }
618 if (escape_seq_state == 1) {
619 escape_seq_state = ch == '[' ? 2 : 0;
620 return;
621 }
622 if (escape_seq_state == 2) {
623 if ((ch < '0' || '9' < ch) && ch != ';')
624 escape_seq_state = 0;
625 return;
626 }
627 escape_seq_state = 0;
628 if (ch == '\r') {
629 got_cr = true;
630 return;
631 }
632 if (ch == '\n') {
633 log("ABC: %s\n", replace_tempdir(linebuf, tempdir_name, show_tempdir).c_str());
634 got_cr = false, linebuf.clear();
635 return;
636 }
637 if (got_cr)
638 got_cr = false, linebuf.clear();
639 linebuf += ch;
640 }
641
next_lineabc_output_filter642 void next_line(const std::string &line)
643 {
644 int pi, po;
645 if (sscanf(line.c_str(), "Start-point = pi%d. End-point = po%d.", &pi, &po) == 2) {
646 log("ABC: Start-point = pi%d (%s). End-point = po%d (%s).\n",
647 pi, pi_map.count(pi) ? pi_map.at(pi).c_str() : "???",
648 po, po_map.count(po) ? po_map.at(po).c_str() : "???");
649 return;
650 }
651
652 for (char ch : line)
653 next_char(ch);
654 }
655 };
656
abc_module(RTLIL::Design * design,RTLIL::Module * current_module,std::string script_file,std::string exe_file,std::vector<std::string> & liberty_files,std::vector<std::string> & genlib_files,std::string constr_file,bool cleanup,vector<int> lut_costs,bool dff_mode,std::string clk_str,bool keepff,std::string delay_target,std::string sop_inputs,std::string sop_products,std::string lutin_shared,bool fast_mode,const std::vector<RTLIL::Cell * > & cells,bool show_tempdir,bool sop_mode,bool abc_dress)657 void abc_module(RTLIL::Design *design, RTLIL::Module *current_module, std::string script_file, std::string exe_file,
658 std::vector<std::string> &liberty_files, std::vector<std::string> &genlib_files, std::string constr_file,
659 bool cleanup, vector<int> lut_costs, bool dff_mode, std::string clk_str, bool keepff, std::string delay_target,
660 std::string sop_inputs, std::string sop_products, std::string lutin_shared, bool fast_mode,
661 const std::vector<RTLIL::Cell*> &cells, bool show_tempdir, bool sop_mode, bool abc_dress)
662 {
663 module = current_module;
664 map_autoidx = autoidx++;
665
666 signal_map.clear();
667 signal_list.clear();
668 pi_map.clear();
669 po_map.clear();
670 recover_init = false;
671
672 if (clk_str != "$")
673 {
674 clk_polarity = true;
675 clk_sig = RTLIL::SigSpec();
676
677 en_polarity = true;
678 en_sig = RTLIL::SigSpec();
679 }
680
681 if (!clk_str.empty() && clk_str != "$")
682 {
683 if (clk_str.find(',') != std::string::npos) {
684 int pos = clk_str.find(',');
685 std::string en_str = clk_str.substr(pos+1);
686 clk_str = clk_str.substr(0, pos);
687 if (en_str[0] == '!') {
688 en_polarity = false;
689 en_str = en_str.substr(1);
690 }
691 if (module->wire(RTLIL::escape_id(en_str)) != nullptr)
692 en_sig = assign_map(module->wire(RTLIL::escape_id(en_str)));
693 }
694 if (clk_str[0] == '!') {
695 clk_polarity = false;
696 clk_str = clk_str.substr(1);
697 }
698 if (module->wire(RTLIL::escape_id(clk_str)) != nullptr)
699 clk_sig = assign_map(module->wire(RTLIL::escape_id(clk_str)));
700 }
701
702 if (dff_mode && clk_sig.empty())
703 log_cmd_error("Clock domain %s not found.\n", clk_str.c_str());
704
705 std::string tempdir_name = "/tmp/" + proc_program_prefix()+ "yosys-abc-XXXXXX";
706 if (!cleanup)
707 tempdir_name[0] = tempdir_name[4] = '_';
708 tempdir_name = make_temp_dir(tempdir_name);
709 log_header(design, "Extracting gate netlist of module `%s' to `%s/input.blif'..\n",
710 module->name.c_str(), replace_tempdir(tempdir_name, tempdir_name, show_tempdir).c_str());
711
712 std::string abc_script = stringf("read_blif %s/input.blif; ", tempdir_name.c_str());
713
714 if (!liberty_files.empty() || !genlib_files.empty()) {
715 for (std::string liberty_file : liberty_files)
716 abc_script += stringf("read_lib -w %s; ", liberty_file.c_str());
717 for (std::string liberty_file : genlib_files)
718 abc_script += stringf("read_library %s; ", liberty_file.c_str());
719 if (!constr_file.empty())
720 abc_script += stringf("read_constr -v %s; ", constr_file.c_str());
721 } else
722 if (!lut_costs.empty())
723 abc_script += stringf("read_lut %s/lutdefs.txt; ", tempdir_name.c_str());
724 else
725 abc_script += stringf("read_library %s/stdcells.genlib; ", tempdir_name.c_str());
726
727 if (!script_file.empty()) {
728 if (script_file[0] == '+') {
729 for (size_t i = 1; i < script_file.size(); i++)
730 if (script_file[i] == '\'')
731 abc_script += "'\\''";
732 else if (script_file[i] == ',')
733 abc_script += " ";
734 else
735 abc_script += script_file[i];
736 } else
737 abc_script += stringf("source %s", script_file.c_str());
738 } else if (!lut_costs.empty()) {
739 bool all_luts_cost_same = true;
740 for (int this_cost : lut_costs)
741 if (this_cost != lut_costs.front())
742 all_luts_cost_same = false;
743 abc_script += fast_mode ? ABC_FAST_COMMAND_LUT : ABC_COMMAND_LUT;
744 if (all_luts_cost_same && !fast_mode)
745 abc_script += "; lutpack {S}";
746 } else if (!liberty_files.empty() || !genlib_files.empty())
747 abc_script += constr_file.empty() ? (fast_mode ? ABC_FAST_COMMAND_LIB : ABC_COMMAND_LIB) : (fast_mode ? ABC_FAST_COMMAND_CTR : ABC_COMMAND_CTR);
748 else if (sop_mode)
749 abc_script += fast_mode ? ABC_FAST_COMMAND_SOP : ABC_COMMAND_SOP;
750 else
751 abc_script += fast_mode ? ABC_FAST_COMMAND_DFL : ABC_COMMAND_DFL;
752
753 if (script_file.empty() && !delay_target.empty())
754 for (size_t pos = abc_script.find("dretime;"); pos != std::string::npos; pos = abc_script.find("dretime;", pos+1))
755 abc_script = abc_script.substr(0, pos) + "dretime; retime -o {D};" + abc_script.substr(pos+8);
756
757 for (size_t pos = abc_script.find("{D}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
758 abc_script = abc_script.substr(0, pos) + delay_target + abc_script.substr(pos+3);
759
760 for (size_t pos = abc_script.find("{I}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
761 abc_script = abc_script.substr(0, pos) + sop_inputs + abc_script.substr(pos+3);
762
763 for (size_t pos = abc_script.find("{P}"); pos != std::string::npos; pos = abc_script.find("{D}", pos))
764 abc_script = abc_script.substr(0, pos) + sop_products + abc_script.substr(pos+3);
765
766 for (size_t pos = abc_script.find("{S}"); pos != std::string::npos; pos = abc_script.find("{S}", pos))
767 abc_script = abc_script.substr(0, pos) + lutin_shared + abc_script.substr(pos+3);
768 if (abc_dress)
769 abc_script += "; dress";
770 abc_script += stringf("; write_blif %s/output.blif", tempdir_name.c_str());
771 abc_script = add_echos_to_abc_cmd(abc_script);
772
773 for (size_t i = 0; i+1 < abc_script.size(); i++)
774 if (abc_script[i] == ';' && abc_script[i+1] == ' ')
775 abc_script[i+1] = '\n';
776
777 std::string buffer = stringf("%s/abc.script", tempdir_name.c_str());
778 FILE *f = fopen(buffer.c_str(), "wt");
779 if (f == nullptr)
780 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
781 fprintf(f, "%s\n", abc_script.c_str());
782 fclose(f);
783
784 if (dff_mode || !clk_str.empty())
785 {
786 if (clk_sig.size() == 0)
787 log("No%s clock domain found. Not extracting any FF cells.\n", clk_str.empty() ? "" : " matching");
788 else {
789 log("Found%s %s clock domain: %s", clk_str.empty() ? "" : " matching", clk_polarity ? "posedge" : "negedge", log_signal(clk_sig));
790 if (en_sig.size() != 0)
791 log(", enabled by %s%s", en_polarity ? "" : "!", log_signal(en_sig));
792 log("\n");
793 }
794 }
795
796 for (auto c : cells)
797 extract_cell(c, keepff);
798
799 for (auto wire : module->wires()) {
800 if (wire->port_id > 0 || wire->get_bool_attribute(ID::keep))
801 mark_port(wire);
802 }
803
804 for (auto cell : module->cells())
805 for (auto &port_it : cell->connections())
806 mark_port(port_it.second);
807
808 if (clk_sig.size() != 0)
809 mark_port(clk_sig);
810
811 if (en_sig.size() != 0)
812 mark_port(en_sig);
813
814 handle_loops();
815
816 buffer = stringf("%s/input.blif", tempdir_name.c_str());
817 f = fopen(buffer.c_str(), "wt");
818 if (f == nullptr)
819 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
820
821 fprintf(f, ".model netlist\n");
822
823 int count_input = 0;
824 fprintf(f, ".inputs");
825 for (auto &si : signal_list) {
826 if (!si.is_port || si.type != G(NONE))
827 continue;
828 fprintf(f, " ys__n%d", si.id);
829 pi_map[count_input++] = log_signal(si.bit);
830 }
831 if (count_input == 0)
832 fprintf(f, " dummy_input\n");
833 fprintf(f, "\n");
834
835 int count_output = 0;
836 fprintf(f, ".outputs");
837 for (auto &si : signal_list) {
838 if (!si.is_port || si.type == G(NONE))
839 continue;
840 fprintf(f, " ys__n%d", si.id);
841 po_map[count_output++] = log_signal(si.bit);
842 }
843 fprintf(f, "\n");
844
845 for (auto &si : signal_list)
846 fprintf(f, "# ys__n%-5d %s\n", si.id, log_signal(si.bit));
847
848 for (auto &si : signal_list) {
849 if (si.bit.wire == nullptr) {
850 fprintf(f, ".names ys__n%d\n", si.id);
851 if (si.bit == RTLIL::State::S1)
852 fprintf(f, "1\n");
853 }
854 }
855
856 int count_gates = 0;
857 for (auto &si : signal_list) {
858 if (si.type == G(BUF)) {
859 fprintf(f, ".names ys__n%d ys__n%d\n", si.in1, si.id);
860 fprintf(f, "1 1\n");
861 } else if (si.type == G(NOT)) {
862 fprintf(f, ".names ys__n%d ys__n%d\n", si.in1, si.id);
863 fprintf(f, "0 1\n");
864 } else if (si.type == G(AND)) {
865 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
866 fprintf(f, "11 1\n");
867 } else if (si.type == G(NAND)) {
868 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
869 fprintf(f, "0- 1\n");
870 fprintf(f, "-0 1\n");
871 } else if (si.type == G(OR)) {
872 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
873 fprintf(f, "-1 1\n");
874 fprintf(f, "1- 1\n");
875 } else if (si.type == G(NOR)) {
876 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
877 fprintf(f, "00 1\n");
878 } else if (si.type == G(XOR)) {
879 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
880 fprintf(f, "01 1\n");
881 fprintf(f, "10 1\n");
882 } else if (si.type == G(XNOR)) {
883 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
884 fprintf(f, "00 1\n");
885 fprintf(f, "11 1\n");
886 } else if (si.type == G(ANDNOT)) {
887 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
888 fprintf(f, "10 1\n");
889 } else if (si.type == G(ORNOT)) {
890 fprintf(f, ".names ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.id);
891 fprintf(f, "1- 1\n");
892 fprintf(f, "-0 1\n");
893 } else if (si.type == G(MUX)) {
894 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
895 fprintf(f, "1-0 1\n");
896 fprintf(f, "-11 1\n");
897 } else if (si.type == G(NMUX)) {
898 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
899 fprintf(f, "0-0 1\n");
900 fprintf(f, "-01 1\n");
901 } else if (si.type == G(AOI3)) {
902 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
903 fprintf(f, "-00 1\n");
904 fprintf(f, "0-0 1\n");
905 } else if (si.type == G(OAI3)) {
906 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.id);
907 fprintf(f, "00- 1\n");
908 fprintf(f, "--0 1\n");
909 } else if (si.type == G(AOI4)) {
910 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.in4, si.id);
911 fprintf(f, "-0-0 1\n");
912 fprintf(f, "-00- 1\n");
913 fprintf(f, "0--0 1\n");
914 fprintf(f, "0-0- 1\n");
915 } else if (si.type == G(OAI4)) {
916 fprintf(f, ".names ys__n%d ys__n%d ys__n%d ys__n%d ys__n%d\n", si.in1, si.in2, si.in3, si.in4, si.id);
917 fprintf(f, "00-- 1\n");
918 fprintf(f, "--00 1\n");
919 } else if (si.type == G(FF)) {
920 if (si.init == State::S0 || si.init == State::S1) {
921 fprintf(f, ".latch ys__n%d ys__n%d %d\n", si.in1, si.id, si.init == State::S1 ? 1 : 0);
922 recover_init = true;
923 } else
924 fprintf(f, ".latch ys__n%d ys__n%d 2\n", si.in1, si.id);
925 } else if (si.type != G(NONE))
926 log_abort();
927 if (si.type != G(NONE))
928 count_gates++;
929 }
930
931 fprintf(f, ".end\n");
932 fclose(f);
933
934 log("Extracted %d gates and %d wires to a netlist network with %d inputs and %d outputs.\n",
935 count_gates, GetSize(signal_list), count_input, count_output);
936 log_push();
937 if (count_output > 0)
938 {
939 log_header(design, "Executing ABC.\n");
940
941 auto &cell_cost = cmos_cost ? CellCosts::cmos_gate_cost() : CellCosts::default_gate_cost();
942
943 buffer = stringf("%s/stdcells.genlib", tempdir_name.c_str());
944 f = fopen(buffer.c_str(), "wt");
945 if (f == nullptr)
946 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
947 fprintf(f, "GATE ZERO 1 Y=CONST0;\n");
948 fprintf(f, "GATE ONE 1 Y=CONST1;\n");
949 fprintf(f, "GATE BUF %d Y=A; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_BUF_)));
950 fprintf(f, "GATE NOT %d Y=!A; PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NOT_)));
951 if (enabled_gates.count("AND"))
952 fprintf(f, "GATE AND %d Y=A*B; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_AND_)));
953 if (enabled_gates.count("NAND"))
954 fprintf(f, "GATE NAND %d Y=!(A*B); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NAND_)));
955 if (enabled_gates.count("OR"))
956 fprintf(f, "GATE OR %d Y=A+B; PIN * NONINV 1 999 1 0 1 0\n", cell_cost.at(ID($_OR_)));
957 if (enabled_gates.count("NOR"))
958 fprintf(f, "GATE NOR %d Y=!(A+B); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_NOR_)));
959 if (enabled_gates.count("XOR"))
960 fprintf(f, "GATE XOR %d Y=(A*!B)+(!A*B); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_XOR_)));
961 if (enabled_gates.count("XNOR"))
962 fprintf(f, "GATE XNOR %d Y=(A*B)+(!A*!B); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_XNOR_)));
963 if (enabled_gates.count("ANDNOT"))
964 fprintf(f, "GATE ANDNOT %d Y=A*!B; PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_ANDNOT_)));
965 if (enabled_gates.count("ORNOT"))
966 fprintf(f, "GATE ORNOT %d Y=A+!B; PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_ORNOT_)));
967 if (enabled_gates.count("AOI3"))
968 fprintf(f, "GATE AOI3 %d Y=!((A*B)+C); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_AOI3_)));
969 if (enabled_gates.count("OAI3"))
970 fprintf(f, "GATE OAI3 %d Y=!((A+B)*C); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_OAI3_)));
971 if (enabled_gates.count("AOI4"))
972 fprintf(f, "GATE AOI4 %d Y=!((A*B)+(C*D)); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_AOI4_)));
973 if (enabled_gates.count("OAI4"))
974 fprintf(f, "GATE OAI4 %d Y=!((A+B)*(C+D)); PIN * INV 1 999 1 0 1 0\n", cell_cost.at(ID($_OAI4_)));
975 if (enabled_gates.count("MUX"))
976 fprintf(f, "GATE MUX %d Y=(A*B)+(S*B)+(!S*A); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_MUX_)));
977 if (enabled_gates.count("NMUX"))
978 fprintf(f, "GATE NMUX %d Y=!((A*B)+(S*B)+(!S*A)); PIN * UNKNOWN 1 999 1 0 1 0\n", cell_cost.at(ID($_NMUX_)));
979 if (map_mux4)
980 fprintf(f, "GATE MUX4 %d Y=(!S*!T*A)+(S*!T*B)+(!S*T*C)+(S*T*D); PIN * UNKNOWN 1 999 1 0 1 0\n", 2*cell_cost.at(ID($_MUX_)));
981 if (map_mux8)
982 fprintf(f, "GATE MUX8 %d Y=(!S*!T*!U*A)+(S*!T*!U*B)+(!S*T*!U*C)+(S*T*!U*D)+(!S*!T*U*E)+(S*!T*U*F)+(!S*T*U*G)+(S*T*U*H); PIN * UNKNOWN 1 999 1 0 1 0\n", 4*cell_cost.at(ID($_MUX_)));
983 if (map_mux16)
984 fprintf(f, "GATE MUX16 %d Y=(!S*!T*!U*!V*A)+(S*!T*!U*!V*B)+(!S*T*!U*!V*C)+(S*T*!U*!V*D)+(!S*!T*U*!V*E)+(S*!T*U*!V*F)+(!S*T*U*!V*G)+(S*T*U*!V*H)+(!S*!T*!U*V*I)+(S*!T*!U*V*J)+(!S*T*!U*V*K)+(S*T*!U*V*L)+(!S*!T*U*V*M)+(S*!T*U*V*N)+(!S*T*U*V*O)+(S*T*U*V*P); PIN * UNKNOWN 1 999 1 0 1 0\n", 8*cell_cost.at(ID($_MUX_)));
985 fclose(f);
986
987 if (!lut_costs.empty()) {
988 buffer = stringf("%s/lutdefs.txt", tempdir_name.c_str());
989 f = fopen(buffer.c_str(), "wt");
990 if (f == nullptr)
991 log_error("Opening %s for writing failed: %s\n", buffer.c_str(), strerror(errno));
992 for (int i = 0; i < GetSize(lut_costs); i++)
993 fprintf(f, "%d %d.00 1.00\n", i+1, lut_costs.at(i));
994 fclose(f);
995 }
996
997 buffer = stringf("%s -s -f %s/abc.script 2>&1", exe_file.c_str(), tempdir_name.c_str());
998 log("Running ABC command: %s\n", replace_tempdir(buffer, tempdir_name, show_tempdir).c_str());
999
1000 #ifndef YOSYS_LINK_ABC
1001 abc_output_filter filt(tempdir_name, show_tempdir);
1002 int ret = run_command(buffer, std::bind(&abc_output_filter::next_line, filt, std::placeholders::_1));
1003 #else
1004 // These needs to be mutable, supposedly due to getopt
1005 char *abc_argv[5];
1006 string tmp_script_name = stringf("%s/abc.script", tempdir_name.c_str());
1007 abc_argv[0] = strdup(exe_file.c_str());
1008 abc_argv[1] = strdup("-s");
1009 abc_argv[2] = strdup("-f");
1010 abc_argv[3] = strdup(tmp_script_name.c_str());
1011 abc_argv[4] = 0;
1012 int ret = Abc_RealMain(4, abc_argv);
1013 free(abc_argv[0]);
1014 free(abc_argv[1]);
1015 free(abc_argv[2]);
1016 free(abc_argv[3]);
1017 #endif
1018 if (ret != 0)
1019 log_error("ABC: execution of command \"%s\" failed: return code %d.\n", buffer.c_str(), ret);
1020
1021 buffer = stringf("%s/%s", tempdir_name.c_str(), "output.blif");
1022 std::ifstream ifs;
1023 ifs.open(buffer);
1024 if (ifs.fail())
1025 log_error("Can't open ABC output file `%s'.\n", buffer.c_str());
1026
1027 bool builtin_lib = liberty_files.empty() && genlib_files.empty();
1028 RTLIL::Design *mapped_design = new RTLIL::Design;
1029 parse_blif(mapped_design, ifs, builtin_lib ? ID(DFF) : ID(_dff_), false, sop_mode);
1030
1031 ifs.close();
1032
1033 log_header(design, "Re-integrating ABC results.\n");
1034 RTLIL::Module *mapped_mod = mapped_design->module(ID(netlist));
1035 if (mapped_mod == nullptr)
1036 log_error("ABC output file does not contain a module `netlist'.\n");
1037 for (auto w : mapped_mod->wires()) {
1038 RTLIL::Wire *orig_wire = nullptr;
1039 RTLIL::Wire *wire = module->addWire(remap_name(w->name, &orig_wire));
1040 if (orig_wire != nullptr && orig_wire->attributes.count(ID::src))
1041 wire->attributes[ID::src] = orig_wire->attributes[ID::src];
1042 if (markgroups) wire->attributes[ID::abcgroup] = map_autoidx;
1043 design->select(module, wire);
1044 }
1045
1046 std::map<std::string, int> cell_stats;
1047 for (auto c : mapped_mod->cells())
1048 {
1049 if (builtin_lib)
1050 {
1051 cell_stats[RTLIL::unescape_id(c->type)]++;
1052 if (c->type.in(ID(ZERO), ID(ONE))) {
1053 RTLIL::SigSig conn;
1054 RTLIL::IdString name_y = remap_name(c->getPort(ID::Y).as_wire()->name);
1055 conn.first = module->wire(name_y);
1056 conn.second = RTLIL::SigSpec(c->type == ID(ZERO) ? 0 : 1, 1);
1057 module->connect(conn);
1058 continue;
1059 }
1060 if (c->type == ID(BUF)) {
1061 RTLIL::SigSig conn;
1062 RTLIL::IdString name_y = remap_name(c->getPort(ID::Y).as_wire()->name);
1063 RTLIL::IdString name_a = remap_name(c->getPort(ID::A).as_wire()->name);
1064 conn.first = module->wire(name_y);
1065 conn.second = module->wire(name_a);
1066 module->connect(conn);
1067 continue;
1068 }
1069 if (c->type == ID(NOT)) {
1070 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_NOT_));
1071 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1072 for (auto name : {ID::A, ID::Y}) {
1073 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1074 cell->setPort(name, module->wire(remapped_name));
1075 }
1076 design->select(module, cell);
1077 continue;
1078 }
1079 if (c->type.in(ID(AND), ID(OR), ID(XOR), ID(NAND), ID(NOR), ID(XNOR), ID(ANDNOT), ID(ORNOT))) {
1080 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1081 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1082 for (auto name : {ID::A, ID::B, ID::Y}) {
1083 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1084 cell->setPort(name, module->wire(remapped_name));
1085 }
1086 design->select(module, cell);
1087 continue;
1088 }
1089 if (c->type.in(ID(MUX), ID(NMUX))) {
1090 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1091 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1092 for (auto name : {ID::A, ID::B, ID::S, ID::Y}) {
1093 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1094 cell->setPort(name, module->wire(remapped_name));
1095 }
1096 design->select(module, cell);
1097 continue;
1098 }
1099 if (c->type == ID(MUX4)) {
1100 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX4_));
1101 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1102 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::S, ID::T, ID::Y}) {
1103 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1104 cell->setPort(name, module->wire(remapped_name));
1105 }
1106 design->select(module, cell);
1107 continue;
1108 }
1109 if (c->type == ID(MUX8)) {
1110 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX8_));
1111 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1112 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::S, ID::T, ID::U, ID::Y}) {
1113 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1114 cell->setPort(name, module->wire(remapped_name));
1115 }
1116 design->select(module, cell);
1117 continue;
1118 }
1119 if (c->type == ID(MUX16)) {
1120 RTLIL::Cell *cell = module->addCell(remap_name(c->name), ID($_MUX16_));
1121 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1122 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::E, ID::F, ID::G, ID::H, ID::I, ID::J, ID::K,
1123 ID::L, ID::M, ID::N, ID::O, ID::P, ID::S, ID::T, ID::U, ID::V, ID::Y}) {
1124 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1125 cell->setPort(name, module->wire(remapped_name));
1126 }
1127 design->select(module, cell);
1128 continue;
1129 }
1130 if (c->type.in(ID(AOI3), ID(OAI3))) {
1131 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1132 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1133 for (auto name : {ID::A, ID::B, ID::C, ID::Y}) {
1134 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1135 cell->setPort(name, module->wire(remapped_name));
1136 }
1137 design->select(module, cell);
1138 continue;
1139 }
1140 if (c->type.in(ID(AOI4), ID(OAI4))) {
1141 RTLIL::Cell *cell = module->addCell(remap_name(c->name), stringf("$_%s_", c->type.c_str()+1));
1142 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1143 for (auto name : {ID::A, ID::B, ID::C, ID::D, ID::Y}) {
1144 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1145 cell->setPort(name, module->wire(remapped_name));
1146 }
1147 design->select(module, cell);
1148 continue;
1149 }
1150 if (c->type == ID(DFF)) {
1151 log_assert(clk_sig.size() == 1);
1152 RTLIL::Cell *cell;
1153 if (en_sig.size() == 0) {
1154 cell = module->addCell(remap_name(c->name), clk_polarity ? ID($_DFF_P_) : ID($_DFF_N_));
1155 } else {
1156 log_assert(en_sig.size() == 1);
1157 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
1158 cell->setPort(ID::E, en_sig);
1159 }
1160 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1161 for (auto name : {ID::D, ID::Q}) {
1162 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1163 cell->setPort(name, module->wire(remapped_name));
1164 }
1165 cell->setPort(ID::C, clk_sig);
1166 design->select(module, cell);
1167 continue;
1168 }
1169 }
1170 else
1171 cell_stats[RTLIL::unescape_id(c->type)]++;
1172
1173 if (c->type.in(ID(_const0_), ID(_const1_))) {
1174 RTLIL::SigSig conn;
1175 conn.first = module->wire(remap_name(c->connections().begin()->second.as_wire()->name));
1176 conn.second = RTLIL::SigSpec(c->type == ID(_const0_) ? 0 : 1, 1);
1177 module->connect(conn);
1178 continue;
1179 }
1180
1181 if (c->type == ID(_dff_)) {
1182 log_assert(clk_sig.size() == 1);
1183 RTLIL::Cell *cell;
1184 if (en_sig.size() == 0) {
1185 cell = module->addCell(remap_name(c->name), clk_polarity ? ID($_DFF_P_) : ID($_DFF_N_));
1186 } else {
1187 log_assert(en_sig.size() == 1);
1188 cell = module->addCell(remap_name(c->name), stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
1189 cell->setPort(ID::E, en_sig);
1190 }
1191 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1192 for (auto name : {ID::D, ID::Q}) {
1193 RTLIL::IdString remapped_name = remap_name(c->getPort(name).as_wire()->name);
1194 cell->setPort(name, module->wire(remapped_name));
1195 }
1196 cell->setPort(ID::C, clk_sig);
1197 design->select(module, cell);
1198 continue;
1199 }
1200
1201 if (c->type == ID($lut) && GetSize(c->getPort(ID::A)) == 1 && c->getParam(ID::LUT).as_int() == 2) {
1202 SigSpec my_a = module->wire(remap_name(c->getPort(ID::A).as_wire()->name));
1203 SigSpec my_y = module->wire(remap_name(c->getPort(ID::Y).as_wire()->name));
1204 module->connect(my_y, my_a);
1205 continue;
1206 }
1207
1208 RTLIL::Cell *cell = module->addCell(remap_name(c->name), c->type);
1209 if (markgroups) cell->attributes[ID::abcgroup] = map_autoidx;
1210 cell->parameters = c->parameters;
1211 for (auto &conn : c->connections()) {
1212 RTLIL::SigSpec newsig;
1213 for (auto &c : conn.second.chunks()) {
1214 if (c.width == 0)
1215 continue;
1216 log_assert(c.width == 1);
1217 newsig.append(module->wire(remap_name(c.wire->name)));
1218 }
1219 cell->setPort(conn.first, newsig);
1220 }
1221 design->select(module, cell);
1222 }
1223
1224 for (auto conn : mapped_mod->connections()) {
1225 if (!conn.first.is_fully_const())
1226 conn.first = module->wire(remap_name(conn.first.as_wire()->name));
1227 if (!conn.second.is_fully_const())
1228 conn.second = module->wire(remap_name(conn.second.as_wire()->name));
1229 module->connect(conn);
1230 }
1231
1232 if (recover_init)
1233 for (auto wire : mapped_mod->wires()) {
1234 if (wire->attributes.count(ID::init)) {
1235 Wire *w = module->wire(remap_name(wire->name));
1236 log_assert(w->attributes.count(ID::init) == 0);
1237 w->attributes[ID::init] = wire->attributes.at(ID::init);
1238 }
1239 }
1240
1241 for (auto &it : cell_stats)
1242 log("ABC RESULTS: %15s cells: %8d\n", it.first.c_str(), it.second);
1243 int in_wires = 0, out_wires = 0;
1244 for (auto &si : signal_list)
1245 if (si.is_port) {
1246 char buffer[100];
1247 snprintf(buffer, 100, "\\ys__n%d", si.id);
1248 RTLIL::SigSig conn;
1249 if (si.type != G(NONE)) {
1250 conn.first = si.bit;
1251 conn.second = module->wire(remap_name(buffer));
1252 out_wires++;
1253 } else {
1254 conn.first = module->wire(remap_name(buffer));
1255 conn.second = si.bit;
1256 in_wires++;
1257 }
1258 module->connect(conn);
1259 }
1260 log("ABC RESULTS: internal signals: %8d\n", int(signal_list.size()) - in_wires - out_wires);
1261 log("ABC RESULTS: input signals: %8d\n", in_wires);
1262 log("ABC RESULTS: output signals: %8d\n", out_wires);
1263
1264 delete mapped_design;
1265 }
1266 else
1267 {
1268 log("Don't call ABC as there is nothing to map.\n");
1269 }
1270
1271 if (cleanup)
1272 {
1273 log("Removing temp directory.\n");
1274 remove_directory(tempdir_name);
1275 }
1276
1277 log_pop();
1278 }
1279
1280 struct AbcPass : public Pass {
AbcPassAbcPass1281 AbcPass() : Pass("abc", "use ABC for technology mapping") { }
helpAbcPass1282 void help() override
1283 {
1284 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1285 log("\n");
1286 log(" abc [options] [selection]\n");
1287 log("\n");
1288 log("This pass uses the ABC tool [1] for technology mapping of yosys's internal gate\n");
1289 log("library to a target architecture.\n");
1290 log("\n");
1291 log(" -exe <command>\n");
1292 #ifdef ABCEXTERNAL
1293 log(" use the specified command instead of \"" ABCEXTERNAL "\" to execute ABC.\n");
1294 #else
1295 log(" use the specified command instead of \"<yosys-bindir>/%syosys-abc\" to execute ABC.\n", proc_program_prefix().c_str());
1296 #endif
1297 log(" This can e.g. be used to call a specific version of ABC or a wrapper.\n");
1298 log("\n");
1299 log(" -script <file>\n");
1300 log(" use the specified ABC script file instead of the default script.\n");
1301 log("\n");
1302 log(" if <file> starts with a plus sign (+), then the rest of the filename\n");
1303 log(" string is interpreted as the command string to be passed to ABC. The\n");
1304 log(" leading plus sign is removed and all commas (,) in the string are\n");
1305 log(" replaced with blanks before the string is passed to ABC.\n");
1306 log("\n");
1307 log(" if no -script parameter is given, the following scripts are used:\n");
1308 log("\n");
1309 log(" for -liberty/-genlib without -constr:\n");
1310 log("%s\n", fold_abc_cmd(ABC_COMMAND_LIB).c_str());
1311 log("\n");
1312 log(" for -liberty/-genlib with -constr:\n");
1313 log("%s\n", fold_abc_cmd(ABC_COMMAND_CTR).c_str());
1314 log("\n");
1315 log(" for -lut/-luts (only one LUT size):\n");
1316 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT "; lutpack {S}").c_str());
1317 log("\n");
1318 log(" for -lut/-luts (different LUT sizes):\n");
1319 log("%s\n", fold_abc_cmd(ABC_COMMAND_LUT).c_str());
1320 log("\n");
1321 log(" for -sop:\n");
1322 log("%s\n", fold_abc_cmd(ABC_COMMAND_SOP).c_str());
1323 log("\n");
1324 log(" otherwise:\n");
1325 log("%s\n", fold_abc_cmd(ABC_COMMAND_DFL).c_str());
1326 log("\n");
1327 log(" -fast\n");
1328 log(" use different default scripts that are slightly faster (at the cost\n");
1329 log(" of output quality):\n");
1330 log("\n");
1331 log(" for -liberty/-genlib without -constr:\n");
1332 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LIB).c_str());
1333 log("\n");
1334 log(" for -liberty/-genlib with -constr:\n");
1335 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_CTR).c_str());
1336 log("\n");
1337 log(" for -lut/-luts:\n");
1338 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_LUT).c_str());
1339 log("\n");
1340 log(" for -sop:\n");
1341 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_SOP).c_str());
1342 log("\n");
1343 log(" otherwise:\n");
1344 log("%s\n", fold_abc_cmd(ABC_FAST_COMMAND_DFL).c_str());
1345 log("\n");
1346 log(" -liberty <file>\n");
1347 log(" generate netlists for the specified cell library (using the liberty\n");
1348 log(" file format).\n");
1349 log("\n");
1350 log(" -genlib <file>\n");
1351 log(" generate netlists for the specified cell library (using the SIS Genlib\n");
1352 log(" file format).\n");
1353 log("\n");
1354 log(" -constr <file>\n");
1355 log(" pass this file with timing constraints to ABC.\n");
1356 log(" use with -liberty/-genlib.\n");
1357 log("\n");
1358 log(" a constr file contains two lines:\n");
1359 log(" set_driving_cell <cell_name>\n");
1360 log(" set_load <floating_point_number>\n");
1361 log("\n");
1362 log(" the set_driving_cell statement defines which cell type is assumed to\n");
1363 log(" drive the primary inputs and the set_load statement sets the load in\n");
1364 log(" femtofarads for each primary output.\n");
1365 log("\n");
1366 log(" -D <picoseconds>\n");
1367 log(" set delay target. the string {D} in the default scripts above is\n");
1368 log(" replaced by this option when used, and an empty string otherwise.\n");
1369 log(" this also replaces 'dretime' with 'dretime; retime -o {D}' in the\n");
1370 log(" default scripts above.\n");
1371 log("\n");
1372 log(" -I <num>\n");
1373 log(" maximum number of SOP inputs.\n");
1374 log(" (replaces {I} in the default scripts above)\n");
1375 log("\n");
1376 log(" -P <num>\n");
1377 log(" maximum number of SOP products.\n");
1378 log(" (replaces {P} in the default scripts above)\n");
1379 log("\n");
1380 log(" -S <num>\n");
1381 log(" maximum number of LUT inputs shared.\n");
1382 log(" (replaces {S} in the default scripts above, default: -S 1)\n");
1383 log("\n");
1384 log(" -lut <width>\n");
1385 log(" generate netlist using luts of (max) the specified width.\n");
1386 log("\n");
1387 log(" -lut <w1>:<w2>\n");
1388 log(" generate netlist using luts of (max) the specified width <w2>. All\n");
1389 log(" luts with width <= <w1> have constant cost. for luts larger than <w1>\n");
1390 log(" the area cost doubles with each additional input bit. the delay cost\n");
1391 log(" is still constant for all lut widths.\n");
1392 log("\n");
1393 log(" -luts <cost1>,<cost2>,<cost3>,<sizeN>:<cost4-N>,..\n");
1394 log(" generate netlist using luts. Use the specified costs for luts with 1,\n");
1395 log(" 2, 3, .. inputs.\n");
1396 log("\n");
1397 log(" -sop\n");
1398 log(" map to sum-of-product cells and inverters\n");
1399 log("\n");
1400 // log(" -mux4, -mux8, -mux16\n");
1401 // log(" try to extract 4-input, 8-input, and/or 16-input muxes\n");
1402 // log(" (ignored when used with -liberty/-genlib or -lut)\n");
1403 // log("\n");
1404 log(" -g type1,type2,...\n");
1405 log(" Map to the specified list of gate types. Supported gates types are:\n");
1406 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
1407 log(" AND, NAND, OR, NOR, XOR, XNOR, ANDNOT, ORNOT, MUX,\n");
1408 log(" NMUX, AOI3, OAI3, AOI4, OAI4.\n");
1409 log(" (The NOT gate is always added to this list automatically.)\n");
1410 log("\n");
1411 log(" The following aliases can be used to reference common sets of gate types:\n");
1412 log(" simple: AND OR XOR MUX\n");
1413 log(" cmos2: NAND NOR\n");
1414 log(" cmos3: NAND NOR AOI3 OAI3\n");
1415 log(" cmos4: NAND NOR AOI3 OAI3 AOI4 OAI4\n");
1416 log(" cmos: NAND NOR AOI3 OAI3 AOI4 OAI4 NMUX MUX XOR XNOR\n");
1417 log(" gates: AND NAND OR NOR XOR XNOR ANDNOT ORNOT\n");
1418 log(" aig: AND NAND OR NOR ANDNOT ORNOT\n");
1419 log("\n");
1420 log(" The alias 'all' represent the full set of all gate types.\n");
1421 log("\n");
1422 log(" Prefix a gate type with a '-' to remove it from the list. For example\n");
1423 log(" the arguments 'AND,OR,XOR' and 'simple,-MUX' are equivalent.\n");
1424 log("\n");
1425 log(" The default is 'all,-NMUX,-AOI3,-OAI3,-AOI4,-OAI4'.\n");
1426 log("\n");
1427 log(" -dff\n");
1428 log(" also pass $_DFF_?_ and $_DFFE_??_ cells through ABC. modules with many\n");
1429 log(" clock domains are automatically partitioned in clock domains and each\n");
1430 log(" domain is passed through ABC independently.\n");
1431 log("\n");
1432 log(" -clk [!]<clock-signal-name>[,[!]<enable-signal-name>]\n");
1433 log(" use only the specified clock domain. this is like -dff, but only FF\n");
1434 log(" cells that belong to the specified clock domain are used.\n");
1435 log("\n");
1436 log(" -keepff\n");
1437 log(" set the \"keep\" attribute on flip-flop output wires. (and thus preserve\n");
1438 log(" them, for example for equivalence checking.)\n");
1439 log("\n");
1440 log(" -nocleanup\n");
1441 log(" when this option is used, the temporary files created by this pass\n");
1442 log(" are not removed. this is useful for debugging.\n");
1443 log("\n");
1444 log(" -showtmp\n");
1445 log(" print the temp dir name in log. usually this is suppressed so that the\n");
1446 log(" command output is identical across runs.\n");
1447 log("\n");
1448 log(" -markgroups\n");
1449 log(" set a 'abcgroup' attribute on all objects created by ABC. The value of\n");
1450 log(" this attribute is a unique integer for each ABC process started. This\n");
1451 log(" is useful for debugging the partitioning of clock domains.\n");
1452 log("\n");
1453 log(" -dress\n");
1454 log(" run the 'dress' command after all other ABC commands. This aims to\n");
1455 log(" preserve naming by an equivalence check between the original and post-ABC\n");
1456 log(" netlists (experimental).\n");
1457 log("\n");
1458 log("When no target cell library is specified the Yosys standard cell library is\n");
1459 log("loaded into ABC before the ABC script is executed.\n");
1460 log("\n");
1461 log("Note that this is a logic optimization pass within Yosys that is calling ABC\n");
1462 log("internally. This is not going to \"run ABC on your design\". It will instead run\n");
1463 log("ABC on logic snippets extracted from your design. You will not get any useful\n");
1464 log("output when passing an ABC script that writes a file. Instead write your full\n");
1465 log("design as BLIF file with write_blif and then load that into ABC externally if\n");
1466 log("you want to use ABC to convert your design into another format.\n");
1467 log("\n");
1468 log("[1] http://www.eecs.berkeley.edu/~alanmi/abc/\n");
1469 log("\n");
1470 }
executeAbcPass1471 void execute(std::vector<std::string> args, RTLIL::Design *design) override
1472 {
1473 log_header(design, "Executing ABC pass (technology mapping using ABC).\n");
1474 log_push();
1475
1476 assign_map.clear();
1477 signal_list.clear();
1478 signal_map.clear();
1479 initvals.clear();
1480 pi_map.clear();
1481 po_map.clear();
1482
1483 std::string exe_file = yosys_abc_executable;
1484 std::string script_file, default_liberty_file, constr_file, clk_str;
1485 std::vector<std::string> liberty_files, genlib_files;
1486 std::string delay_target, sop_inputs, sop_products, lutin_shared = "-S 1";
1487 bool fast_mode = false, dff_mode = false, keepff = false, cleanup = true;
1488 bool show_tempdir = false, sop_mode = false;
1489 bool abc_dress = false;
1490 vector<int> lut_costs;
1491 markgroups = false;
1492
1493 map_mux4 = false;
1494 map_mux8 = false;
1495 map_mux16 = false;
1496 enabled_gates.clear();
1497 cmos_cost = false;
1498
1499 // get arguments from scratchpad first, then override by command arguments
1500 std::string lut_arg, luts_arg, g_arg;
1501 exe_file = design->scratchpad_get_string("abc.exe", exe_file /* inherit default value if not set */);
1502 script_file = design->scratchpad_get_string("abc.script", script_file);
1503 default_liberty_file = design->scratchpad_get_string("abc.liberty", default_liberty_file);
1504 constr_file = design->scratchpad_get_string("abc.constr", constr_file);
1505 if (design->scratchpad.count("abc.D")) {
1506 delay_target = "-D " + design->scratchpad_get_string("abc.D");
1507 }
1508 if (design->scratchpad.count("abc.I")) {
1509 sop_inputs = "-I " + design->scratchpad_get_string("abc.I");
1510 }
1511 if (design->scratchpad.count("abc.P")) {
1512 sop_products = "-P " + design->scratchpad_get_string("abc.P");
1513 }
1514 if (design->scratchpad.count("abc.S")) {
1515 lutin_shared = "-S " + design->scratchpad_get_string("abc.S");
1516 }
1517 lut_arg = design->scratchpad_get_string("abc.lut", lut_arg);
1518 luts_arg = design->scratchpad_get_string("abc.luts", luts_arg);
1519 sop_mode = design->scratchpad_get_bool("abc.sop", sop_mode);
1520 map_mux4 = design->scratchpad_get_bool("abc.mux4", map_mux4);
1521 map_mux8 = design->scratchpad_get_bool("abc.mux8", map_mux8);
1522 map_mux16 = design->scratchpad_get_bool("abc.mux16", map_mux16);
1523 abc_dress = design->scratchpad_get_bool("abc.dress", abc_dress);
1524 g_arg = design->scratchpad_get_string("abc.g", g_arg);
1525
1526 fast_mode = design->scratchpad_get_bool("abc.fast", fast_mode);
1527 dff_mode = design->scratchpad_get_bool("abc.dff", dff_mode);
1528 if (design->scratchpad.count("abc.clk")) {
1529 clk_str = design->scratchpad_get_string("abc.clk");
1530 dff_mode = true;
1531 }
1532 keepff = design->scratchpad_get_bool("abc.keepff", keepff);
1533 cleanup = !design->scratchpad_get_bool("abc.nocleanup", !cleanup);
1534 keepff = design->scratchpad_get_bool("abc.keepff", keepff);
1535 show_tempdir = design->scratchpad_get_bool("abc.showtmp", show_tempdir);
1536 markgroups = design->scratchpad_get_bool("abc.markgroups", markgroups);
1537
1538 if (design->scratchpad_get_bool("abc.debug")) {
1539 cleanup = false;
1540 show_tempdir = true;
1541 }
1542
1543 size_t argidx, g_argidx;
1544 bool g_arg_from_cmd = false;
1545 #if defined(__wasm)
1546 const char *pwd = ".";
1547 #else
1548 char pwd [PATH_MAX];
1549 if (!getcwd(pwd, sizeof(pwd))) {
1550 log_cmd_error("getcwd failed: %s\n", strerror(errno));
1551 log_abort();
1552 }
1553 #endif
1554 for (argidx = 1; argidx < args.size(); argidx++) {
1555 std::string arg = args[argidx];
1556 if (arg == "-exe" && argidx+1 < args.size()) {
1557 exe_file = args[++argidx];
1558 continue;
1559 }
1560 if (arg == "-script" && argidx+1 < args.size()) {
1561 script_file = args[++argidx];
1562 continue;
1563 }
1564 if (arg == "-liberty" && argidx+1 < args.size()) {
1565 liberty_files.push_back(args[++argidx]);
1566 continue;
1567 }
1568 if (arg == "-genlib" && argidx+1 < args.size()) {
1569 genlib_files.push_back(args[++argidx]);
1570 continue;
1571 }
1572 if (arg == "-constr" && argidx+1 < args.size()) {
1573 constr_file = args[++argidx];
1574 continue;
1575 }
1576 if (arg == "-D" && argidx+1 < args.size()) {
1577 delay_target = "-D " + args[++argidx];
1578 continue;
1579 }
1580 if (arg == "-I" && argidx+1 < args.size()) {
1581 sop_inputs = "-I " + args[++argidx];
1582 continue;
1583 }
1584 if (arg == "-P" && argidx+1 < args.size()) {
1585 sop_products = "-P " + args[++argidx];
1586 continue;
1587 }
1588 if (arg == "-S" && argidx+1 < args.size()) {
1589 lutin_shared = "-S " + args[++argidx];
1590 continue;
1591 }
1592 if (arg == "-lut" && argidx+1 < args.size()) {
1593 lut_arg = args[++argidx];
1594 continue;
1595 }
1596 if (arg == "-luts" && argidx+1 < args.size()) {
1597 luts_arg = args[++argidx];
1598 continue;
1599 }
1600 if (arg == "-sop") {
1601 sop_mode = true;
1602 continue;
1603 }
1604 if (arg == "-mux4") {
1605 map_mux4 = true;
1606 continue;
1607 }
1608 if (arg == "-mux8") {
1609 map_mux8 = true;
1610 continue;
1611 }
1612 if (arg == "-mux16") {
1613 map_mux16 = true;
1614 continue;
1615 }
1616 if (arg == "-dress") {
1617 abc_dress = true;
1618 continue;
1619 }
1620 if (arg == "-g" && argidx+1 < args.size()) {
1621 if (g_arg_from_cmd)
1622 log_cmd_error("Can only use -g once. Please combine.");
1623 g_arg = args[++argidx];
1624 g_argidx = argidx;
1625 g_arg_from_cmd = true;
1626 continue;
1627 }
1628 if (arg == "-fast") {
1629 fast_mode = true;
1630 continue;
1631 }
1632 if (arg == "-dff") {
1633 dff_mode = true;
1634 continue;
1635 }
1636 if (arg == "-clk" && argidx+1 < args.size()) {
1637 clk_str = args[++argidx];
1638 dff_mode = true;
1639 continue;
1640 }
1641 if (arg == "-keepff") {
1642 keepff = true;
1643 continue;
1644 }
1645 if (arg == "-nocleanup") {
1646 cleanup = false;
1647 continue;
1648 }
1649 if (arg == "-showtmp") {
1650 show_tempdir = true;
1651 continue;
1652 }
1653 if (arg == "-markgroups") {
1654 markgroups = true;
1655 continue;
1656 }
1657 break;
1658 }
1659 extra_args(args, argidx, design);
1660
1661 if (genlib_files.empty() && liberty_files.empty() && !default_liberty_file.empty())
1662 liberty_files.push_back(default_liberty_file);
1663
1664 rewrite_filename(script_file);
1665 if (!script_file.empty() && !is_absolute_path(script_file) && script_file[0] != '+')
1666 script_file = std::string(pwd) + "/" + script_file;
1667 for (int i = 0; i < GetSize(liberty_files); i++) {
1668 rewrite_filename(liberty_files[i]);
1669 if (!liberty_files[i].empty() && !is_absolute_path(liberty_files[i]))
1670 liberty_files[i] = std::string(pwd) + "/" + liberty_files[i];
1671 }
1672 for (int i = 0; i < GetSize(genlib_files); i++) {
1673 rewrite_filename(genlib_files[i]);
1674 if (!genlib_files[i].empty() && !is_absolute_path(genlib_files[i]))
1675 genlib_files[i] = std::string(pwd) + "/" + genlib_files[i];
1676 }
1677 rewrite_filename(constr_file);
1678 if (!constr_file.empty() && !is_absolute_path(constr_file))
1679 constr_file = std::string(pwd) + "/" + constr_file;
1680
1681 // handle -lut argument
1682 if (!lut_arg.empty()) {
1683 size_t pos = lut_arg.find_first_of(':');
1684 int lut_mode = 0, lut_mode2 = 0;
1685 if (pos != string::npos) {
1686 lut_mode = atoi(lut_arg.substr(0, pos).c_str());
1687 lut_mode2 = atoi(lut_arg.substr(pos+1).c_str());
1688 } else {
1689 lut_mode = atoi(lut_arg.c_str());
1690 lut_mode2 = lut_mode;
1691 }
1692 lut_costs.clear();
1693 for (int i = 0; i < lut_mode; i++)
1694 lut_costs.push_back(1);
1695 for (int i = lut_mode; i < lut_mode2; i++)
1696 lut_costs.push_back(2 << (i - lut_mode));
1697 }
1698 //handle -luts argument
1699 if (!luts_arg.empty()){
1700 lut_costs.clear();
1701 for (auto &tok : split_tokens(luts_arg, ",")) {
1702 auto parts = split_tokens(tok, ":");
1703 if (GetSize(parts) == 0 && !lut_costs.empty())
1704 lut_costs.push_back(lut_costs.back());
1705 else if (GetSize(parts) == 1)
1706 lut_costs.push_back(atoi(parts.at(0).c_str()));
1707 else if (GetSize(parts) == 2)
1708 while (GetSize(lut_costs) < std::atoi(parts.at(0).c_str()))
1709 lut_costs.push_back(atoi(parts.at(1).c_str()));
1710 else
1711 log_cmd_error("Invalid -luts syntax.\n");
1712 }
1713 }
1714
1715 // handle -g argument
1716 if (!g_arg.empty()){
1717 for (auto g : split_tokens(g_arg, ",")) {
1718 vector<string> gate_list;
1719 bool remove_gates = false;
1720 if (GetSize(g) > 0 && g[0] == '-') {
1721 remove_gates = true;
1722 g = g.substr(1);
1723 }
1724 if (g == "AND") goto ok_gate;
1725 if (g == "NAND") goto ok_gate;
1726 if (g == "OR") goto ok_gate;
1727 if (g == "NOR") goto ok_gate;
1728 if (g == "XOR") goto ok_gate;
1729 if (g == "XNOR") goto ok_gate;
1730 if (g == "ANDNOT") goto ok_gate;
1731 if (g == "ORNOT") goto ok_gate;
1732 if (g == "MUX") goto ok_gate;
1733 if (g == "NMUX") goto ok_gate;
1734 if (g == "AOI3") goto ok_gate;
1735 if (g == "OAI3") goto ok_gate;
1736 if (g == "AOI4") goto ok_gate;
1737 if (g == "OAI4") goto ok_gate;
1738 if (g == "simple") {
1739 gate_list.push_back("AND");
1740 gate_list.push_back("OR");
1741 gate_list.push_back("XOR");
1742 gate_list.push_back("MUX");
1743 goto ok_alias;
1744 }
1745 if (g == "cmos2") {
1746 if (!remove_gates)
1747 cmos_cost = true;
1748 gate_list.push_back("NAND");
1749 gate_list.push_back("NOR");
1750 goto ok_alias;
1751 }
1752 if (g == "cmos3") {
1753 if (!remove_gates)
1754 cmos_cost = true;
1755 gate_list.push_back("NAND");
1756 gate_list.push_back("NOR");
1757 gate_list.push_back("AOI3");
1758 gate_list.push_back("OAI3");
1759 goto ok_alias;
1760 }
1761 if (g == "cmos4") {
1762 if (!remove_gates)
1763 cmos_cost = true;
1764 gate_list.push_back("NAND");
1765 gate_list.push_back("NOR");
1766 gate_list.push_back("AOI3");
1767 gate_list.push_back("OAI3");
1768 gate_list.push_back("AOI4");
1769 gate_list.push_back("OAI4");
1770 goto ok_alias;
1771 }
1772 if (g == "cmos") {
1773 if (!remove_gates)
1774 cmos_cost = true;
1775 gate_list.push_back("NAND");
1776 gate_list.push_back("NOR");
1777 gate_list.push_back("AOI3");
1778 gate_list.push_back("OAI3");
1779 gate_list.push_back("AOI4");
1780 gate_list.push_back("OAI4");
1781 gate_list.push_back("NMUX");
1782 gate_list.push_back("MUX");
1783 gate_list.push_back("XOR");
1784 gate_list.push_back("XNOR");
1785 goto ok_alias;
1786 }
1787 if (g == "gates") {
1788 gate_list.push_back("AND");
1789 gate_list.push_back("NAND");
1790 gate_list.push_back("OR");
1791 gate_list.push_back("NOR");
1792 gate_list.push_back("XOR");
1793 gate_list.push_back("XNOR");
1794 gate_list.push_back("ANDNOT");
1795 gate_list.push_back("ORNOT");
1796 goto ok_alias;
1797 }
1798 if (g == "aig") {
1799 gate_list.push_back("AND");
1800 gate_list.push_back("NAND");
1801 gate_list.push_back("OR");
1802 gate_list.push_back("NOR");
1803 gate_list.push_back("ANDNOT");
1804 gate_list.push_back("ORNOT");
1805 goto ok_alias;
1806 }
1807 if (g == "all") {
1808 gate_list.push_back("AND");
1809 gate_list.push_back("NAND");
1810 gate_list.push_back("OR");
1811 gate_list.push_back("NOR");
1812 gate_list.push_back("XOR");
1813 gate_list.push_back("XNOR");
1814 gate_list.push_back("ANDNOT");
1815 gate_list.push_back("ORNOT");
1816 gate_list.push_back("AOI3");
1817 gate_list.push_back("OAI3");
1818 gate_list.push_back("AOI4");
1819 gate_list.push_back("OAI4");
1820 gate_list.push_back("MUX");
1821 gate_list.push_back("NMUX");
1822 goto ok_alias;
1823 }
1824 if (g_arg_from_cmd)
1825 cmd_error(args, g_argidx, stringf("Unsupported gate type: %s", g.c_str()));
1826 else
1827 log_cmd_error("Unsupported gate type: %s", g.c_str());
1828 ok_gate:
1829 gate_list.push_back(g);
1830 ok_alias:
1831 for (auto gate : gate_list) {
1832 if (remove_gates)
1833 enabled_gates.erase(gate);
1834 else
1835 enabled_gates.insert(gate);
1836 }
1837 }
1838 }
1839
1840 if (!lut_costs.empty() && !(liberty_files.empty() && genlib_files.empty()))
1841 log_cmd_error("Got -lut and -liberty/-genlib! These two options are exclusive.\n");
1842 if (!constr_file.empty() && (liberty_files.empty() && genlib_files.empty()))
1843 log_cmd_error("Got -constr but no -liberty/-genlib!\n");
1844
1845 if (enabled_gates.empty()) {
1846 enabled_gates.insert("AND");
1847 enabled_gates.insert("NAND");
1848 enabled_gates.insert("OR");
1849 enabled_gates.insert("NOR");
1850 enabled_gates.insert("XOR");
1851 enabled_gates.insert("XNOR");
1852 enabled_gates.insert("ANDNOT");
1853 enabled_gates.insert("ORNOT");
1854 // enabled_gates.insert("AOI3");
1855 // enabled_gates.insert("OAI3");
1856 // enabled_gates.insert("AOI4");
1857 // enabled_gates.insert("OAI4");
1858 enabled_gates.insert("MUX");
1859 // enabled_gates.insert("NMUX");
1860 }
1861
1862 for (auto mod : design->selected_modules())
1863 {
1864 if (mod->processes.size() > 0) {
1865 log("Skipping module %s as it contains processes.\n", log_id(mod));
1866 continue;
1867 }
1868
1869 assign_map.set(mod);
1870 initvals.set(&assign_map, mod);
1871
1872 if (!dff_mode || !clk_str.empty()) {
1873 abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, dff_mode, clk_str, keepff,
1874 delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, mod->selected_cells(), show_tempdir, sop_mode, abc_dress);
1875 continue;
1876 }
1877
1878 CellTypes ct(design);
1879
1880 std::vector<RTLIL::Cell*> all_cells = mod->selected_cells();
1881 std::set<RTLIL::Cell*> unassigned_cells(all_cells.begin(), all_cells.end());
1882
1883 std::set<RTLIL::Cell*> expand_queue, next_expand_queue;
1884 std::set<RTLIL::Cell*> expand_queue_up, next_expand_queue_up;
1885 std::set<RTLIL::Cell*> expand_queue_down, next_expand_queue_down;
1886
1887 typedef tuple<bool, RTLIL::SigSpec, bool, RTLIL::SigSpec> clkdomain_t;
1888 std::map<clkdomain_t, std::vector<RTLIL::Cell*>> assigned_cells;
1889 std::map<RTLIL::Cell*, clkdomain_t> assigned_cells_reverse;
1890
1891 std::map<RTLIL::Cell*, std::set<RTLIL::SigBit>> cell_to_bit, cell_to_bit_up, cell_to_bit_down;
1892 std::map<RTLIL::SigBit, std::set<RTLIL::Cell*>> bit_to_cell, bit_to_cell_up, bit_to_cell_down;
1893
1894 for (auto cell : all_cells)
1895 {
1896 clkdomain_t key;
1897
1898 for (auto &conn : cell->connections())
1899 for (auto bit : conn.second) {
1900 bit = assign_map(bit);
1901 if (bit.wire != nullptr) {
1902 cell_to_bit[cell].insert(bit);
1903 bit_to_cell[bit].insert(cell);
1904 if (ct.cell_input(cell->type, conn.first)) {
1905 cell_to_bit_up[cell].insert(bit);
1906 bit_to_cell_down[bit].insert(cell);
1907 }
1908 if (ct.cell_output(cell->type, conn.first)) {
1909 cell_to_bit_down[cell].insert(bit);
1910 bit_to_cell_up[bit].insert(cell);
1911 }
1912 }
1913 }
1914
1915 if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_)))
1916 {
1917 key = clkdomain_t(cell->type == ID($_DFF_P_), assign_map(cell->getPort(ID::C)), true, RTLIL::SigSpec());
1918 }
1919 else
1920 if (cell->type.in(ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
1921 {
1922 bool this_clk_pol = cell->type.in(ID($_DFFE_PN_), ID($_DFFE_PP_));
1923 bool this_en_pol = cell->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_));
1924 key = clkdomain_t(this_clk_pol, assign_map(cell->getPort(ID::C)), this_en_pol, assign_map(cell->getPort(ID::E)));
1925 }
1926 else
1927 continue;
1928
1929 unassigned_cells.erase(cell);
1930 expand_queue.insert(cell);
1931 expand_queue_up.insert(cell);
1932 expand_queue_down.insert(cell);
1933
1934 assigned_cells[key].push_back(cell);
1935 assigned_cells_reverse[cell] = key;
1936 }
1937
1938 while (!expand_queue_up.empty() || !expand_queue_down.empty())
1939 {
1940 if (!expand_queue_up.empty())
1941 {
1942 RTLIL::Cell *cell = *expand_queue_up.begin();
1943 clkdomain_t key = assigned_cells_reverse.at(cell);
1944 expand_queue_up.erase(cell);
1945
1946 for (auto bit : cell_to_bit_up[cell])
1947 for (auto c : bit_to_cell_up[bit])
1948 if (unassigned_cells.count(c)) {
1949 unassigned_cells.erase(c);
1950 next_expand_queue_up.insert(c);
1951 assigned_cells[key].push_back(c);
1952 assigned_cells_reverse[c] = key;
1953 expand_queue.insert(c);
1954 }
1955 }
1956
1957 if (!expand_queue_down.empty())
1958 {
1959 RTLIL::Cell *cell = *expand_queue_down.begin();
1960 clkdomain_t key = assigned_cells_reverse.at(cell);
1961 expand_queue_down.erase(cell);
1962
1963 for (auto bit : cell_to_bit_down[cell])
1964 for (auto c : bit_to_cell_down[bit])
1965 if (unassigned_cells.count(c)) {
1966 unassigned_cells.erase(c);
1967 next_expand_queue_up.insert(c);
1968 assigned_cells[key].push_back(c);
1969 assigned_cells_reverse[c] = key;
1970 expand_queue.insert(c);
1971 }
1972 }
1973
1974 if (expand_queue_up.empty() && expand_queue_down.empty()) {
1975 expand_queue_up.swap(next_expand_queue_up);
1976 expand_queue_down.swap(next_expand_queue_down);
1977 }
1978 }
1979
1980 while (!expand_queue.empty())
1981 {
1982 RTLIL::Cell *cell = *expand_queue.begin();
1983 clkdomain_t key = assigned_cells_reverse.at(cell);
1984 expand_queue.erase(cell);
1985
1986 for (auto bit : cell_to_bit.at(cell)) {
1987 for (auto c : bit_to_cell[bit])
1988 if (unassigned_cells.count(c)) {
1989 unassigned_cells.erase(c);
1990 next_expand_queue.insert(c);
1991 assigned_cells[key].push_back(c);
1992 assigned_cells_reverse[c] = key;
1993 }
1994 bit_to_cell[bit].clear();
1995 }
1996
1997 if (expand_queue.empty())
1998 expand_queue.swap(next_expand_queue);
1999 }
2000
2001 clkdomain_t key(true, RTLIL::SigSpec(), true, RTLIL::SigSpec());
2002 for (auto cell : unassigned_cells) {
2003 assigned_cells[key].push_back(cell);
2004 assigned_cells_reverse[cell] = key;
2005 }
2006
2007 log_header(design, "Summary of detected clock domains:\n");
2008 for (auto &it : assigned_cells)
2009 log(" %d cells in clk=%s%s, en=%s%s\n", GetSize(it.second),
2010 std::get<0>(it.first) ? "" : "!", log_signal(std::get<1>(it.first)),
2011 std::get<2>(it.first) ? "" : "!", log_signal(std::get<3>(it.first)));
2012
2013 for (auto &it : assigned_cells) {
2014 clk_polarity = std::get<0>(it.first);
2015 clk_sig = assign_map(std::get<1>(it.first));
2016 en_polarity = std::get<2>(it.first);
2017 en_sig = assign_map(std::get<3>(it.first));
2018 abc_module(design, mod, script_file, exe_file, liberty_files, genlib_files, constr_file, cleanup, lut_costs, !clk_sig.empty(), "$",
2019 keepff, delay_target, sop_inputs, sop_products, lutin_shared, fast_mode, it.second, show_tempdir, sop_mode, abc_dress);
2020 assign_map.set(mod);
2021 }
2022 }
2023
2024 assign_map.clear();
2025 signal_list.clear();
2026 signal_map.clear();
2027 initvals.clear();
2028 pi_map.clear();
2029 po_map.clear();
2030
2031 log_pop();
2032 }
2033 } AbcPass;
2034
2035 PRIVATE_NAMESPACE_END
2036