Use "(id)" instead of "id" for types as temporary hack
[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 bswap32 _byteswap_ulong
25 #elif defined(__APPLE__)
26 #include <libkern/OSByteOrder.h>
27 #define bswap32 OSSwapInt32
28 #elif defined(__GNUC__)
29 #define bswap32 __builtin_bswap32
30 #else
31 #include <cstdint>
32 inline static uint32_t bswap32(uint32_t x)
33 {
34 // https://stackoverflow.com/a/27796212
35 register uint32_t value = number_to_be_reversed;
36 uint8_t lolo = (value >> 0) & 0xFF;
37 uint8_t lohi = (value >> 8) & 0xFF;
38 uint8_t hilo = (value >> 16) & 0xFF;
39 uint8_t hihi = (value >> 24) & 0xFF;
40 return (hihi << 24)
41 | (hilo << 16)
42 | (lohi << 8)
43 | (lolo << 0);
44 }
45 #endif
46
47 #include "kernel/yosys.h"
48 #include "kernel/sigtools.h"
49 #include "kernel/utils.h"
50
51 USING_YOSYS_NAMESPACE
52 PRIVATE_NAMESPACE_BEGIN
53
54 inline int32_t to_big_endian(int32_t i32) {
55 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
56 return bswap32(i32);
57 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
58 return i32;
59 #else
60 #error "Unknown endianness"
61 #endif
62 }
63
64 void aiger_encode(std::ostream &f, int x)
65 {
66 log_assert(x >= 0);
67
68 while (x & ~0x7f) {
69 f.put((x & 0x7f) | 0x80);
70 x = x >> 7;
71 }
72
73 f.put(x);
74 }
75
76 struct XAigerWriter
77 {
78 Module *module;
79 SigMap sigmap;
80
81 pool<SigBit> input_bits, output_bits;
82 dict<SigBit, SigBit> not_map, alias_map;
83 dict<SigBit, pair<SigBit, SigBit>> and_map;
84 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int>> ci_bits;
85 vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int,int>> co_bits;
86 dict<SigBit, float> arrival_times;
87
88 vector<pair<int, int>> aig_gates;
89 vector<int> aig_outputs;
90 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
91
92 dict<SigBit, int> aig_map;
93 dict<SigBit, int> ordered_outputs;
94
95 vector<Cell*> box_list;
96 bool omode = false;
97
98 int mkgate(int a0, int a1)
99 {
100 aig_m++, aig_a++;
101 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
102 return 2*aig_m;
103 }
104
105 int bit2aig(SigBit bit)
106 {
107 auto it = aig_map.find(bit);
108 if (it != aig_map.end()) {
109 log_assert(it->second >= 0);
110 return it->second;
111 }
112
113 // NB: Cannot use iterator returned from aig_map.insert()
114 // since this function is called recursively
115
116 int a = -1;
117 if (not_map.count(bit)) {
118 a = bit2aig(not_map.at(bit)) ^ 1;
119 } else
120 if (and_map.count(bit)) {
121 auto args = and_map.at(bit);
122 int a0 = bit2aig(args.first);
123 int a1 = bit2aig(args.second);
124 a = mkgate(a0, a1);
125 } else
126 if (alias_map.count(bit)) {
127 a = bit2aig(alias_map.at(bit));
128 }
129
130 if (bit == State::Sx || bit == State::Sz) {
131 log_debug("Design contains 'x' or 'z' bits. Treating as 1'b0.\n");
132 a = aig_map.at(State::S0);
133 }
134
135 log_assert(a >= 0);
136 aig_map[bit] = a;
137 return a;
138 }
139
140 XAigerWriter(Module *module, bool holes_mode=false) : module(module), sigmap(module)
141 {
142 pool<SigBit> undriven_bits;
143 pool<SigBit> unused_bits;
144 pool<SigBit> keep_bits;
145
146 // promote public wires
147 for (auto wire : module->wires())
148 if (wire->name[0] == '\\')
149 sigmap.add(wire);
150
151 // promote input wires
152 for (auto wire : module->wires())
153 if (wire->port_input)
154 sigmap.add(wire);
155
156 // promote output wires
157 for (auto wire : module->wires())
158 if (wire->port_output)
159 sigmap.add(wire);
160
161 for (auto wire : module->wires())
162 {
163 bool keep = wire->attributes.count("\\keep");
164
165 for (int i = 0; i < GetSize(wire); i++)
166 {
167 SigBit wirebit(wire, i);
168 SigBit bit = sigmap(wirebit);
169
170 if (bit.wire) {
171 undriven_bits.insert(bit);
172 unused_bits.insert(bit);
173 }
174
175 if (keep)
176 keep_bits.insert(bit);
177
178 if (wire->port_input || keep) {
179 if (bit != wirebit)
180 alias_map[bit] = wirebit;
181 input_bits.insert(wirebit);
182 }
183
184 if (wire->port_output || keep) {
185 if (bit != RTLIL::Sx) {
186 if (bit != wirebit)
187 alias_map[wirebit] = bit;
188 output_bits.insert(wirebit);
189 }
190 else
191 log_debug("Skipping PO '%s' driven by 1'bx\n", log_signal(wirebit));
192 }
193 }
194 }
195
196 for (auto bit : input_bits)
197 undriven_bits.erase(sigmap(bit));
198 for (auto bit : output_bits)
199 if (!bit.wire->port_input)
200 unused_bits.erase(bit);
201
202 // TODO: Speed up toposort -- ultimately we care about
203 // box ordering, but not individual AIG cells
204 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
205 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
206 bool abc9_box_seen = false;
207
208 for (auto cell : module->selected_cells()) {
209 if (cell->type == "$_NOT_")
210 {
211 SigBit A = sigmap(cell->getPort("\\A").as_bit());
212 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
213 unused_bits.erase(A);
214 undriven_bits.erase(Y);
215 not_map[Y] = A;
216 if (!holes_mode) {
217 toposort.node(cell->name);
218 bit_users[A].insert(cell->name);
219 bit_drivers[Y].insert(cell->name);
220 }
221 continue;
222 }
223
224 if (cell->type == "$_AND_")
225 {
226 SigBit A = sigmap(cell->getPort("\\A").as_bit());
227 SigBit B = sigmap(cell->getPort("\\B").as_bit());
228 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
229 unused_bits.erase(A);
230 unused_bits.erase(B);
231 undriven_bits.erase(Y);
232 and_map[Y] = make_pair(A, B);
233 if (!holes_mode) {
234 toposort.node(cell->name);
235 bit_users[A].insert(cell->name);
236 bit_users[B].insert(cell->name);
237 bit_drivers[Y].insert(cell->name);
238 }
239 continue;
240 }
241
242 log_assert(!holes_mode);
243
244 RTLIL::Module* inst_module = module->design->module(cell->type);
245 if (inst_module && inst_module->attributes.count("\\abc9_box_id")) {
246 abc9_box_seen = true;
247
248 if (!holes_mode) {
249 toposort.node(cell->name);
250 for (const auto &conn : cell->connections()) {
251 auto port_wire = inst_module->wire(conn.first);
252 if (port_wire->port_input) {
253 // Ignore inout for the sake of topographical ordering
254 if (port_wire->port_output) continue;
255 for (auto bit : sigmap(conn.second))
256 bit_users[bit].insert(cell->name);
257 }
258
259 if (port_wire->port_output)
260 for (auto bit : sigmap(conn.second))
261 bit_drivers[bit].insert(cell->name);
262 }
263 }
264 }
265 else {
266 bool cell_known = inst_module || cell->known();
267 for (const auto &c : cell->connections()) {
268 if (c.second.is_fully_const()) continue;
269 auto port_wire = inst_module ? inst_module->wire(c.first) : nullptr;
270 auto is_input = (port_wire && port_wire->port_input) || !cell_known || cell->input(c.first);
271 auto is_output = (port_wire && port_wire->port_output) || !cell_known || cell->output(c.first);
272 if (!is_input && !is_output)
273 log_error("Connection '%s' on cell '%s' (type '%s') not recognised!\n", log_id(c.first), log_id(cell), log_id(cell->type));
274
275 if (is_input) {
276 for (auto b : c.second) {
277 Wire *w = b.wire;
278 if (!w) continue;
279 if (!w->port_output || !cell_known) {
280 SigBit I = sigmap(b);
281 if (I != b)
282 alias_map[b] = I;
283 output_bits.insert(b);
284 unused_bits.erase(b);
285
286 if (!cell_known)
287 keep_bits.insert(b);
288 }
289 }
290 }
291 if (is_output) {
292 int arrival = 0;
293 if (port_wire) {
294 auto it = port_wire->attributes.find("\\abc9_arrival");
295 if (it != port_wire->attributes.end()) {
296 if (it->second.flags != 0)
297 log_error("Attribute 'abc9_arrival' on port '%s' of module '%s' is not an integer.\n", log_id(port_wire), log_id(cell->type));
298 arrival = it->second.as_int();
299 }
300 }
301
302 for (auto b : c.second) {
303 Wire *w = b.wire;
304 if (!w) continue;
305 input_bits.insert(b);
306 SigBit O = sigmap(b);
307 if (O != b)
308 alias_map[O] = b;
309 undriven_bits.erase(O);
310
311 if (arrival)
312 arrival_times[b] = arrival;
313 }
314 }
315 }
316 }
317
318 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
319 }
320
321 if (abc9_box_seen) {
322 for (auto &it : bit_users)
323 if (bit_drivers.count(it.first))
324 for (auto driver_cell : bit_drivers.at(it.first))
325 for (auto user_cell : it.second)
326 toposort.edge(driver_cell, user_cell);
327
328 #if 0
329 toposort.analyze_loops = true;
330 #endif
331 bool no_loops YS_ATTRIBUTE(unused) = toposort.sort();
332 #if 0
333 unsigned i = 0;
334 for (auto &it : toposort.loops) {
335 log(" loop %d\n", i++);
336 for (auto cell_name : it) {
337 auto cell = module->cell(cell_name);
338 log_assert(cell);
339 log("\t%s (%s @ %s)\n", log_id(cell), log_id(cell->type), cell->get_src_attribute().c_str());
340 }
341 }
342 #endif
343 log_assert(no_loops);
344
345 for (auto cell_name : toposort.sorted) {
346 RTLIL::Cell *cell = module->cell(cell_name);
347 log_assert(cell);
348
349 RTLIL::Module* box_module = module->design->module(cell->type);
350 if (!box_module || !box_module->attributes.count("\\abc9_box_id"))
351 continue;
352
353 bool blackbox = box_module->get_blackbox_attribute(true /* ignore_wb */);
354
355 // Fully pad all unused input connections of this box cell with S0
356 // Fully pad all undriven output connections of this box cell with anonymous wires
357 // NB: Assume box_module->ports are sorted alphabetically
358 // (as RTLIL::Module::fixup_ports() would do)
359 for (const auto &port_name : box_module->ports) {
360 RTLIL::Wire* w = box_module->wire(port_name);
361 log_assert(w);
362 auto it = cell->connections_.find(port_name);
363 if (w->port_input) {
364 RTLIL::SigSpec rhs;
365 if (it != cell->connections_.end()) {
366 if (GetSize(it->second) < GetSize(w))
367 it->second.append(RTLIL::SigSpec(State::S0, GetSize(w)-GetSize(it->second)));
368 rhs = it->second;
369 }
370 else {
371 rhs = RTLIL::SigSpec(State::S0, GetSize(w));
372 cell->setPort(port_name, rhs);
373 }
374
375 int offset = 0;
376 for (auto b : rhs.bits()) {
377 SigBit I = sigmap(b);
378 if (b == RTLIL::Sx)
379 b = State::S0;
380 else if (I != b) {
381 if (I == RTLIL::Sx)
382 alias_map[b] = State::S0;
383 else
384 alias_map[b] = I;
385 }
386 co_bits.emplace_back(b, cell, port_name, offset++, 0);
387 unused_bits.erase(b);
388 }
389 }
390 if (w->port_output) {
391 RTLIL::SigSpec rhs;
392 auto it = cell->connections_.find(w->name);
393 if (it != cell->connections_.end()) {
394 if (GetSize(it->second) < GetSize(w))
395 it->second.append(module->addWire(NEW_ID, GetSize(w)-GetSize(it->second)));
396 rhs = it->second;
397 }
398 else {
399 Wire *wire = module->addWire(NEW_ID, GetSize(w));
400 if (blackbox)
401 wire->set_bool_attribute(ID(abc9_padding));
402 rhs = wire;
403 cell->setPort(port_name, rhs);
404 }
405
406 int offset = 0;
407 for (const auto &b : rhs.bits()) {
408 ci_bits.emplace_back(b, cell, port_name, offset++);
409 SigBit O = sigmap(b);
410 if (O != b)
411 alias_map[O] = b;
412 undriven_bits.erase(O);
413 input_bits.erase(b);
414 }
415 }
416 }
417 box_list.emplace_back(cell);
418 }
419
420 // TODO: Free memory from toposort, bit_drivers, bit_users
421 }
422
423 for (auto bit : input_bits) {
424 if (!output_bits.count(bit))
425 continue;
426 RTLIL::Wire *wire = bit.wire;
427 // If encountering an inout port, or a keep-ed wire, then create a new wire
428 // with $inout.out suffix, make it a PO driven by the existing inout, and
429 // inherit existing inout's drivers
430 if ((wire->port_input && wire->port_output && !undriven_bits.count(bit))
431 || keep_bits.count(bit)) {
432 RTLIL::IdString wire_name = stringf("$%s$inout.out", wire->name.c_str());
433 RTLIL::Wire *new_wire = module->wire(wire_name);
434 if (!new_wire)
435 new_wire = module->addWire(wire_name, GetSize(wire));
436 SigBit new_bit(new_wire, bit.offset);
437 module->connect(new_bit, bit);
438 if (not_map.count(bit)) {
439 auto a = not_map.at(bit);
440 not_map[new_bit] = a;
441 }
442 else if (and_map.count(bit)) {
443 auto a = and_map.at(bit);
444 and_map[new_bit] = a;
445 }
446 else if (alias_map.count(bit)) {
447 auto a = alias_map.at(bit);
448 alias_map[new_bit] = a;
449 }
450 else
451 alias_map[new_bit] = bit;
452 output_bits.erase(bit);
453 output_bits.insert(new_bit);
454 }
455 }
456
457 for (auto bit : unused_bits)
458 undriven_bits.erase(bit);
459
460 if (!undriven_bits.empty() && !holes_mode) {
461 undriven_bits.sort();
462 for (auto bit : undriven_bits) {
463 log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
464 input_bits.insert(bit);
465 }
466 log_warning("Treating a total of %d undriven bits in %s like $anyseq.\n", GetSize(undriven_bits), log_id(module));
467 }
468
469 if (holes_mode) {
470 struct sort_by_port_id {
471 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
472 return a.wire->port_id < b.wire->port_id;
473 }
474 };
475 input_bits.sort(sort_by_port_id());
476 output_bits.sort(sort_by_port_id());
477 }
478 else {
479 input_bits.sort();
480 output_bits.sort();
481 }
482
483 not_map.sort();
484 and_map.sort();
485
486 aig_map[State::S0] = 0;
487 aig_map[State::S1] = 1;
488
489 for (auto bit : input_bits) {
490 aig_m++, aig_i++;
491 log_assert(!aig_map.count(bit));
492 aig_map[bit] = 2*aig_m;
493 }
494
495 for (auto &c : ci_bits) {
496 RTLIL::SigBit bit = std::get<0>(c);
497 aig_m++, aig_i++;
498 aig_map[bit] = 2*aig_m;
499 }
500
501 for (auto &c : co_bits) {
502 RTLIL::SigBit bit = std::get<0>(c);
503 std::get<4>(c) = ordered_outputs[bit] = aig_o++;
504 aig_outputs.push_back(bit2aig(bit));
505 }
506
507 if (output_bits.empty()) {
508 output_bits.insert(State::S0);
509 omode = true;
510 }
511
512 for (auto bit : output_bits) {
513 ordered_outputs[bit] = aig_o++;
514 aig_outputs.push_back(bit2aig(bit));
515 }
516
517 }
518
519 void write_aiger(std::ostream &f, bool ascii_mode)
520 {
521 int aig_obc = aig_o;
522 int aig_obcj = aig_obc;
523 int aig_obcjf = aig_obcj;
524
525 log_assert(aig_m == aig_i + aig_l + aig_a);
526 log_assert(aig_obcjf == GetSize(aig_outputs));
527
528 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
529 f << stringf("\n");
530
531 if (ascii_mode)
532 {
533 for (int i = 0; i < aig_i; i++)
534 f << stringf("%d\n", 2*i+2);
535
536 for (int i = 0; i < aig_obc; i++)
537 f << stringf("%d\n", aig_outputs.at(i));
538
539 for (int i = aig_obc; i < aig_obcj; i++)
540 f << stringf("1\n");
541
542 for (int i = aig_obc; i < aig_obcj; i++)
543 f << stringf("%d\n", aig_outputs.at(i));
544
545 for (int i = aig_obcj; i < aig_obcjf; i++)
546 f << stringf("%d\n", aig_outputs.at(i));
547
548 for (int i = 0; i < aig_a; i++)
549 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
550 }
551 else
552 {
553 for (int i = 0; i < aig_obc; i++)
554 f << stringf("%d\n", aig_outputs.at(i));
555
556 for (int i = aig_obc; i < aig_obcj; i++)
557 f << stringf("1\n");
558
559 for (int i = aig_obc; i < aig_obcj; i++)
560 f << stringf("%d\n", aig_outputs.at(i));
561
562 for (int i = aig_obcj; i < aig_obcjf; i++)
563 f << stringf("%d\n", aig_outputs.at(i));
564
565 for (int i = 0; i < aig_a; i++) {
566 int lhs = 2*(aig_i+aig_l+i)+2;
567 int rhs0 = aig_gates.at(i).first;
568 int rhs1 = aig_gates.at(i).second;
569 int delta0 = lhs - rhs0;
570 int delta1 = rhs0 - rhs1;
571 aiger_encode(f, delta0);
572 aiger_encode(f, delta1);
573 }
574 }
575
576 f << "c";
577
578 log_assert(!output_bits.empty());
579 auto write_buffer = [](std::stringstream &buffer, int i32) {
580 int32_t i32_be = to_big_endian(i32);
581 buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
582 };
583 std::stringstream h_buffer;
584 auto write_h_buffer = std::bind(write_buffer, std::ref(h_buffer), std::placeholders::_1);
585 write_h_buffer(1);
586 log_debug("ciNum = %d\n", GetSize(input_bits) + GetSize(ci_bits));
587 write_h_buffer(input_bits.size() + ci_bits.size());
588 log_debug("coNum = %d\n", GetSize(output_bits) + GetSize(co_bits));
589 write_h_buffer(output_bits.size() + GetSize(co_bits));
590 log_debug("piNum = %d\n", GetSize(input_bits));
591 write_h_buffer(input_bits.size());
592 log_debug("poNum = %d\n", GetSize(output_bits));
593 write_h_buffer(output_bits.size());
594 log_debug("boxNum = %d\n", GetSize(box_list));
595 write_h_buffer(box_list.size());
596
597 auto write_buffer_float = [](std::stringstream &buffer, float f32) {
598 buffer.write(reinterpret_cast<const char*>(&f32), sizeof(f32));
599 };
600 std::stringstream i_buffer;
601 auto write_i_buffer = std::bind(write_buffer_float, std::ref(i_buffer), std::placeholders::_1);
602 for (auto bit : input_bits)
603 write_i_buffer(arrival_times.at(bit, 0));
604 //std::stringstream o_buffer;
605 //auto write_o_buffer = std::bind(write_buffer_float, std::ref(o_buffer), std::placeholders::_1);
606 //for (auto bit : output_bits)
607 // write_o_buffer(0);
608
609 if (!box_list.empty()) {
610 RTLIL::Module *holes_module = module->design->addModule("$__holes__");
611 log_assert(holes_module);
612
613 int port_id = 1;
614 int box_count = 0;
615 for (auto cell : box_list) {
616 RTLIL::Module* box_module = module->design->module(cell->type);
617 int box_inputs = 0, box_outputs = 0;
618 Cell *holes_cell = nullptr;
619 if (box_module->get_bool_attribute("\\whitebox")) {
620 holes_cell = holes_module->addCell(cell->name, cell->type);
621 holes_cell->parameters = cell->parameters;
622 }
623
624 // NB: Assume box_module->ports are sorted alphabetically
625 // (as RTLIL::Module::fixup_ports() would do)
626 for (const auto &port_name : box_module->ports) {
627 RTLIL::Wire *w = box_module->wire(port_name);
628 log_assert(w);
629 RTLIL::Wire *holes_wire;
630 RTLIL::SigSpec port_wire;
631 if (w->port_input) {
632 for (int i = 0; i < GetSize(w); i++) {
633 box_inputs++;
634 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
635 if (!holes_wire) {
636 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
637 holes_wire->port_input = true;
638 holes_wire->port_id = port_id++;
639 holes_module->ports.push_back(holes_wire->name);
640 }
641 if (holes_cell)
642 port_wire.append(holes_wire);
643 }
644 if (!port_wire.empty())
645 holes_cell->setPort(w->name, port_wire);
646 }
647 if (w->port_output) {
648 box_outputs += GetSize(w);
649 for (int i = 0; i < GetSize(w); i++) {
650 if (GetSize(w) == 1)
651 holes_wire = holes_module->addWire(stringf("%s.%s", cell->name.c_str(), w->name.c_str()));
652 else
653 holes_wire = holes_module->addWire(stringf("%s.%s[%d]", cell->name.c_str(), w->name.c_str(), i));
654 holes_wire->port_output = true;
655 holes_wire->port_id = port_id++;
656 holes_module->ports.push_back(holes_wire->name);
657 if (holes_cell)
658 port_wire.append(holes_wire);
659 else
660 holes_module->connect(holes_wire, State::S0);
661 }
662 if (!port_wire.empty())
663 holes_cell->setPort(w->name, port_wire);
664 }
665 }
666
667 write_h_buffer(box_inputs);
668 write_h_buffer(box_outputs);
669 write_h_buffer(box_module->attributes.at("\\abc9_box_id").as_int());
670 write_h_buffer(box_count++);
671 }
672
673 std::stringstream r_buffer;
674 auto write_r_buffer = std::bind(write_buffer, std::ref(r_buffer), std::placeholders::_1);
675 write_r_buffer(0);
676 f << "r";
677 std::string buffer_str = r_buffer.str();
678 int32_t buffer_size_be = to_big_endian(buffer_str.size());
679 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
680 f.write(buffer_str.data(), buffer_str.size());
681
682 if (holes_module) {
683 log_push();
684
685 // NB: fixup_ports() will sort ports by name
686 //holes_module->fixup_ports();
687 holes_module->check();
688
689 holes_module->design->selection_stack.emplace_back(false);
690 RTLIL::Selection& sel = holes_module->design->selection_stack.back();
691 sel.select(holes_module);
692
693 // TODO: Should not need to opt_merge if we only instantiate
694 // each box type once...
695 Pass::call(holes_module->design, "opt_merge -share_all");
696
697 Pass::call(holes_module->design, "flatten -wb");
698
699 // TODO: Should techmap/aigmap/check all lib_whitebox-es just once,
700 // instead of per write_xaiger call
701 Pass::call(holes_module->design, "techmap");
702 Pass::call(holes_module->design, "aigmap");
703 for (auto cell : holes_module->cells())
704 if (!cell->type.in("$_NOT_", "$_AND_"))
705 log_error("Whitebox contents cannot be represented as AIG. Please verify whiteboxes are synthesisable.\n");
706
707 holes_module->design->selection_stack.pop_back();
708
709 // Move into a new (temporary) design so that "clean" will only
710 // operate (and run checks on) this one module
711 RTLIL::Design *holes_design = new RTLIL::Design;
712 holes_module->design->modules_.erase(holes_module->name);
713 holes_design->add(holes_module);
714 Pass::call(holes_design, "clean -purge");
715
716 std::stringstream a_buffer;
717 XAigerWriter writer(holes_module, true /* holes_mode */);
718 writer.write_aiger(a_buffer, false /*ascii_mode*/);
719
720 delete holes_design;
721
722 f << "a";
723 std::string buffer_str = a_buffer.str();
724 int32_t buffer_size_be = to_big_endian(buffer_str.size());
725 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
726 f.write(buffer_str.data(), buffer_str.size());
727
728 log_pop();
729 }
730 }
731
732 f << "h";
733 std::string buffer_str = h_buffer.str();
734 int32_t buffer_size_be = to_big_endian(buffer_str.size());
735 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
736 f.write(buffer_str.data(), buffer_str.size());
737
738 f << "i";
739 buffer_str = i_buffer.str();
740 buffer_size_be = to_big_endian(buffer_str.size());
741 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
742 f.write(buffer_str.data(), buffer_str.size());
743 //f << "o";
744 //buffer_str = o_buffer.str();
745 //buffer_size_be = to_big_endian(buffer_str.size());
746 //f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
747 //f.write(buffer_str.data(), buffer_str.size());
748
749 f << stringf("Generated by %s\n", yosys_version_str);
750 }
751
752 void write_map(std::ostream &f, bool verbose_map)
753 {
754 dict<int, string> input_lines;
755 dict<int, string> output_lines;
756 dict<int, string> wire_lines;
757
758 for (auto wire : module->wires())
759 {
760 //if (!verbose_map && wire->name[0] == '$')
761 // continue;
762
763 SigSpec sig = sigmap(wire);
764
765 for (int i = 0; i < GetSize(wire); i++)
766 {
767 RTLIL::SigBit b(wire, i);
768 if (input_bits.count(b)) {
769 int a = aig_map.at(b);
770 log_assert((a & 1) == 0);
771 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
772 }
773
774 if (output_bits.count(b)) {
775 int o = ordered_outputs.at(b);
776 output_lines[o] += stringf("output %d %d %s\n", o - GetSize(co_bits), i, log_id(wire));
777 continue;
778 }
779
780 if (verbose_map) {
781 if (aig_map.count(sig[i]) == 0)
782 continue;
783
784 int a = aig_map.at(sig[i]);
785 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
786 }
787 }
788 }
789
790 input_lines.sort();
791 for (auto &it : input_lines)
792 f << it.second;
793 log_assert(input_lines.size() == input_bits.size());
794
795 int box_count = 0;
796 for (auto cell : box_list)
797 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
798
799 output_lines.sort();
800 if (omode)
801 output_lines[State::S0] = "output 0 0 $__dummy__\n";
802 for (auto &it : output_lines)
803 f << it.second;
804 log_assert(output_lines.size() == output_bits.size());
805
806 wire_lines.sort();
807 for (auto &it : wire_lines)
808 f << it.second;
809 }
810 };
811
812 struct XAigerBackend : public Backend {
813 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
814 void help() YS_OVERRIDE
815 {
816 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
817 log("\n");
818 log(" write_xaiger [options] [filename]\n");
819 log("\n");
820 log("Write the current design to an XAIGER file. The design must be flattened and\n");
821 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
822 log("\n");
823 log(" -ascii\n");
824 log(" write ASCII version of AIGER format\n");
825 log("\n");
826 log(" -map <filename>\n");
827 log(" write an extra file with port and latch symbols\n");
828 log("\n");
829 log(" -vmap <filename>\n");
830 log(" like -map, but more verbose\n");
831 log("\n");
832 }
833 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
834 {
835 bool ascii_mode = false;
836 bool verbose_map = false;
837 std::string map_filename;
838
839 log_header(design, "Executing XAIGER backend.\n");
840
841 size_t argidx;
842 for (argidx = 1; argidx < args.size(); argidx++)
843 {
844 if (args[argidx] == "-ascii") {
845 ascii_mode = true;
846 continue;
847 }
848 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
849 map_filename = args[++argidx];
850 continue;
851 }
852 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
853 map_filename = args[++argidx];
854 verbose_map = true;
855 continue;
856 }
857 break;
858 }
859 extra_args(f, filename, args, argidx, !ascii_mode);
860
861 Module *top_module = design->top_module();
862
863 if (top_module == nullptr)
864 log_error("Can't find top module in current design!\n");
865
866 XAigerWriter writer(top_module);
867 writer.write_aiger(*f, ascii_mode);
868
869 if (!map_filename.empty()) {
870 std::ofstream mapf;
871 mapf.open(map_filename.c_str(), std::ofstream::trunc);
872 if (mapf.fail())
873 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
874 writer.write_map(mapf, verbose_map);
875 }
876 }
877 } XAigerBackend;
878
879 PRIVATE_NAMESPACE_END