Fix for abc9_test022
[yosys.git] / backends / aiger / xaiger.cc
1 /*
2 * yosys -- Yosys Open SYnthesis Suite
3 *
4 * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
5 * Copyright (C) 2019 Eddie Hung <eddie@fpgeh.com>
6 *
7 * Permission to use, copy, modify, and/or distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 *
19 */
20
21 #include "kernel/yosys.h"
22 #include "kernel/sigtools.h"
23 #include "kernel/celltypes.h"
24 #include "kernel/utils.h"
25
26 USING_YOSYS_NAMESPACE
27 PRIVATE_NAMESPACE_BEGIN
28
29 void aiger_encode(std::ostream &f, int x)
30 {
31 log_assert(x >= 0);
32
33 while (x & ~0x7f) {
34 f.put((x & 0x7f) | 0x80);
35 x = x >> 7;
36 }
37
38 f.put(x);
39 }
40
41 struct XAigerWriter
42 {
43 Module *module;
44 bool zinit_mode;
45 SigMap sigmap;
46
47 dict<SigBit, bool> init_map;
48 pool<SigBit> input_bits, output_bits;
49 dict<SigBit, SigBit> not_map, ff_map, alias_map;
50 dict<SigBit, pair<SigBit, SigBit>> and_map;
51 //pool<SigBit> initstate_bits;
52 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int>> ci_bits;
53 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int,int>> co_bits;
54
55 vector<pair<int, int>> aig_gates;
56 vector<int> aig_latchin, aig_latchinit, aig_outputs;
57 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
58
59 dict<SigBit, int> aig_map;
60 dict<SigBit, int> ordered_outputs;
61 dict<SigBit, int> ordered_latches;
62
63 vector<Cell*> box_list;
64
65 //dict<SigBit, int> init_inputs;
66 //int initstate_ff = 0;
67
68 int mkgate(int a0, int a1)
69 {
70 aig_m++, aig_a++;
71 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
72 return 2*aig_m;
73 }
74
75 int bit2aig(SigBit bit)
76 {
77 if (aig_map.count(bit) == 0)
78 {
79 aig_map[bit] = -1;
80
81 //if (initstate_bits.count(bit)) {
82 // log_assert(initstate_ff > 0);
83 // aig_map[bit] = initstate_ff;
84 //} else
85 if (not_map.count(bit)) {
86 int a = bit2aig(not_map.at(bit)) ^ 1;
87 aig_map[bit] = a;
88 } else
89 if (and_map.count(bit)) {
90 auto args = and_map.at(bit);
91 int a0 = bit2aig(args.first);
92 int a1 = bit2aig(args.second);
93 aig_map[bit] = mkgate(a0, a1);
94 } else
95 if (alias_map.count(bit)) {
96 aig_map[bit] = bit2aig(alias_map.at(bit));
97 }
98
99 if (bit == State::Sx || bit == State::Sz)
100 log_error("Design contains 'x' or 'z' bits. Use 'setundef' to replace those constants.\n");
101 }
102
103 log_assert(aig_map.at(bit) >= 0);
104 return aig_map.at(bit);
105 }
106
107 XAigerWriter(Module *module, bool zinit_mode, bool imode, bool omode, bool bmode, bool holes_mode=false) : module(module), zinit_mode(zinit_mode), sigmap(module)
108 {
109 pool<SigBit> undriven_bits;
110 pool<SigBit> unused_bits;
111
112 // promote public wires
113 for (auto wire : module->wires())
114 if (wire->name[0] == '\\')
115 sigmap.add(wire);
116
117 // promote input wires
118 for (auto wire : module->wires())
119 if (wire->port_input)
120 sigmap.add(wire);
121
122 // promote output wires
123 for (auto wire : module->wires())
124 if (wire->port_output)
125 sigmap.add(wire);
126
127 for (auto wire : module->wires())
128 {
129 if (wire->attributes.count("\\init")) {
130 SigSpec initsig = sigmap(wire);
131 Const initval = wire->attributes.at("\\init");
132 for (int i = 0; i < GetSize(wire) && i < GetSize(initval); i++)
133 if (initval[i] == State::S0 || initval[i] == State::S1)
134 init_map[initsig[i]] = initval[i] == State::S1;
135 }
136
137 bool keep = wire->attributes.count("\\keep");
138
139 for (int i = 0; i < GetSize(wire); i++)
140 {
141 SigBit wirebit(wire, i);
142 SigBit bit = sigmap(wirebit);
143
144 if (bit.wire == nullptr) {
145 if (wire->port_output) {
146 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
147 output_bits.insert(wirebit);
148 }
149 continue;
150 }
151
152 undriven_bits.insert(bit);
153 unused_bits.insert(bit);
154
155 if (wire->port_input)
156 input_bits.insert(bit);
157 else if (keep)
158 input_bits.insert(wirebit);
159
160 if (wire->port_output || keep) {
161 if (bit != wirebit)
162 alias_map[wirebit] = bit;
163 output_bits.insert(wirebit);
164 }
165 }
166 }
167
168 for (auto bit : input_bits)
169 undriven_bits.erase(bit);
170
171 for (auto bit : output_bits)
172 if (!bit.wire->port_input)
173 unused_bits.erase(bit);
174
175 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
176 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
177 bool abc_box_seen = false;
178
179 for (auto cell : module->cells())
180 {
181 RTLIL::Module* inst_module = module->design->module(cell->type);
182 bool known_type = yosys_celltypes.cell_known(cell->type);
183
184 if (!holes_mode) {
185 toposort.node(cell->name);
186 for (const auto &conn : cell->connections())
187 {
188 if (!cell->type.in("$_NOT_", "$_AND_")) {
189 if (known_type) {
190 if (conn.first.in("\\Q", "\\CTRL_OUT", "\\RD_DATA"))
191 continue;
192 if (cell->type == "$memrd" && conn.first == "\\DATA")
193 continue;
194 }
195
196 if (inst_module) {
197 RTLIL::Wire* inst_module_port = inst_module->wire(conn.first);
198 log_assert(inst_module_port);
199
200 if (inst_module_port->attributes.count("\\abc_flop_q"))
201 continue;
202 }
203 }
204
205 if (cell->input(conn.first)) {
206 // Ignore inout for the sake of topographical ordering
207 if (cell->output(conn.first)) continue;
208 for (auto bit : sigmap(conn.second))
209 bit_users[bit].insert(cell->name);
210 }
211
212 if (cell->output(conn.first))
213 for (auto bit : sigmap(conn.second))
214 bit_drivers[bit].insert(cell->name);
215 }
216 }
217
218 if (cell->type == "$_NOT_")
219 {
220 SigBit A = sigmap(cell->getPort("\\A").as_bit());
221 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
222 unused_bits.erase(A);
223 undriven_bits.erase(Y);
224 not_map[Y] = A;
225 continue;
226 }
227
228 //if (cell->type.in("$_FF_", "$_DFF_N_", "$_DFF_P_"))
229 //{
230 // SigBit D = sigmap(cell->getPort("\\D").as_bit());
231 // SigBit Q = sigmap(cell->getPort("\\Q").as_bit());
232 // unused_bits.erase(D);
233 // undriven_bits.erase(Q);
234 // ff_map[Q] = D;
235 // continue;
236 //}
237
238 if (cell->type == "$_AND_")
239 {
240 SigBit A = sigmap(cell->getPort("\\A").as_bit());
241 SigBit B = sigmap(cell->getPort("\\B").as_bit());
242 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
243 unused_bits.erase(A);
244 unused_bits.erase(B);
245 undriven_bits.erase(Y);
246 and_map[Y] = make_pair(A, B);
247 continue;
248 }
249
250 //if (cell->type == "$initstate")
251 //{
252 // SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
253 // undriven_bits.erase(Y);
254 // initstate_bits.insert(Y);
255 // continue;
256 //}
257
258 if (inst_module && inst_module->attributes.count("\\abc_box_id")) {
259 abc_box_seen = true;
260 }
261 else {
262 for (const auto &c : cell->connections()) {
263 if (c.second.is_fully_const()) continue;
264 for (auto b : c.second.bits()) {
265 Wire *w = b.wire;
266 if (!w) continue;
267 auto is_input = cell->input(c.first);
268 auto is_output = cell->output(c.first);
269 log_assert(is_input || is_output);
270 if (is_input) {
271 if (!w->port_input) {
272 SigBit I = sigmap(b);
273 if (I != b)
274 alias_map[b] = I;
275 output_bits.insert(b);
276 unused_bits.erase(b);
277 }
278 }
279 if (is_output) {
280 input_bits.insert(b);
281 SigBit O = sigmap(b);
282 if (O != b)
283 alias_map[O] = b;
284 undriven_bits.erase(O);
285 }
286 }
287 }
288 }
289
290 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
291 }
292
293 if (abc_box_seen) {
294 for (auto &it : bit_users)
295 if (bit_drivers.count(it.first))
296 for (auto driver_cell : bit_drivers.at(it.first))
297 for (auto user_cell : it.second)
298 toposort.edge(driver_cell, user_cell);
299
300 toposort.sort();
301 for (auto cell_name : toposort.sorted) {
302 RTLIL::Cell *cell = module->cell(cell_name);
303 RTLIL::Module* box_module = module->design->module(cell->type);
304 if (!box_module || !box_module->attributes.count("\\abc_box_id"))
305 continue;
306
307 // Fully pad all unused input connections of this box cell with S0
308 // Fully pad all undriven output connections of this box cell with anonymous wires
309 // NB: Assume box_module->ports are sorted alphabetically
310 // (as RTLIL::Module::fixup_ports() would do)
311 for (const auto &port_name : box_module->ports) {
312 RTLIL::Wire* w = box_module->wire(port_name);
313 log_assert(w);
314 auto it = cell->connections_.find(port_name);
315 if (w->port_input) {
316 RTLIL::SigSpec rhs;
317 if (it != cell->connections_.end()) {
318 if (GetSize(it->second) < GetSize(w))
319 it->second.append(RTLIL::SigSpec(RTLIL::S0, GetSize(w)-GetSize(it->second)));
320 rhs = it->second;
321 }
322 else {
323 rhs = RTLIL::SigSpec(RTLIL::S0, GetSize(w));
324 cell->setPort(port_name, rhs);
325 }
326
327 int offset = 0;
328 for (const auto &b : rhs.bits()) {
329 SigBit I = sigmap(b);
330 if (I != b)
331 alias_map[b] = I;
332 co_bits.emplace_back(b, cell, port_name, offset++, 0);
333 unused_bits.erase(b);
334 }
335 }
336 if (w->port_output) {
337 RTLIL::SigSpec rhs;
338 auto it = cell->connections_.find(w->name);
339 if (it != cell->connections_.end()) {
340 if (GetSize(it->second) < GetSize(w))
341 it->second.append(module->addWire(NEW_ID, GetSize(w)-GetSize(it->second)));
342 rhs = it->second;
343 }
344 else {
345 rhs = module->addWire(NEW_ID, GetSize(w));
346 cell->setPort(port_name, rhs);
347 }
348
349 int offset = 0;
350 for (const auto &b : rhs.bits()) {
351 ci_bits.emplace_back(b, cell, port_name, offset++);
352 SigBit O = sigmap(b);
353 if (O != b)
354 alias_map[O] = b;
355 undriven_bits.erase(O);
356 }
357 }
358 }
359 box_list.emplace_back(cell);
360 }
361
362 // TODO: Free memory from toposort, bit_drivers, bit_users
363 }
364
365 for (auto bit : input_bits) {
366 RTLIL::Wire *wire = bit.wire;
367 // If encountering an inout port, or a keep-ed wire, then create a new wire
368 // with $inout.out suffix, make it a PO driven by the existing inout, and
369 // inherit existing inout's drivers
370 if ((wire->port_input && wire->port_output && !undriven_bits.count(bit))
371 || wire->attributes.count("\\keep")) {
372 log_assert(input_bits.count(bit) && output_bits.count(bit));
373 RTLIL::Wire *new_wire = module->wire(wire->name.str() + "$inout.out");
374 if (!new_wire)
375 new_wire = module->addWire(wire->name.str() + "$inout.out", GetSize(wire));
376 SigBit new_bit(new_wire, bit.offset);
377 module->connect(new_bit, bit);
378 if (not_map.count(bit))
379 not_map[new_bit] = not_map.at(bit);
380 else if (and_map.count(bit))
381 and_map[new_bit] = and_map.at(bit);
382 else if (alias_map.count(bit))
383 alias_map[new_bit] = alias_map.at(bit);
384 else
385 //log_abort();
386 alias_map[new_bit] = bit;
387 output_bits.erase(bit);
388 output_bits.insert(new_bit);
389 }
390 }
391
392 // Erase all POs that are undriven
393 if (!holes_mode)
394 for (auto bit : undriven_bits)
395 output_bits.erase(bit);
396 for (auto bit : unused_bits)
397 undriven_bits.erase(bit);
398
399 if (!undriven_bits.empty() && !holes_mode) {
400 undriven_bits.sort();
401 for (auto bit : undriven_bits) {
402 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
403 input_bits.insert(bit);
404 }
405 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
406 }
407
408 init_map.sort();
409 if (holes_mode) {
410 struct sort_by_port_id {
411 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
412 return a.wire->port_id < b.wire->port_id;
413 }
414 };
415 input_bits.sort(sort_by_port_id());
416 output_bits.sort(sort_by_port_id());
417 }
418 else {
419 input_bits.sort();
420 output_bits.sort();
421 }
422
423 not_map.sort();
424 ff_map.sort();
425 and_map.sort();
426
427 aig_map[State::S0] = 0;
428 aig_map[State::S1] = 1;
429
430 for (auto bit : input_bits) {
431 aig_m++, aig_i++;
432 aig_map[bit] = 2*aig_m;
433 }
434
435 for (auto &c : ci_bits) {
436 aig_m++, aig_i++;
437 aig_map[std::get<0>(c)] = 2*aig_m;
438 }
439
440 if (imode && input_bits.empty()) {
441 aig_m++, aig_i++;
442 }
443
444 //if (zinit_mode)
445 //{
446 // for (auto it : ff_map) {
447 // if (init_map.count(it.first))
448 // continue;
449 // aig_m++, aig_i++;
450 // init_inputs[it.first] = 2*aig_m;
451 // }
452 //}
453
454 for (auto it : ff_map) {
455 aig_m++, aig_l++;
456 aig_map[it.first] = 2*aig_m;
457 ordered_latches[it.first] = aig_l-1;
458 if (init_map.count(it.first) == 0)
459 aig_latchinit.push_back(2);
460 else
461 aig_latchinit.push_back(init_map.at(it.first) ? 1 : 0);
462 }
463
464 //if (!initstate_bits.empty() || !init_inputs.empty()) {
465 // aig_m++, aig_l++;
466 // initstate_ff = 2*aig_m+1;
467 // aig_latchinit.push_back(0);
468 //}
469
470 //if (zinit_mode)
471 //{
472 // for (auto it : ff_map)
473 // {
474 // int l = ordered_latches[it.first];
475
476 // if (aig_latchinit.at(l) == 1)
477 // aig_map[it.first] ^= 1;
478
479 // if (aig_latchinit.at(l) == 2)
480 // {
481 // int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
482 // int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
483 // aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
484 // }
485 // }
486 //}
487
488 for (auto it : ff_map) {
489 int a = bit2aig(it.second);
490 int l = ordered_latches[it.first];
491 if (zinit_mode && aig_latchinit.at(l) == 1)
492 aig_latchin.push_back(a ^ 1);
493 else
494 aig_latchin.push_back(a);
495 }
496
497 //if (!initstate_bits.empty() || !init_inputs.empty())
498 // aig_latchin.push_back(1);
499
500 for (auto &c : co_bits) {
501 RTLIL::SigBit bit = std::get<0>(c);
502 std::get<4>(c) = aig_o++;
503 ordered_outputs[bit] = std::get<4>(c);
504 aig_outputs.push_back(bit2aig(bit));
505 }
506
507 for (auto bit : output_bits) {
508 ordered_outputs[bit] = aig_o++;
509 aig_outputs.push_back(bit2aig(bit));
510 }
511
512 if (omode && output_bits.empty()) {
513 aig_o++;
514 aig_outputs.push_back(0);
515 }
516
517 if (bmode) {
518 //aig_b++;
519 aig_outputs.push_back(0);
520 }
521 }
522
523 void write_aiger(std::ostream &f, bool ascii_mode, bool miter_mode, bool symbols_mode, bool omode)
524 {
525 int aig_obc = aig_o;
526 int aig_obcj = aig_obc;
527 int aig_obcjf = aig_obcj;
528
529 log_assert(aig_m == aig_i + aig_l + aig_a);
530 log_assert(aig_l == GetSize(aig_latchin));
531 log_assert(aig_l == GetSize(aig_latchinit));
532 log_assert(aig_obcjf == GetSize(aig_outputs));
533
534 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
535 f << stringf("\n");
536
537 if (ascii_mode)
538 {
539 for (int i = 0; i < aig_i; i++)
540 f << stringf("%d\n", 2*i+2);
541
542 for (int i = 0; i < aig_l; i++) {
543 if (zinit_mode || aig_latchinit.at(i) == 0)
544 f << stringf("%d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i));
545 else if (aig_latchinit.at(i) == 1)
546 f << stringf("%d %d 1\n", 2*(aig_i+i)+2, aig_latchin.at(i));
547 else if (aig_latchinit.at(i) == 2)
548 f << stringf("%d %d %d\n", 2*(aig_i+i)+2, aig_latchin.at(i), 2*(aig_i+i)+2);
549 }
550
551 for (int i = 0; i < aig_obc; i++)
552 f << stringf("%d\n", aig_outputs.at(i));
553
554 for (int i = aig_obc; i < aig_obcj; i++)
555 f << stringf("1\n");
556
557 for (int i = aig_obc; i < aig_obcj; i++)
558 f << stringf("%d\n", aig_outputs.at(i));
559
560 for (int i = aig_obcj; i < aig_obcjf; i++)
561 f << stringf("%d\n", aig_outputs.at(i));
562
563 for (int i = 0; i < aig_a; i++)
564 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
565 }
566 else
567 {
568 for (int i = 0; i < aig_l; i++) {
569 if (zinit_mode || aig_latchinit.at(i) == 0)
570 f << stringf("%d\n", aig_latchin.at(i));
571 else if (aig_latchinit.at(i) == 1)
572 f << stringf("%d 1\n", aig_latchin.at(i));
573 else if (aig_latchinit.at(i) == 2)
574 f << stringf("%d %d\n", aig_latchin.at(i), 2*(aig_i+i)+2);
575 }
576
577 for (int i = 0; i < aig_obc; i++)
578 f << stringf("%d\n", aig_outputs.at(i));
579
580 for (int i = aig_obc; i < aig_obcj; i++)
581 f << stringf("1\n");
582
583 for (int i = aig_obc; i < aig_obcj; i++)
584 f << stringf("%d\n", aig_outputs.at(i));
585
586 for (int i = aig_obcj; i < aig_obcjf; i++)
587 f << stringf("%d\n", aig_outputs.at(i));
588
589 for (int i = 0; i < aig_a; i++) {
590 int lhs = 2*(aig_i+aig_l+i)+2;
591 int rhs0 = aig_gates.at(i).first;
592 int rhs1 = aig_gates.at(i).second;
593 int delta0 = lhs - rhs0;
594 int delta1 = rhs0 - rhs1;
595 aiger_encode(f, delta0);
596 aiger_encode(f, delta1);
597 }
598 }
599
600 if (symbols_mode)
601 {
602 dict<string, vector<string>> symbols;
603
604 bool output_seen = false;
605 for (auto wire : module->wires())
606 {
607 //if (wire->name[0] == '$')
608 // continue;
609
610 SigSpec sig = sigmap(wire);
611
612 for (int i = 0; i < GetSize(wire); i++)
613 {
614 RTLIL::SigBit b(wire, i);
615 if (input_bits.count(b)) {
616 int a = aig_map.at(sig[i]);
617 log_assert((a & 1) == 0);
618 if (GetSize(wire) != 1)
619 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s[%d]", log_id(wire), i));
620 else
621 symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s", log_id(wire)));
622 }
623
624 if (output_bits.count(b)) {
625 int o = ordered_outputs.at(b);
626 output_seen = !miter_mode;
627 if (GetSize(wire) != 1)
628 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s[%d]", log_id(wire), i));
629 else
630 symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s", log_id(wire)));
631 }
632
633 //if (init_inputs.count(sig[i])) {
634 // int a = init_inputs.at(sig[i]);
635 // log_assert((a & 1) == 0);
636 // if (GetSize(wire) != 1)
637 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
638 // else
639 // symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
640 //}
641
642 if (ordered_latches.count(sig[i])) {
643 int l = ordered_latches.at(sig[i]);
644 const char *p = (zinit_mode && (aig_latchinit.at(l) == 1)) ? "!" : "";
645 if (GetSize(wire) != 1)
646 symbols[stringf("l%d", l)].push_back(stringf("%s%s[%d]", p, log_id(wire), i));
647 else
648 symbols[stringf("l%d", l)].push_back(stringf("%s%s", p, log_id(wire)));
649 }
650 }
651 }
652
653 if (omode && !output_seen)
654 symbols["o0"].push_back("__dummy_o__");
655
656 symbols.sort();
657
658 for (auto &sym : symbols) {
659 f << sym.first;
660 std::sort(sym.second.begin(), sym.second.end());
661 for (auto &s : sym.second)
662 f << " " << s;
663 f << std::endl;
664 }
665 }
666
667 f << "c";
668
669 if (!box_list.empty()) {
670 std::stringstream h_buffer;
671 auto write_h_buffer = [&h_buffer](int i32) {
672 // TODO: Don't assume we're on little endian
673 #ifdef _WIN32
674 int i32_be = _byteswap_ulong(i32);
675 #else
676 int i32_be = __builtin_bswap32(i32);
677 #endif
678 h_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
679 };
680 int num_outputs = output_bits.size();
681 if (omode && num_outputs == 0)
682 num_outputs = 1;
683 write_h_buffer(1);
684 write_h_buffer(input_bits.size() + ci_bits.size());
685 write_h_buffer(num_outputs + co_bits.size());
686 write_h_buffer(input_bits.size());
687 write_h_buffer(num_outputs);
688 write_h_buffer(box_list.size());
689
690 RTLIL::Module *holes_module = nullptr;
691 holes_module = module->design->addModule("\\__holes__");
692 log_assert(holes_module);
693
694 int port_id = 1;
695 int box_count = 0;
696 for (auto cell : box_list) {
697 RTLIL::Module* box_module = module->design->module(cell->type);
698 int box_inputs = 0, box_outputs = 0;
699 Cell *holes_cell = nullptr;
700 if (box_module->get_bool_attribute("\\whitebox"))
701 holes_cell = holes_module->addCell(cell->name, cell->type);
702
703 RTLIL::Wire *holes_wire;
704 // TODO: Only sort once
705 box_module->wires_.sort(RTLIL::sort_by_id_str());
706 for (const auto w : box_module->wires()) {
707 RTLIL::SigSpec port_wire;
708 if (w->port_input) {
709 for (int i = 0; i < GetSize(w); i++) {
710 box_inputs++;
711 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
712 if (!holes_wire) {
713 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
714 holes_wire->port_input = true;
715 holes_wire->port_id = port_id++;
716 holes_module->ports.push_back(holes_wire->name);
717 }
718 if (holes_cell)
719 port_wire.append(holes_wire);
720 }
721 if (!port_wire.empty())
722 holes_cell->setPort(w->name, port_wire);
723 }
724 if (w->port_output) {
725 box_outputs += GetSize(w);
726 for (int i = 0; i < GetSize(w); i++) {
727 if (GetSize(w) == 1)
728 holes_wire = holes_module->addWire(stringf("%s.%s", cell->name.c_str(), w->name.c_str()));
729 else
730 holes_wire = holes_module->addWire(stringf("%s.%s[%d]", cell->name.c_str(), w->name.c_str(), i));
731 holes_wire->port_output = true;
732 holes_wire->port_id = port_id++;
733 holes_module->ports.push_back(holes_wire->name);
734 if (holes_cell)
735 port_wire.append(holes_wire);
736 else
737 holes_module->connect(holes_wire, RTLIL::S0);
738 }
739 if (!port_wire.empty())
740 holes_cell->setPort(w->name, port_wire);
741 }
742 }
743
744 write_h_buffer(box_inputs);
745 write_h_buffer(box_outputs);
746 write_h_buffer(box_module->attributes.at("\\abc_box_id").as_int());
747 write_h_buffer(box_count++);
748 }
749
750 f << "h";
751 std::string buffer_str = h_buffer.str();
752 // TODO: Don't assume we're on little endian
753 #ifdef _WIN32
754 int buffer_size_be = _byteswap_ulong(buffer_str.size());
755 #else
756 int buffer_size_be = __builtin_bswap32(buffer_str.size());
757 #endif
758 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
759 f.write(buffer_str.data(), buffer_str.size());
760
761 if (holes_module) {
762 // NB: fixup_ports() will sort ports by name
763 //holes_module->fixup_ports();
764 holes_module->check();
765
766 holes_module->design->selection_stack.emplace_back(false);
767 RTLIL::Selection& sel = holes_module->design->selection_stack.back();
768 sel.select(holes_module);
769
770 // TODO: Should not need to opt_merge if we only instantiate
771 // each box type once...
772 Pass::call(holes_module->design, "opt_merge -share_all");
773
774 Pass::call(holes_module->design, "flatten -wb");
775
776 // TODO: Should techmap all lib_whitebox-es once
777 //Pass::call(holes_module->design, "techmap");
778
779 Pass::call(holes_module->design, "aigmap");
780 Pass::call(holes_module->design, "clean -purge");
781
782 holes_module->design->selection_stack.pop_back();
783
784 std::stringstream a_buffer;
785 XAigerWriter writer(holes_module, false /*zinit_mode*/, false /*imode*/, false /*omode*/, false /*bmode*/, true /* holes_mode */);
786 writer.write_aiger(a_buffer, false /*ascii_mode*/, false /*miter_mode*/, false /*symbols_mode*/, false /*omode*/);
787
788 f << "a";
789 std::string buffer_str = a_buffer.str();
790 // TODO: Don't assume we're on little endian
791 #ifdef _WIN32
792 int buffer_size_be = _byteswap_ulong(buffer_str.size());
793 #else
794 int buffer_size_be = __builtin_bswap32(buffer_str.size());
795 #endif
796 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
797 f.write(buffer_str.data(), buffer_str.size());
798 holes_module->design->remove(holes_module);
799 }
800
801 std::stringstream r_buffer;
802 auto write_r_buffer = [&r_buffer](int i32) {
803 // TODO: Don't assume we're on little endian
804 #ifdef _WIN32
805 int i32_be = _byteswap_ulong(i32);
806 #else
807 int i32_be = __builtin_bswap32(i32);
808 #endif
809 r_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
810 };
811 write_r_buffer(0);
812
813 f << "r";
814 buffer_str = r_buffer.str();
815 // TODO: Don't assume we're on little endian
816 #ifdef _WIN32
817 buffer_size_be = _byteswap_ulong(buffer_str.size());
818 #else
819 buffer_size_be = __builtin_bswap32(buffer_str.size());
820 #endif
821 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
822 f.write(buffer_str.data(), buffer_str.size());
823 }
824
825 f << stringf("Generated by %s\n", yosys_version_str);
826 }
827
828 void write_map(std::ostream &f, bool verbose_map, bool omode)
829 {
830 dict<int, string> input_lines;
831 dict<int, string> init_lines;
832 dict<int, string> output_lines;
833 dict<int, string> latch_lines;
834 dict<int, string> wire_lines;
835
836 for (auto wire : module->wires())
837 {
838 //if (!verbose_map && wire->name[0] == '$')
839 // continue;
840
841 SigSpec sig = sigmap(wire);
842
843 for (int i = 0; i < GetSize(wire); i++)
844 {
845 RTLIL::SigBit b(wire, i);
846 if (input_bits.count(b)) {
847 int a = aig_map.at(b);
848 log_assert((a & 1) == 0);
849 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
850 }
851
852 if (output_bits.count(b)) {
853 int o = ordered_outputs.at(b);
854 output_lines[o] += stringf("output %lu %d %s\n", o - co_bits.size(), i, log_id(wire));
855 continue;
856 }
857
858 //if (init_inputs.count(sig[i])) {
859 // int a = init_inputs.at(sig[i]);
860 // log_assert((a & 1) == 0);
861 // init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
862 // continue;
863 //}
864
865 if (ordered_latches.count(sig[i])) {
866 int l = ordered_latches.at(sig[i]);
867 if (zinit_mode && (aig_latchinit.at(l) == 1))
868 latch_lines[l] += stringf("invlatch %d %d %s\n", l, i, log_id(wire));
869 else
870 latch_lines[l] += stringf("latch %d %d %s\n", l, i, log_id(wire));
871 continue;
872 }
873
874 if (verbose_map) {
875 if (aig_map.count(sig[i]) == 0)
876 continue;
877
878 int a = aig_map.at(sig[i]);
879 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
880 }
881 }
882 }
883
884 input_lines.sort();
885 for (auto &it : input_lines)
886 f << it.second;
887 log_assert(input_lines.size() == input_bits.size());
888
889 init_lines.sort();
890 for (auto &it : init_lines)
891 f << it.second;
892
893 int box_count = 0;
894 for (auto cell : box_list)
895 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
896
897 output_lines.sort();
898 for (auto &it : output_lines)
899 f << it.second;
900 log_assert(output_lines.size() == output_bits.size());
901 if (omode && output_bits.empty())
902 f << "output " << output_lines.size() << " 0 __dummy_o__\n";
903
904 latch_lines.sort();
905 for (auto &it : latch_lines)
906 f << it.second;
907
908 wire_lines.sort();
909 for (auto &it : wire_lines)
910 f << it.second;
911 }
912 };
913
914 struct XAigerBackend : public Backend {
915 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
916 void help() YS_OVERRIDE
917 {
918 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
919 log("\n");
920 log(" write_xaiger [options] [filename]\n");
921 log("\n");
922 log("Write the current design to an XAIGER file. The design must be flattened and\n");
923 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
924 log("\n");
925 log(" -ascii\n");
926 log(" write ASCII version of AIGER format\n");
927 log("\n");
928 log(" -zinit\n");
929 log(" convert FFs to zero-initialized FFs, adding additional inputs for\n");
930 log(" uninitialized FFs.\n");
931 log("\n");
932 log(" -symbols\n");
933 log(" include a symbol table in the generated AIGER file\n");
934 log("\n");
935 log(" -map <filename>\n");
936 log(" write an extra file with port and latch symbols\n");
937 log("\n");
938 log(" -vmap <filename>\n");
939 log(" like -map, but more verbose\n");
940 log("\n");
941 log(" -I, -O, -B\n");
942 log(" If the design contains no input/output/assert then create one\n");
943 log(" dummy input/output/bad_state pin to make the tools reading the\n");
944 log(" AIGER file happy.\n");
945 log("\n");
946 }
947 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
948 {
949 bool ascii_mode = false;
950 bool zinit_mode = false;
951 bool miter_mode = false;
952 bool symbols_mode = false;
953 bool verbose_map = false;
954 bool imode = false;
955 bool omode = false;
956 bool bmode = false;
957 std::string map_filename;
958
959 log_header(design, "Executing XAIGER backend.\n");
960
961 size_t argidx;
962 for (argidx = 1; argidx < args.size(); argidx++)
963 {
964 if (args[argidx] == "-ascii") {
965 ascii_mode = true;
966 continue;
967 }
968 if (args[argidx] == "-zinit") {
969 zinit_mode = true;
970 continue;
971 }
972 if (args[argidx] == "-symbols") {
973 symbols_mode = true;
974 continue;
975 }
976 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
977 map_filename = args[++argidx];
978 continue;
979 }
980 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
981 map_filename = args[++argidx];
982 verbose_map = true;
983 continue;
984 }
985 if (args[argidx] == "-I") {
986 imode = true;
987 continue;
988 }
989 if (args[argidx] == "-O") {
990 omode = true;
991 continue;
992 }
993 if (args[argidx] == "-B") {
994 bmode = true;
995 continue;
996 }
997 break;
998 }
999 extra_args(f, filename, args, argidx);
1000
1001 Module *top_module = design->top_module();
1002
1003 if (top_module == nullptr)
1004 log_error("Can't find top module in current design!\n");
1005
1006 XAigerWriter writer(top_module, zinit_mode, imode, omode, bmode);
1007 writer.write_aiger(*f, ascii_mode, miter_mode, symbols_mode, omode);
1008
1009 if (!map_filename.empty()) {
1010 std::ofstream mapf;
1011 mapf.open(map_filename.c_str(), std::ofstream::trunc);
1012 if (mapf.fail())
1013 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
1014 writer.write_map(mapf, verbose_map, omode);
1015 }
1016 }
1017 } XAigerBackend;
1018
1019 PRIVATE_NAMESPACE_END