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