write_aiger() to perform CI/CO post-processing and fix symbols
[yosys.git] / backends / aiger / xaiger.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
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 #include "kernel/yosys.h"
21 #include "kernel/sigtools.h"
22
23 USING_YOSYS_NAMESPACE
24 PRIVATE_NAMESPACE_BEGIN
25
26 void aiger_encode(std::ostream &f, int x)
27 {
28 log_assert(x >= 0);
29
30 while (x & ~0x7f) {
31 f.put((x & 0x7f) | 0x80);
32 x = x >> 7;
33 }
34
35 f.put(x);
36 }
37
38 struct XAigerWriter
39 {
40 Module *module;
41 bool zinit_mode;
42 SigMap sigmap;
43
44 dict<SigBit, bool> init_map;
45 pool<SigBit> input_bits, output_bits;
46 dict<SigBit, SigBit> not_map, ff_map, alias_map;
47 dict<SigBit, pair<SigBit, SigBit>> and_map;
48 pool<SigBit> initstate_bits;
49 pool<SigBit> ci_bits, co_bits;
50 dict<IdString, unsigned> type_map;
51
52 vector<pair<int, int>> aig_gates;
53 vector<int> aig_latchin, aig_latchinit, aig_outputs;
54 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
55
56 dict<SigBit, int> aig_map;
57 dict<SigBit, int> ordered_outputs;
58 dict<SigBit, int> ordered_latches;
59
60 dict<SigBit, int> init_inputs;
61 int initstate_ff = 0;
62
63 int mkgate(int a0, int a1)
64 {
65 aig_m++, aig_a++;
66 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
67 return 2*aig_m;
68 }
69
70 int bit2aig(SigBit bit)
71 {
72 if (aig_map.count(bit) == 0)
73 {
74 aig_map[bit] = -1;
75
76 if (initstate_bits.count(bit)) {
77 log_assert(initstate_ff > 0);
78 aig_map[bit] = initstate_ff;
79 } else
80 if (not_map.count(bit)) {
81 int a = bit2aig(not_map.at(bit)) ^ 1;
82 aig_map[bit] = a;
83 } else
84 if (and_map.count(bit)) {
85 auto args = and_map.at(bit);
86 int a0 = bit2aig(args.first);
87 int a1 = bit2aig(args.second);
88 aig_map[bit] = mkgate(a0, a1);
89 } else
90 if (alias_map.count(bit)) {
91 aig_map[bit] = bit2aig(alias_map.at(bit));
92 }
93
94 if (bit == State::Sx || bit == State::Sz)
95 log_error("Design contains 'x' or 'z' bits. Use 'setundef' to replace those constants.\n");
96 }
97
98 log_assert(aig_map.at(bit) >= 0);
99 return aig_map.at(bit);
100 }
101
102 XAigerWriter(Module *module, bool zinit_mode, bool imode, bool omode, bool bmode) : module(module), zinit_mode(zinit_mode), sigmap(module)
103 {
104 pool<SigBit> undriven_bits;
105 pool<SigBit> unused_bits;
106
107 // promote public wires
108 for (auto wire : module->wires())
109 if (wire->name[0] == '\\')
110 sigmap.add(wire);
111
112 // promote input wires
113 for (auto wire : module->wires())
114 if (wire->port_input)
115 sigmap.add(wire);
116
117 // promote output wires
118 for (auto wire : module->wires())
119 if (wire->port_output)
120 sigmap.add(wire);
121
122 for (auto wire : module->wires())
123 {
124 if (wire->attributes.count("\\init")) {
125 SigSpec initsig = sigmap(wire);
126 Const initval = wire->attributes.at("\\init");
127 for (int i = 0; i < GetSize(wire) && i < GetSize(initval); i++)
128 if (initval[i] == State::S0 || initval[i] == State::S1)
129 init_map[initsig[i]] = initval[i] == State::S1;
130 }
131
132 for (int i = 0; i < GetSize(wire); i++)
133 {
134 SigBit wirebit(wire, i);
135 SigBit bit = sigmap(wirebit);
136
137 if (bit.wire == nullptr) {
138 if (wire->port_output) {
139 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
140 //output_bits.insert(wirebit);
141 }
142 continue;
143 }
144
145 undriven_bits.insert(bit);
146 unused_bits.insert(bit);
147
148 if (wire->port_input)
149 input_bits.insert(bit);
150
151 if (wire->port_output) {
152 if (bit != wirebit)
153 alias_map[wirebit] = bit;
154 //output_bits.insert(wirebit);
155 }
156 }
157 }
158
159 for (auto bit : input_bits)
160 undriven_bits.erase(bit);
161
162 for (auto bit : output_bits)
163 unused_bits.erase(bit);
164
165 for (auto cell : module->cells())
166 {
167 if (cell->type == "$_NOT_")
168 {
169 SigBit A = sigmap(cell->getPort("\\A").as_bit());
170 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
171 if (Y.wire->port_output)
172 output_bits.insert(Y);
173 unused_bits.erase(A);
174 undriven_bits.erase(Y);
175 not_map[Y] = A;
176 continue;
177 }
178
179 if (cell->type.in("$_FF_", "$_DFF_N_", "$_DFF_P_"))
180 {
181 SigBit D = sigmap(cell->getPort("\\D").as_bit());
182 SigBit Q = sigmap(cell->getPort("\\Q").as_bit());
183 unused_bits.erase(D);
184 undriven_bits.erase(Q);
185 ff_map[Q] = D;
186 continue;
187 }
188
189 if (cell->type == "$_AND_")
190 {
191 SigBit A = sigmap(cell->getPort("\\A").as_bit());
192 SigBit B = sigmap(cell->getPort("\\B").as_bit());
193 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
194 if (Y.wire->port_output)
195 output_bits.insert(Y);
196 unused_bits.erase(A);
197 unused_bits.erase(B);
198 undriven_bits.erase(Y);
199 and_map[Y] = make_pair(A, B);
200 continue;
201 }
202
203 if (cell->type == "$initstate")
204 {
205 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
206 undriven_bits.erase(Y);
207 initstate_bits.insert(Y);
208 continue;
209 }
210
211 for (const auto &c : cell->connections()) {
212 if (c.second.is_fully_const()) continue;
213 SigBit b = c.second.as_bit();
214 Wire *w = b.wire;
215 if (cell->input(c.first)) {
216 SigBit I = sigmap(b);
217 if (!w->port_input)
218 co_bits.insert(I);
219 }
220 else if (cell->output(c.first)) {
221 SigBit O = sigmap(b);
222 ci_bits.insert(O);
223 }
224 else log_abort();
225 if (!type_map.count(cell->type))
226 type_map[cell->type] = type_map.size()+1;
227 }
228 //log_error("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
229 }
230
231 // Do some CI/CO post-processing:
232 // Erase all COs that are undriven
233 for (auto bit : undriven_bits)
234 co_bits.erase(bit);
235 // Erase all CIs that are also COs or POs
236 for (auto bit : co_bits)
237 ci_bits.erase(bit);
238 for (auto bit : output_bits)
239 ci_bits.erase(bit);
240 // CIs cannot be undriven
241 for (auto bit : ci_bits)
242 undriven_bits.erase(bit);
243
244 for (auto bit : unused_bits)
245 undriven_bits.erase(bit);
246
247 if (!undriven_bits.empty()) {
248 undriven_bits.sort();
249 for (auto bit : undriven_bits) {
250 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
251 input_bits.insert(bit);
252 }
253 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
254 }
255
256 init_map.sort();
257 input_bits.sort();
258 output_bits.sort();
259 not_map.sort();
260 ff_map.sort();
261 and_map.sort();
262
263 aig_map[State::S0] = 0;
264 aig_map[State::S1] = 1;
265
266 for (auto bit : ci_bits) {
267 aig_m++, aig_i++;
268 aig_map[bit] = 2*aig_m;
269 }
270
271 for (auto bit : input_bits) {
272 aig_m++, aig_i++;
273 aig_map[bit] = 2*aig_m;
274 }
275
276 if (imode && input_bits.empty()) {
277 aig_m++, aig_i++;
278 }
279
280 if (zinit_mode)
281 {
282 for (auto it : ff_map) {
283 if (init_map.count(it.first))
284 continue;
285 aig_m++, aig_i++;
286 init_inputs[it.first] = 2*aig_m;
287 }
288 }
289
290 for (auto it : ff_map) {
291 aig_m++, aig_l++;
292 aig_map[it.first] = 2*aig_m;
293 ordered_latches[it.first] = aig_l-1;
294 if (init_map.count(it.first) == 0)
295 aig_latchinit.push_back(2);
296 else
297 aig_latchinit.push_back(init_map.at(it.first) ? 1 : 0);
298 }
299
300 if (!initstate_bits.empty() || !init_inputs.empty()) {
301 aig_m++, aig_l++;
302 initstate_ff = 2*aig_m+1;
303 aig_latchinit.push_back(0);
304 }
305
306 if (zinit_mode)
307 {
308 for (auto it : ff_map)
309 {
310 int l = ordered_latches[it.first];
311
312 if (aig_latchinit.at(l) == 1)
313 aig_map[it.first] ^= 1;
314
315 if (aig_latchinit.at(l) == 2)
316 {
317 int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
318 int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
319 aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
320 }
321 }
322 }
323
324 for (auto it : ff_map) {
325 int a = bit2aig(it.second);
326 int l = ordered_latches[it.first];
327 if (zinit_mode && aig_latchinit.at(l) == 1)
328 aig_latchin.push_back(a ^ 1);
329 else
330 aig_latchin.push_back(a);
331 }
332
333 if (!initstate_bits.empty() || !init_inputs.empty())
334 aig_latchin.push_back(1);
335
336 for (auto bit : co_bits) {
337 aig_o++;
338 ordered_outputs[bit] = aig_o-1;
339 aig_outputs.push_back(bit2aig(bit));
340 }
341
342 for (auto bit : output_bits) {
343 aig_o++;
344 ordered_outputs[bit] = aig_o-1;
345 aig_outputs.push_back(bit2aig(bit));
346 }
347
348 if (omode && output_bits.empty()) {
349 aig_o++;
350 aig_outputs.push_back(0);
351 }
352
353 if (bmode) {
354 //aig_b++;
355 aig_outputs.push_back(0);
356 }
357 }
358
359 void write_aiger(std::ostream &f, bool ascii_mode, bool miter_mode, bool symbols_mode)
360 {
361 int aig_obc = aig_o;
362 int aig_obcj = aig_obc;
363 int aig_obcjf = aig_obcj;
364
365 log_assert(aig_m == aig_i + aig_l + aig_a);
366 log_assert(aig_l == GetSize(aig_latchin));
367 log_assert(aig_l == GetSize(aig_latchinit));
368 log_assert(aig_obcjf == GetSize(aig_outputs));
369
370 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
371 f << stringf("\n");
372
373 if (ascii_mode)
374 {
375 for (int i = 0; i < aig_i; i++)
376 f << stringf("%d\n", 2*i+2);
377
378 for (int i = 0; i < aig_l; i++) {
379 if (zinit_mode || aig_latchinit.at(i) == 0)
380 f << stringf("%d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i));
381 else if (aig_latchinit.at(i) == 1)
382 f << stringf("%d %d 1\n", 2*(aig_i+i)+2, aig_latchin.at(i));
383 else if (aig_latchinit.at(i) == 2)
384 f << stringf("%d %d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i), 2*(aig_i+i)+2);
385 }
386
387 for (int i = 0; i < aig_obc; i++)
388 f << stringf("%d\n", aig_outputs.at(i));
389
390 for (int i = aig_obc; i < aig_obcj; i++)
391 f << stringf("1\n");
392
393 for (int i = aig_obc; i < aig_obcj; i++)
394 f << stringf("%d\n", aig_outputs.at(i));
395
396 for (int i = aig_obcj; i < aig_obcjf; i++)
397 f << stringf("%d\n", aig_outputs.at(i));
398
399 for (int i = 0; i < aig_a; i++)
400 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
401 }
402 else
403 {
404 for (int i = 0; i < aig_l; i++) {
405 if (zinit_mode || aig_latchinit.at(i) == 0)
406 f << stringf("%d\n", aig_latchin.at(i));
407 else if (aig_latchinit.at(i) == 1)
408 f << stringf("%d 1\n", aig_latchin.at(i));
409 else if (aig_latchinit.at(i) == 2)
410 f << stringf("%d %d\n", aig_latchin.at(i), 2*(aig_i+i)+2);
411 }
412
413 for (int i = 0; i < aig_obc; i++)
414 f << stringf("%d\n", aig_outputs.at(i));
415
416 for (int i = aig_obc; i < aig_obcj; i++)
417 f << stringf("1\n");
418
419 for (int i = aig_obc; i < aig_obcj; i++)
420 f << stringf("%d\n", aig_outputs.at(i));
421
422 for (int i = aig_obcj; i < aig_obcjf; i++)
423 f << stringf("%d\n", aig_outputs.at(i));
424
425 for (int i = 0; i < aig_a; i++) {
426 int lhs = 2*(aig_i+aig_l+i)+2;
427 int rhs0 = aig_gates.at(i).first;
428 int rhs1 = aig_gates.at(i).second;
429 int delta0 = lhs - rhs0;
430 int delta1 = rhs0 - rhs1;
431 aiger_encode(f, delta0);
432 aiger_encode(f, delta1);
433 }
434 }
435
436 if (symbols_mode)
437 {
438 dict<string, vector<string>> symbols;
439
440 for (auto wire : module->wires())
441 {
442 //if (wire->name[0] == '$')
443 // continue;
444
445 SigSpec sig = sigmap(wire);
446
447 for (int i = 0; i < GetSize(wire); i++)
448 {
449 if (sig[i].wire == nullptr) {
450 if (wire->port_output)
451 sig[i] = SigBit(wire, i);
452 else
453 continue;
454 }
455
456 if (input_bits.count(sig[i]) || ci_bits.count(SigSpec(sig[i]))) {
457 int a = aig_map.at(sig[i]);
458 log_assert((a & 1) == 0);
459 if (GetSize(wire) != 1)
460 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s[%d]", log_id(wire), i));
461 else
462 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s", log_id(wire)));
463 }
464
465 if (output_bits.count(SigSpec(wire, i)) || co_bits.count(SigSpec(wire, i))) {
466 int o = ordered_outputs.at(SigSpec(wire, i));
467 if (GetSize(wire) != 1)
468 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s[%d]", log_id(wire), i));
469 else
470 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s", log_id(wire)));
471 }
472
473 if (init_inputs.count(sig[i])) {
474 int a = init_inputs.at(sig[i]);
475 log_assert((a & 1) == 0);
476 if (GetSize(wire) != 1)
477 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
478 else
479 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
480 }
481
482 if (ordered_latches.count(sig[i])) {
483 int l = ordered_latches.at(sig[i]);
484 const char *p = (zinit_mode && (aig_latchinit.at(l) == 1)) ? "!" : "";
485 if (GetSize(wire) != 1)
486 symbols[stringf("l%d", l)].push_back(stringf("%s%s[%d]", p, log_id(wire), i));
487 else
488 symbols[stringf("l%d", l)].push_back(stringf("%s%s", p, log_id(wire)));
489 }
490 }
491 }
492
493 symbols.sort();
494
495 for (auto &sym : symbols) {
496 f << sym.first;
497 std::sort(sym.second.begin(), sym.second.end());
498 for (auto &s : sym.second)
499 f << " " << s;
500 f << std::endl;
501 }
502 }
503
504 f << stringf("c\nGenerated by %s\n", yosys_version_str);
505 }
506
507 void write_map(std::ostream &f, bool verbose_map)
508 {
509 dict<int, string> input_lines;
510 dict<int, string> init_lines;
511 dict<int, string> output_lines;
512 dict<int, string> latch_lines;
513 dict<int, string> wire_lines;
514
515 for (auto wire : module->wires())
516 {
517 //if (!verbose_map && wire->name[0] == '$')
518 // continue;
519
520 SigSpec sig = sigmap(wire);
521
522 for (int i = 0; i < GetSize(wire); i++)
523 {
524 if (aig_map.count(sig[i]) == 0 || sig[i].wire == nullptr)
525 continue;
526
527 int a = aig_map.at(sig[i]);
528
529 if (verbose_map)
530 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
531
532 if (wire->port_input || ci_bits.count(RTLIL::SigBit{wire, i})) {
533 log_assert((a & 1) == 0);
534 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
535 }
536
537 if (output_bits.count(RTLIL::SigBit{wire, i}) || co_bits.count(RTLIL::SigBit{wire, i})) {
538 int o = ordered_outputs.at(sig[i]);
539 output_lines[o] += stringf("output %d %d %s\n", o, i, log_id(wire));
540 }
541
542 if (init_inputs.count(sig[i])) {
543 int a = init_inputs.at(sig[i]);
544 log_assert((a & 1) == 0);
545 init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
546 }
547
548 if (ordered_latches.count(sig[i])) {
549 int l = ordered_latches.at(sig[i]);
550 if (zinit_mode && (aig_latchinit.at(l) == 1))
551 latch_lines[l] += stringf("invlatch %d %d %s\n", l, i, log_id(wire));
552 else
553 latch_lines[l] += stringf("latch %d %d %s\n", l, i, log_id(wire));
554 }
555 }
556 }
557
558 input_lines.sort();
559 for (auto &it : input_lines)
560 f << it.second;
561
562 init_lines.sort();
563 for (auto &it : init_lines)
564 f << it.second;
565
566 output_lines.sort();
567 for (auto &it : output_lines)
568 f << it.second;
569
570 latch_lines.sort();
571 for (auto &it : latch_lines)
572 f << it.second;
573
574 wire_lines.sort();
575 for (auto &it : wire_lines)
576 f << it.second;
577 }
578 };
579
580 struct XAigerBackend : public Backend {
581 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
582 void help() YS_OVERRIDE
583 {
584 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
585 log("\n");
586 log(" write_xaiger [options] [filename]\n");
587 log("\n");
588 log("Write the current design to an XAIGER file. The design must be flattened and\n");
589 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
590 log("\n");
591 log(" -ascii\n");
592 log(" write ASCII version of AGIER format\n");
593 log("\n");
594 log(" -zinit\n");
595 log(" convert FFs to zero-initialized FFs, adding additional inputs for\n");
596 log(" uninitialized FFs.\n");
597 log("\n");
598 log(" -symbols\n");
599 log(" include a symbol table in the generated AIGER file\n");
600 log("\n");
601 log(" -map <filename>\n");
602 log(" write an extra file with port and latch symbols\n");
603 log("\n");
604 log(" -vmap <filename>\n");
605 log(" like -map, but more verbose\n");
606 log("\n");
607 log(" -I, -O, -B\n");
608 log(" If the design contains no input/output/assert then create one\n");
609 log(" dummy input/output/bad_state pin to make the tools reading the\n");
610 log(" AIGER file happy.\n");
611 log("\n");
612 }
613 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
614 {
615 bool ascii_mode = false;
616 bool zinit_mode = false;
617 bool miter_mode = false;
618 bool symbols_mode = false;
619 bool verbose_map = false;
620 bool imode = false;
621 bool omode = false;
622 bool bmode = false;
623 std::string map_filename;
624
625 log_header(design, "Executing XAIGER backend.\n");
626
627 size_t argidx;
628 for (argidx = 1; argidx < args.size(); argidx++)
629 {
630 if (args[argidx] == "-ascii") {
631 ascii_mode = true;
632 continue;
633 }
634 if (args[argidx] == "-zinit") {
635 zinit_mode = true;
636 continue;
637 }
638 if (args[argidx] == "-symbols") {
639 symbols_mode = true;
640 continue;
641 }
642 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
643 map_filename = args[++argidx];
644 continue;
645 }
646 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
647 map_filename = args[++argidx];
648 verbose_map = true;
649 continue;
650 }
651 if (args[argidx] == "-I") {
652 imode = true;
653 continue;
654 }
655 if (args[argidx] == "-O") {
656 omode = true;
657 continue;
658 }
659 if (args[argidx] == "-B") {
660 bmode = true;
661 continue;
662 }
663 break;
664 }
665 extra_args(f, filename, args, argidx);
666
667 Module *top_module = design->top_module();
668
669 if (top_module == nullptr)
670 log_error("Can't find top module in current design!\n");
671
672 XAigerWriter writer(top_module, zinit_mode, imode, omode, bmode);
673 writer.write_aiger(*f, ascii_mode, miter_mode, symbols_mode);
674
675 if (!map_filename.empty()) {
676 std::ofstream mapf;
677 mapf.open(map_filename.c_str(), std::ofstream::trunc);
678 if (mapf.fail())
679 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
680 writer.write_map(mapf, verbose_map);
681 }
682 }
683 } XAigerBackend;
684
685 PRIVATE_NAMESPACE_END