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