e7d767721387f9782c7da6d904ee9a3b35ff7766
[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, external_bits;
82 dict<SigBit, SigBit> not_map, alias_map;
83 dict<SigBit, pair<SigBit, SigBit>> and_map;
84 vector<SigBit> ci_bits, co_bits;
85 dict<SigBit, std::pair<int,int>> ff_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
97 int mkgate(int a0, int a1)
98 {
99 aig_m++, aig_a++;
100 aig_gates.push_back(a0 > a1 ? make_pair(a0, a1) : make_pair(a1, a0));
101 return 2*aig_m;
102 }
103
104 int bit2aig(SigBit bit)
105 {
106 auto it = aig_map.find(bit);
107 if (it != aig_map.end()) {
108 log_assert(it->second >= 0);
109 return it->second;
110 }
111
112 // NB: Cannot use iterator returned from aig_map.insert()
113 // since this function is called recursively
114
115 int a = -1;
116 if (not_map.count(bit)) {
117 a = bit2aig(not_map.at(bit)) ^ 1;
118 } else
119 if (and_map.count(bit)) {
120 auto args = and_map.at(bit);
121 int a0 = bit2aig(args.first);
122 int a1 = bit2aig(args.second);
123 a = mkgate(a0, a1);
124 } else
125 if (alias_map.count(bit)) {
126 a = bit2aig(alias_map.at(bit));
127 }
128
129 if (bit == State::Sx || bit == State::Sz) {
130 log_debug("Design contains 'x' or 'z' bits. Treating as 1'b0.\n");
131 a = aig_map.at(State::S0);
132 }
133
134 log_assert(a >= 0);
135 aig_map[bit] = a;
136 return a;
137 }
138
139 XAigerWriter(Module *module, bool holes_mode=false) : module(module), sigmap(module)
140 {
141 pool<SigBit> undriven_bits;
142 pool<SigBit> unused_bits;
143 pool<SigBit> inout_bits;
144
145 // promote public wires
146 for (auto wire : module->wires())
147 if (wire->name[0] == '\\')
148 sigmap.add(wire);
149
150 // promote input wires
151 for (auto wire : module->wires())
152 if (wire->port_input)
153 sigmap.add(wire);
154
155 // promote keep wires
156 for (auto wire : module->wires())
157 if (wire->get_bool_attribute(ID::keep))
158 sigmap.add(wire);
159
160 for (auto wire : module->wires())
161 for (int i = 0; i < GetSize(wire); i++)
162 {
163 SigBit wirebit(wire, i);
164 SigBit bit = sigmap(wirebit);
165
166 if (bit.wire == nullptr) {
167 if (wire->port_output) {
168 aig_map[wirebit] = (bit == State::S1) ? 1 : 0;
169 if (holes_mode)
170 output_bits.insert(wirebit);
171 //external_bits.insert(wirebit);
172 }
173 continue;
174 }
175
176 undriven_bits.insert(bit);
177 unused_bits.insert(bit);
178
179 if (wire->port_input)
180 input_bits.insert(bit);
181
182 if (wire->port_output) {
183 if (bit != wirebit)
184 alias_map[wirebit] = bit;
185 if (holes_mode)
186 output_bits.insert(wirebit);
187 else
188 external_bits.insert(wirebit);
189 }
190
191 if (wire->port_input && wire->port_output)
192 inout_bits.insert(wirebit);
193 }
194
195 // TODO: Speed up toposort -- ultimately we care about
196 // box ordering, but not individual AIG cells
197 dict<SigBit, pool<IdString>> bit_drivers, bit_users;
198 TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
199 bool abc9_box_seen = false;
200 std::vector<Cell*> flop_boxes;
201
202 for (auto cell : module->selected_cells()) {
203 if (cell->type == "$_NOT_")
204 {
205 SigBit A = sigmap(cell->getPort("\\A").as_bit());
206 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
207 unused_bits.erase(A);
208 undriven_bits.erase(Y);
209 not_map[Y] = A;
210 if (!holes_mode) {
211 toposort.node(cell->name);
212 bit_users[A].insert(cell->name);
213 bit_drivers[Y].insert(cell->name);
214 }
215 continue;
216 }
217
218 if (cell->type == "$_AND_")
219 {
220 SigBit A = sigmap(cell->getPort("\\A").as_bit());
221 SigBit B = sigmap(cell->getPort("\\B").as_bit());
222 SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
223 unused_bits.erase(A);
224 unused_bits.erase(B);
225 undriven_bits.erase(Y);
226 and_map[Y] = make_pair(A, B);
227 if (!holes_mode) {
228 toposort.node(cell->name);
229 bit_users[A].insert(cell->name);
230 bit_users[B].insert(cell->name);
231 bit_drivers[Y].insert(cell->name);
232 }
233 continue;
234 }
235
236 log_assert(!holes_mode);
237
238 if (cell->type == "$__ABC9_FF_")
239 {
240 SigBit D = sigmap(cell->getPort("\\D").as_bit());
241 SigBit Q = sigmap(cell->getPort("\\Q").as_bit());
242 unused_bits.erase(D);
243 undriven_bits.erase(Q);
244 alias_map[Q] = D;
245 auto r = ff_bits.insert(std::make_pair(D, std::make_pair(0, 2)));
246 log_assert(r.second);
247 continue;
248 }
249
250 RTLIL::Module* inst_module = module->design->module(cell->type);
251 if (inst_module) {
252 bool abc9_box = inst_module->attributes.count("\\abc9_box_id") && !cell->get_bool_attribute("\\abc9_keep");
253
254 for (const auto &conn : cell->connections()) {
255 auto port_wire = inst_module->wire(conn.first);
256
257 if (port_wire->port_output) {
258 int arrival = 0;
259 auto it = port_wire->attributes.find("\\abc9_arrival");
260 if (it != port_wire->attributes.end()) {
261 if (it->second.flags != 0)
262 log_error("Attribute 'abc9_arrival' on port '%s' of module '%s' is not an integer.\n", log_id(port_wire), log_id(cell->type));
263 arrival = it->second.as_int();
264 }
265 if (arrival)
266 for (auto bit : sigmap(conn.second))
267 arrival_times[bit] = arrival;
268 }
269
270 if (abc9_box) {
271 // Ignore inout for the sake of topographical ordering
272 if (port_wire->port_input && !port_wire->port_output)
273 for (auto bit : sigmap(conn.second))
274 bit_users[bit].insert(cell->name);
275 if (port_wire->port_output)
276 for (auto bit : sigmap(conn.second))
277 bit_drivers[bit].insert(cell->name);
278 }
279 }
280
281 if (abc9_box) {
282 abc9_box_seen = true;
283
284 toposort.node(cell->name);
285
286 if (inst_module->attributes.count("\\abc9_flop"))
287 flop_boxes.push_back(cell);
288 continue;
289 }
290 }
291
292 bool cell_known = inst_module || cell->known();
293 for (const auto &c : cell->connections()) {
294 if (c.second.is_fully_const()) continue;
295 auto port_wire = inst_module ? inst_module->wire(c.first) : nullptr;
296 auto is_input = (port_wire && port_wire->port_input) || !cell_known || cell->input(c.first);
297 auto is_output = (port_wire && port_wire->port_output) || !cell_known || cell->output(c.first);
298 if (!is_input && !is_output)
299 log_error("Connection '%s' on cell '%s' (type '%s') not recognised!\n", log_id(c.first), log_id(cell), log_id(cell->type));
300
301 if (is_input) {
302 for (auto b : c.second) {
303 Wire *w = b.wire;
304 if (!w) continue;
305 if (!w->port_output || !cell_known) {
306 SigBit I = sigmap(b);
307 if (I != b)
308 alias_map[b] = I;
309 if (holes_mode)
310 output_bits.insert(b);
311 else
312 external_bits.insert(b);
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 dict<IdString, std::pair<IdString,int>> flop_q;
323 for (auto cell : flop_boxes) {
324 auto r = flop_q.insert(std::make_pair(cell->type, std::make_pair(IdString(), 0)));
325 SigBit d;
326 if (r.second) {
327 for (const auto &conn : cell->connections()) {
328 const SigSpec &rhs = conn.second;
329 if (!rhs.is_bit())
330 continue;
331 if (!ff_bits.count(rhs))
332 continue;
333 r.first->second.first = conn.first;
334 Module *inst_module = module->design->module(cell->type);
335 Wire *wire = inst_module->wire(conn.first);
336 log_assert(wire);
337 auto jt = wire->attributes.find("\\abc9_arrival");
338 if (jt != wire->attributes.end()) {
339 if (jt->second.flags != 0)
340 log_error("Attribute 'abc9_arrival' on port '%s' of module '%s' is not an integer.\n", log_id(wire), log_id(cell->type));
341 r.first->second.second = jt->second.as_int();
342 }
343 d = rhs;
344 log_assert(d == sigmap(d));
345 break;
346 }
347 }
348 else
349 d = cell->getPort(r.first->second.first);
350
351 auto &rhs = ff_bits.at(d);
352
353 auto it = cell->attributes.find(ID(abc9_mergeability));
354 log_assert(it != cell->attributes.end());
355 rhs.first = it->second.as_int();
356 cell->attributes.erase(it);
357
358 it = cell->attributes.find(ID(abc9_init));
359 log_assert(it != cell->attributes.end());
360 log_assert(GetSize(it->second) == 1);
361 if (it->second[0] == State::S1)
362 rhs.second = 1;
363 else if (it->second[0] == State::S0)
364 rhs.second = 0;
365 else {
366 log_assert(it->second[0] == State::Sx);
367 rhs.second = 0;
368 }
369 cell->attributes.erase(it);
370
371 auto arrival = r.first->second.second;
372 if (arrival)
373 arrival_times[d] = arrival;
374 }
375
376 for (auto &it : bit_users)
377 if (bit_drivers.count(it.first))
378 for (auto driver_cell : bit_drivers.at(it.first))
379 for (auto user_cell : it.second)
380 toposort.edge(driver_cell, user_cell);
381
382 #if 0
383 toposort.analyze_loops = true;
384 #endif
385 bool no_loops YS_ATTRIBUTE(unused) = toposort.sort();
386 #if 0
387 unsigned i = 0;
388 for (auto &it : toposort.loops) {
389 log(" loop %d\n", i++);
390 for (auto cell_name : it) {
391 auto cell = module->cell(cell_name);
392 log_assert(cell);
393 log("\t%s (%s @ %s)\n", log_id(cell), log_id(cell->type), cell->get_src_attribute().c_str());
394 }
395 }
396 #endif
397 log_assert(no_loops);
398
399 for (auto cell_name : toposort.sorted) {
400 RTLIL::Cell *cell = module->cell(cell_name);
401 log_assert(cell);
402
403 RTLIL::Module* box_module = module->design->module(cell->type);
404 if (!box_module || !box_module->attributes.count("\\abc9_box_id")
405 || cell->get_bool_attribute("\\abc9_keep"))
406 continue;
407
408 bool blackbox = box_module->get_blackbox_attribute(true /* ignore_wb */);
409
410 // Fully pad all unused input connections of this box cell with S0
411 // Fully pad all undriven output connections of this box cell with anonymous wires
412 // NB: Assume box_module->ports are sorted alphabetically
413 // (as RTLIL::Module::fixup_ports() would do)
414 for (const auto &port_name : box_module->ports) {
415 RTLIL::Wire* w = box_module->wire(port_name);
416 log_assert(w);
417 auto it = cell->connections_.find(port_name);
418 if (w->port_input) {
419 RTLIL::SigSpec rhs;
420 if (it != cell->connections_.end()) {
421 if (GetSize(it->second) < GetSize(w))
422 it->second.append(RTLIL::SigSpec(State::S0, GetSize(w)-GetSize(it->second)));
423 rhs = it->second;
424 }
425 else {
426 rhs = RTLIL::SigSpec(State::S0, GetSize(w));
427 cell->setPort(port_name, rhs);
428 }
429
430 for (auto b : rhs.bits()) {
431 SigBit I = sigmap(b);
432 if (b == RTLIL::Sx)
433 b = State::S0;
434 else if (I != b) {
435 if (I == RTLIL::Sx)
436 alias_map[b] = State::S0;
437 else
438 alias_map[b] = I;
439 }
440 co_bits.emplace_back(b);
441 unused_bits.erase(I);
442 }
443 }
444 if (w->port_output) {
445 RTLIL::SigSpec rhs;
446 auto it = cell->connections_.find(w->name);
447 if (it != cell->connections_.end()) {
448 if (GetSize(it->second) < GetSize(w))
449 it->second.append(module->addWire(NEW_ID, GetSize(w)-GetSize(it->second)));
450 rhs = it->second;
451 }
452 else {
453 Wire *wire = module->addWire(NEW_ID, GetSize(w));
454 if (blackbox)
455 wire->set_bool_attribute(ID(abc9_padding));
456 rhs = wire;
457 cell->setPort(port_name, rhs);
458 }
459
460 for (const auto &b : rhs.bits()) {
461 ci_bits.emplace_back(b);
462 SigBit O = sigmap(b);
463 if (O != b)
464 alias_map[O] = b;
465 input_bits.erase(O);
466 undriven_bits.erase(O);
467 }
468 }
469 }
470
471 // Connect <cell>.$abc9_currQ (inserted by abc9_map.v) as an input to the flop box
472 if (box_module->get_bool_attribute("\\abc9_flop")) {
473 SigSpec rhs = module->wire(stringf("%s.$abc9_currQ", cell->name.c_str()));
474 if (rhs.empty())
475 log_error("'%s.$abc9_currQ' is not a wire present in module '%s'.\n", log_id(cell), log_id(module));
476
477 for (auto b : rhs) {
478 SigBit I = sigmap(b);
479 if (b == RTLIL::Sx)
480 b = State::S0;
481 else if (I != b) {
482 if (I == RTLIL::Sx)
483 alias_map[b] = State::S0;
484 else
485 alias_map[b] = I;
486 }
487 co_bits.emplace_back(b);
488 unused_bits.erase(I);
489 }
490 }
491
492 box_list.emplace_back(cell);
493 }
494
495 // TODO: Free memory from toposort, bit_drivers, bit_users
496 }
497
498 if (!holes_mode)
499 for (auto cell : module->cells())
500 if (!module->selected(cell))
501 for (auto &conn : cell->connections())
502 if (cell->input(conn.first))
503 for (auto wirebit : conn.second)
504 if (sigmap(wirebit).wire)
505 external_bits.insert(wirebit);
506
507 // For all bits consumed outside of the selected cells,
508 // but driven from a selected cell, then add it as
509 // a primary output
510 for (auto wirebit : external_bits) {
511 SigBit bit = sigmap(wirebit);
512 if (!bit.wire)
513 continue;
514 if (!undriven_bits.count(bit)) {
515 if (bit != wirebit)
516 alias_map[wirebit] = bit;
517 output_bits.insert(wirebit);
518 }
519 }
520
521 for (auto bit : input_bits)
522 undriven_bits.erase(sigmap(bit));
523 for (auto bit : output_bits)
524 unused_bits.erase(sigmap(bit));
525 for (auto bit : unused_bits)
526 undriven_bits.erase(bit);
527
528 // Make all undriven bits a primary input
529 if (!holes_mode)
530 for (auto bit : undriven_bits) {
531 input_bits.insert(bit);
532 undriven_bits.erase(bit);
533 }
534
535 if (holes_mode) {
536 struct sort_by_port_id {
537 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
538 return a.wire->port_id < b.wire->port_id;
539 }
540 };
541 input_bits.sort(sort_by_port_id());
542 output_bits.sort(sort_by_port_id());
543 }
544 else {
545 input_bits.sort();
546 output_bits.sort();
547 }
548
549 not_map.sort();
550 and_map.sort();
551
552 aig_map[State::S0] = 0;
553 aig_map[State::S1] = 1;
554
555 for (auto bit : input_bits) {
556 aig_m++, aig_i++;
557 log_assert(!aig_map.count(bit));
558 aig_map[bit] = 2*aig_m;
559 }
560
561 for (const auto &i : ff_bits) {
562 const SigBit &bit = i.first;
563 aig_m++, aig_i++;
564 log_assert(!aig_map.count(bit));
565 aig_map[bit] = 2*aig_m;
566 }
567
568 dict<SigBit, int> ff_aig_map;
569 for (auto &bit : ci_bits) {
570 aig_m++, aig_i++;
571 auto r = aig_map.insert(std::make_pair(bit, 2*aig_m));
572 if (!r.second)
573 ff_aig_map[bit] = 2*aig_m;
574 }
575
576 for (auto bit : co_bits) {
577 ordered_outputs[bit] = aig_o++;
578 aig_outputs.push_back(bit2aig(bit));
579 }
580
581 for (auto bit : output_bits) {
582 ordered_outputs[bit] = aig_o++;
583 aig_outputs.push_back(bit2aig(bit));
584 }
585
586 for (auto &i : ff_bits) {
587 const SigBit &bit = i.first;
588 aig_o++;
589 aig_outputs.push_back(ff_aig_map.at(bit));
590 }
591 }
592
593 void write_aiger(std::ostream &f, bool ascii_mode)
594 {
595 int aig_obc = aig_o;
596 int aig_obcj = aig_obc;
597 int aig_obcjf = aig_obcj;
598
599 log_assert(aig_m == aig_i + aig_l + aig_a);
600 log_assert(aig_obcjf == GetSize(aig_outputs));
601
602 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
603 f << stringf("\n");
604
605 if (ascii_mode)
606 {
607 for (int i = 0; i < aig_i; i++)
608 f << stringf("%d\n", 2*i+2);
609
610 for (int i = 0; i < aig_obc; i++)
611 f << stringf("%d\n", aig_outputs.at(i));
612
613 for (int i = aig_obc; i < aig_obcj; i++)
614 f << stringf("1\n");
615
616 for (int i = aig_obc; i < aig_obcj; i++)
617 f << stringf("%d\n", aig_outputs.at(i));
618
619 for (int i = aig_obcj; i < aig_obcjf; i++)
620 f << stringf("%d\n", aig_outputs.at(i));
621
622 for (int i = 0; i < aig_a; i++)
623 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
624 }
625 else
626 {
627 for (int i = 0; i < aig_obc; i++)
628 f << stringf("%d\n", aig_outputs.at(i));
629
630 for (int i = aig_obc; i < aig_obcj; i++)
631 f << stringf("1\n");
632
633 for (int i = aig_obc; i < aig_obcj; i++)
634 f << stringf("%d\n", aig_outputs.at(i));
635
636 for (int i = aig_obcj; i < aig_obcjf; i++)
637 f << stringf("%d\n", aig_outputs.at(i));
638
639 for (int i = 0; i < aig_a; i++) {
640 int lhs = 2*(aig_i+aig_l+i)+2;
641 int rhs0 = aig_gates.at(i).first;
642 int rhs1 = aig_gates.at(i).second;
643 int delta0 = lhs - rhs0;
644 int delta1 = rhs0 - rhs1;
645 aiger_encode(f, delta0);
646 aiger_encode(f, delta1);
647 }
648 }
649
650 f << "c";
651
652 auto write_buffer = [](std::stringstream &buffer, int i32) {
653 int32_t i32_be = to_big_endian(i32);
654 buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
655 };
656 std::stringstream h_buffer;
657 auto write_h_buffer = std::bind(write_buffer, std::ref(h_buffer), std::placeholders::_1);
658 write_h_buffer(1);
659 log_debug("ciNum = %d\n", GetSize(input_bits) + GetSize(ff_bits) + GetSize(ci_bits));
660 write_h_buffer(input_bits.size() + ff_bits.size() + ci_bits.size());
661 log_debug("coNum = %d\n", GetSize(output_bits) + GetSize(ff_bits) + GetSize(co_bits));
662 write_h_buffer(output_bits.size() + GetSize(ff_bits) + GetSize(co_bits));
663 log_debug("piNum = %d\n", GetSize(input_bits) + GetSize(ff_bits));
664 write_h_buffer(input_bits.size() + ff_bits.size());
665 log_debug("poNum = %d\n", GetSize(output_bits) + GetSize(ff_bits));
666 write_h_buffer(output_bits.size() + ff_bits.size());
667 log_debug("boxNum = %d\n", GetSize(box_list));
668 write_h_buffer(box_list.size());
669
670 auto write_buffer_float = [](std::stringstream &buffer, float f32) {
671 buffer.write(reinterpret_cast<const char*>(&f32), sizeof(f32));
672 };
673 std::stringstream i_buffer;
674 auto write_i_buffer = std::bind(write_buffer_float, std::ref(i_buffer), std::placeholders::_1);
675 for (auto bit : input_bits)
676 write_i_buffer(arrival_times.at(bit, 0));
677 //std::stringstream o_buffer;
678 //auto write_o_buffer = std::bind(write_buffer_float, std::ref(o_buffer), std::placeholders::_1);
679 //for (auto bit : output_bits)
680 // write_o_buffer(0);
681
682 if (!box_list.empty() || !ff_bits.empty()) {
683 RTLIL::Module *holes_module = module->design->addModule("$__holes__");
684 log_assert(holes_module);
685
686 dict<IdString, Cell*> cell_cache;
687
688 int port_id = 1;
689 int box_count = 0;
690 for (auto cell : box_list) {
691 RTLIL::Module* orig_box_module = module->design->module(cell->type);
692 log_assert(orig_box_module);
693 IdString derived_name = orig_box_module->derive(module->design, cell->parameters);
694 RTLIL::Module* box_module = module->design->module(derived_name);
695 if (box_module->has_processes())
696 Pass::call_on_module(module->design, box_module, "proc");
697
698 int box_inputs = 0, box_outputs = 0;
699 auto r = cell_cache.insert(std::make_pair(derived_name, nullptr));
700 Cell *holes_cell = r.first->second;
701 if (r.second && box_module->get_bool_attribute("\\whitebox")) {
702 holes_cell = holes_module->addCell(cell->name, cell->type);
703 holes_cell->parameters = cell->parameters;
704 r.first->second = holes_cell;
705
706 // Since Module::derive() will create a new module, there
707 // is a chance that the ports will be alphabetically ordered
708 // again, which is a problem when carry-chains are involved.
709 // Inherit the port ordering from the original module here...
710 // (and set the port_id below, when iterating through those)
711 log_assert(GetSize(box_module->ports) == GetSize(orig_box_module->ports));
712 box_module->ports = orig_box_module->ports;
713 }
714
715 // NB: Assume box_module->ports are sorted alphabetically
716 // (as RTLIL::Module::fixup_ports() would do)
717 int box_port_id = 1;
718 for (const auto &port_name : box_module->ports) {
719 RTLIL::Wire *w = box_module->wire(port_name);
720 log_assert(w);
721 if (r.second)
722 w->port_id = box_port_id++;
723 RTLIL::Wire *holes_wire;
724 RTLIL::SigSpec port_sig;
725 if (w->port_input)
726 for (int i = 0; i < GetSize(w); i++) {
727 box_inputs++;
728 holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
729 if (!holes_wire) {
730 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
731 holes_wire->port_input = true;
732 holes_wire->port_id = port_id++;
733 holes_module->ports.push_back(holes_wire->name);
734 }
735 if (holes_cell)
736 port_sig.append(holes_wire);
737 }
738 if (w->port_output) {
739 box_outputs += GetSize(w);
740 for (int i = 0; i < GetSize(w); i++) {
741 if (GetSize(w) == 1)
742 holes_wire = holes_module->addWire(stringf("$abc%s.%s", cell->name.c_str(), log_id(w->name)));
743 else
744 holes_wire = holes_module->addWire(stringf("$abc%s.%s[%d]", cell->name.c_str(), log_id(w->name), i));
745 holes_wire->port_output = true;
746 holes_wire->port_id = port_id++;
747 holes_module->ports.push_back(holes_wire->name);
748 if (holes_cell)
749 port_sig.append(holes_wire);
750 else
751 holes_module->connect(holes_wire, State::S0);
752 }
753 }
754 if (!port_sig.empty()) {
755 if (r.second)
756 holes_cell->setPort(w->name, port_sig);
757 else
758 holes_module->connect(holes_cell->getPort(w->name), port_sig);
759 }
760 }
761
762 // For flops only, create an extra 1-bit input that drives a new wire
763 // called "<cell>.$abc9_currQ" that is used below
764 if (box_module->get_bool_attribute("\\abc9_flop")) {
765 log_assert(holes_cell);
766
767 box_inputs++;
768 Wire *holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
769 if (!holes_wire) {
770 holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
771 holes_wire->port_input = true;
772 holes_wire->port_id = port_id++;
773 holes_module->ports.push_back(holes_wire->name);
774 }
775 Wire *w = holes_module->addWire(stringf("%s.$abc9_currQ", cell->name.c_str()));
776 holes_module->connect(w, holes_wire);
777 }
778
779 write_h_buffer(box_inputs);
780 write_h_buffer(box_outputs);
781 write_h_buffer(box_module->attributes.at("\\abc9_box_id").as_int());
782 write_h_buffer(box_count++);
783 }
784
785 std::stringstream r_buffer;
786 auto write_r_buffer = std::bind(write_buffer, std::ref(r_buffer), std::placeholders::_1);
787 log_debug("flopNum = %d\n", GetSize(ff_bits));
788 write_r_buffer(ff_bits.size());
789
790 std::stringstream s_buffer;
791 auto write_s_buffer = std::bind(write_buffer, std::ref(s_buffer), std::placeholders::_1);
792 write_s_buffer(ff_bits.size());
793
794 for (const auto &i : ff_bits) {
795 const SigBit &bit = i.first;
796 int mergeability = i.second.first;
797 log_assert(mergeability > 0);
798 write_r_buffer(mergeability);
799 int init = i.second.second;
800 write_s_buffer(init);
801 write_i_buffer(arrival_times.at(bit, 0));
802 //write_o_buffer(0);
803 }
804
805 f << "r";
806 std::string buffer_str = r_buffer.str();
807 int32_t buffer_size_be = to_big_endian(buffer_str.size());
808 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
809 f.write(buffer_str.data(), buffer_str.size());
810
811 f << "s";
812 buffer_str = s_buffer.str();
813 buffer_size_be = to_big_endian(buffer_str.size());
814 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
815 f.write(buffer_str.data(), buffer_str.size());
816
817 if (holes_module) {
818 log_push();
819
820 // NB: fixup_ports() will sort ports by name
821 //holes_module->fixup_ports();
822 holes_module->check();
823
824 // Cannot techmap/aigmap/check all lib_whitebox-es outside of write_xaiger
825 // since boxes may contain parameters in which case `flatten` would have
826 // created a new $paramod ...
827 Pass::call_on_module(holes_module->design, holes_module, "flatten -wb; techmap; aigmap");
828
829 dict<SigSig, SigSig> replace;
830 for (auto it = holes_module->cells_.begin(); it != holes_module->cells_.end(); ) {
831 auto cell = it->second;
832 if (cell->type.in("$_DFF_N_", "$_DFF_NN0_", "$_DFF_NN1_", "$_DFF_NP0_", "$_DFF_NP1_",
833 "$_DFF_P_", "$_DFF_PN0_", "$_DFF_PN1", "$_DFF_PP0_", "$_DFF_PP1_")) {
834 SigBit D = cell->getPort("\\D");
835 SigBit Q = cell->getPort("\\Q");
836 // Remove the DFF cell from what needs to be a combinatorial box
837 it = holes_module->cells_.erase(it);
838 Wire *port;
839 if (GetSize(Q.wire) == 1)
840 port = holes_module->wire(stringf("$abc%s", Q.wire->name.c_str()));
841 else
842 port = holes_module->wire(stringf("$abc%s[%d]", Q.wire->name.c_str(), Q.offset));
843 log_assert(port);
844 // Prepare to replace "assign <port> = DFF.Q;" with "assign <port> = DFF.D;"
845 // in order to extract the combinatorial control logic that feeds the box
846 // (i.e. clock enable, synchronous reset, etc.)
847 replace.insert(std::make_pair(SigSig(port,Q), SigSig(port,D)));
848 // Since `flatten` above would have created wires named "<cell>.Q",
849 // extract the pre-techmap cell name
850 auto pos = Q.wire->name.str().rfind(".");
851 log_assert(pos != std::string::npos);
852 IdString driver = Q.wire->name.substr(0, pos);
853 // And drive the signal that was previously driven by "DFF.Q" (typically
854 // used to implement clock-enable functionality) with the "<cell>.$abc9_currQ"
855 // wire (which itself is driven an input port) we inserted above
856 Wire *currQ = holes_module->wire(stringf("%s.$abc9_currQ", driver.c_str()));
857 log_assert(currQ);
858 holes_module->connect(Q, currQ);
859 continue;
860 }
861 else if (!cell->type.in("$_NOT_", "$_AND_"))
862 log_error("Whitebox contents cannot be represented as AIG. Please verify whiteboxes are synthesisable.\n");
863 ++it;
864 }
865
866 for (auto &conn : holes_module->connections_) {
867 auto it = replace.find(conn);
868 if (it != replace.end())
869 conn = it->second;
870 }
871
872 // Move into a new (temporary) design so that "clean" will only
873 // operate (and run checks on) this one module
874 RTLIL::Design *holes_design = new RTLIL::Design;
875 module->design->modules_.erase(holes_module->name);
876 holes_design->add(holes_module);
877 Pass::call(holes_design, "opt -purge");
878
879 std::stringstream a_buffer;
880 XAigerWriter writer(holes_module, true /* holes_mode */);
881 writer.write_aiger(a_buffer, false /*ascii_mode*/);
882 delete holes_design;
883
884 f << "a";
885 std::string buffer_str = a_buffer.str();
886 int32_t buffer_size_be = to_big_endian(buffer_str.size());
887 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
888 f.write(buffer_str.data(), buffer_str.size());
889
890 log_pop();
891 }
892 }
893
894 f << "h";
895 std::string buffer_str = h_buffer.str();
896 int32_t buffer_size_be = to_big_endian(buffer_str.size());
897 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
898 f.write(buffer_str.data(), buffer_str.size());
899
900 f << "i";
901 buffer_str = i_buffer.str();
902 buffer_size_be = to_big_endian(buffer_str.size());
903 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
904 f.write(buffer_str.data(), buffer_str.size());
905 //f << "o";
906 //buffer_str = o_buffer.str();
907 //buffer_size_be = to_big_endian(buffer_str.size());
908 //f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
909 //f.write(buffer_str.data(), buffer_str.size());
910
911 f << stringf("Generated by %s\n", yosys_version_str);
912
913 module->design->scratchpad_set_int("write_xaiger.num_ands", and_map.size());
914 module->design->scratchpad_set_int("write_xaiger.num_wires", aig_map.size());
915 module->design->scratchpad_set_int("write_xaiger.num_inputs", input_bits.size());
916 module->design->scratchpad_set_int("write_xaiger.num_outputs", output_bits.size());
917 }
918
919 void write_map(std::ostream &f, bool verbose_map)
920 {
921 dict<int, string> input_lines;
922 dict<int, string> output_lines;
923 dict<int, string> wire_lines;
924
925 for (auto wire : module->wires())
926 {
927 //if (!verbose_map && wire->name[0] == '$')
928 // continue;
929
930 SigSpec sig = sigmap(wire);
931
932 for (int i = 0; i < GetSize(wire); i++)
933 {
934 RTLIL::SigBit b(wire, i);
935 if (input_bits.count(b)) {
936 int a = aig_map.at(b);
937 log_assert((a & 1) == 0);
938 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
939 }
940
941 if (output_bits.count(b)) {
942 int o = ordered_outputs.at(b);
943 int init = 2;
944 output_lines[o] += stringf("output %d %d %s %d\n", o - GetSize(co_bits), i, log_id(wire), init);
945 continue;
946 }
947
948 if (verbose_map) {
949 if (aig_map.count(sig[i]) == 0)
950 continue;
951
952 int a = aig_map.at(sig[i]);
953 wire_lines[a] += stringf("wire %d %d %s\n", a, i, log_id(wire));
954 }
955 }
956 }
957
958 input_lines.sort();
959 for (auto &it : input_lines)
960 f << it.second;
961 log_assert(input_lines.size() == input_bits.size());
962
963 int box_count = 0;
964 for (auto cell : box_list)
965 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
966
967 output_lines.sort();
968 for (auto &it : output_lines)
969 f << it.second;
970 log_assert(output_lines.size() == output_bits.size());
971
972 wire_lines.sort();
973 for (auto &it : wire_lines)
974 f << it.second;
975 }
976 };
977
978 struct XAigerBackend : public Backend {
979 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
980 void help() YS_OVERRIDE
981 {
982 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
983 log("\n");
984 log(" write_xaiger [options] [filename]\n");
985 log("\n");
986 log("Write the current design to an XAIGER file. The design must be flattened and\n");
987 log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
988 log("\n");
989 log(" -ascii\n");
990 log(" write ASCII version of AIGER format\n");
991 log("\n");
992 log(" -map <filename>\n");
993 log(" write an extra file with port and box symbols\n");
994 log("\n");
995 log(" -vmap <filename>\n");
996 log(" like -map, but more verbose\n");
997 log("\n");
998 }
999 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
1000 {
1001 bool ascii_mode = false;
1002 bool verbose_map = false;
1003 std::string map_filename;
1004
1005 log_header(design, "Executing XAIGER backend.\n");
1006
1007 size_t argidx;
1008 for (argidx = 1; argidx < args.size(); argidx++)
1009 {
1010 if (args[argidx] == "-ascii") {
1011 ascii_mode = true;
1012 continue;
1013 }
1014 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
1015 map_filename = args[++argidx];
1016 continue;
1017 }
1018 if (map_filename.empty() && args[argidx] == "-vmap" && argidx+1 < args.size()) {
1019 map_filename = args[++argidx];
1020 verbose_map = true;
1021 continue;
1022 }
1023 break;
1024 }
1025 extra_args(f, filename, args, argidx, !ascii_mode);
1026
1027 Module *top_module = design->top_module();
1028
1029 if (top_module == nullptr)
1030 log_error("Can't find top module in current design!\n");
1031
1032 XAigerWriter writer(top_module);
1033 writer.write_aiger(*f, ascii_mode);
1034
1035 if (!map_filename.empty()) {
1036 std::ofstream mapf;
1037 mapf.open(map_filename.c_str(), std::ofstream::trunc);
1038 if (mapf.fail())
1039 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
1040 writer.write_map(mapf, verbose_map);
1041 }
1042 }
1043 } XAigerBackend;
1044
1045 PRIVATE_NAMESPACE_END