xaiger: output $_DFF_[NP]_ with mergeability if -dff option
[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 #include "kernel/timinginfo.h"
51
52 USING_YOSYS_NAMESPACE
53 PRIVATE_NAMESPACE_BEGIN
54
55 inline int32_t to_big_endian(int32_t i32) {
56 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
57 return bswap32(i32);
58 #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
59 return i32;
60 #else
61 #error "Unknown endianness"
62 #endif
63 }
64
65 void aiger_encode(std::ostream &f, int x)
66 {
67 log_assert(x >= 0);
68
69 while (x & ~0x7f) {
70 f.put((x & 0x7f) | 0x80);
71 x = x >> 7;
72 }
73
74 f.put(x);
75 }
76
77 struct XAigerWriter
78 {
79 Module *module;
80 SigMap sigmap;
81
82 pool<SigBit> input_bits, output_bits;
83 dict<SigBit, SigBit> not_map, alias_map;
84 dict<SigBit, pair<SigBit, SigBit>> and_map;
85 vector<SigBit> ci_bits, co_bits;
86 dict<SigBit, Cell*> ff_bits;
87 dict<SigBit, float> arrival_times;
88
89 vector<pair<int, int>> aig_gates;
90 vector<int> aig_outputs;
91 int aig_m = 0, aig_i = 0, aig_l = 0, aig_o = 0, aig_a = 0;
92
93 dict<SigBit, int> aig_map;
94 dict<SigBit, int> ordered_outputs;
95
96 vector<Cell*> box_list;
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 dff_mode, 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 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 output_bits.insert(wirebit);
170 }
171 continue;
172 }
173
174 undriven_bits.insert(bit);
175 unused_bits.insert(bit);
176
177 bool scc = wire->attributes.count(ID::abc9_scc);
178 if (wire->port_input || scc)
179 input_bits.insert(bit);
180
181 bool keep = wire->get_bool_attribute(ID::keep);
182 if (wire->port_output || keep || scc) {
183 if (bit != wirebit)
184 alias_map[wirebit] = bit;
185 output_bits.insert(wirebit);
186 }
187 }
188
189 TimingInfo timing;
190
191 for (auto cell : module->cells()) {
192 if (!cell->has_keep_attr()) {
193 if (cell->type == ID($_NOT_))
194 {
195 SigBit A = sigmap(cell->getPort(ID::A).as_bit());
196 SigBit Y = sigmap(cell->getPort(ID::Y).as_bit());
197 unused_bits.erase(A);
198 undriven_bits.erase(Y);
199 not_map[Y] = A;
200 continue;
201 }
202
203 if (cell->type == ID($_AND_))
204 {
205 SigBit A = sigmap(cell->getPort(ID::A).as_bit());
206 SigBit B = sigmap(cell->getPort(ID::B).as_bit());
207 SigBit Y = sigmap(cell->getPort(ID::Y).as_bit());
208 unused_bits.erase(A);
209 unused_bits.erase(B);
210 undriven_bits.erase(Y);
211 and_map[Y] = make_pair(A, B);
212 continue;
213 }
214
215 if (dff_mode && cell->type.in(ID($_DFF_N_), ID($_DFF_P_)))
216 {
217 SigBit D = sigmap(cell->getPort(ID::D).as_bit());
218 SigBit Q = sigmap(cell->getPort(ID::Q).as_bit());
219 unused_bits.erase(D);
220 undriven_bits.erase(Q);
221 alias_map[Q] = D;
222 auto r YS_ATTRIBUTE(unused) = ff_bits.insert(std::make_pair(D, cell));
223 log_assert(r.second);
224 continue;
225 }
226
227 if (cell->type.in(ID($specify2), ID($specify3), ID($specrule)))
228 continue;
229 }
230
231 RTLIL::Module* inst_module = module->design->module(cell->type);
232 if (inst_module) {
233 IdString derived_type;
234 if (cell->parameters.empty())
235 derived_type = cell->type;
236 else
237 derived_type = inst_module->derive(module->design, cell->parameters);
238 inst_module = module->design->module(derived_type);
239 log_assert(inst_module);
240
241 bool abc9_flop = false;
242 if (!cell->has_keep_attr()) {
243 auto it = cell->attributes.find(ID::abc9_box_seq);
244 if (it != cell->attributes.end()) {
245 int abc9_box_seq = it->second.as_int();
246 if (GetSize(box_list) <= abc9_box_seq)
247 box_list.resize(abc9_box_seq+1);
248 box_list[abc9_box_seq] = cell;
249 // Only flop boxes may have arrival times
250 // (all others are combinatorial)
251 abc9_flop = inst_module->get_bool_attribute(ID::abc9_flop);
252 if (!abc9_flop)
253 continue;
254 }
255 }
256
257 if (!timing.count(derived_type))
258 timing.setup_module(inst_module);
259 auto &t = timing.at(derived_type).arrival;
260 for (const auto &conn : cell->connections()) {
261 auto port_wire = inst_module->wire(conn.first);
262 if (!port_wire->port_output)
263 continue;
264
265 for (int i = 0; i < GetSize(conn.second); i++) {
266 auto d = t.at(TimingInfo::NameBit(conn.first,i), 0);
267 if (d == 0)
268 continue;
269
270 #ifndef NDEBUG
271 if (ys_debug(1)) {
272 static std::set<std::tuple<IdString,IdString,int>> seen;
273 if (seen.emplace(derived_type, conn.first, i).second) log("%s.%s[%d] abc9_arrival = %d\n",
274 log_id(cell->type), log_id(conn.first), i, d);
275 }
276 #endif
277 arrival_times[conn.second[i]] = d;
278 }
279 }
280
281 if (abc9_flop)
282 continue;
283 }
284 else {
285 if (cell->type == ID($__ABC9_DELAY))
286 log_error("Cell type '%s' not recognised. Check that '+/abc9_model.v' has been read.\n", cell->type.c_str());
287 }
288
289 bool cell_known = inst_module || cell->known();
290 for (const auto &c : cell->connections()) {
291 if (c.second.is_fully_const()) continue;
292 auto port_wire = inst_module ? inst_module->wire(c.first) : nullptr;
293 auto is_input = (port_wire && port_wire->port_input) || !cell_known || cell->input(c.first);
294 auto is_output = (port_wire && port_wire->port_output) || !cell_known || cell->output(c.first);
295 if (!is_input && !is_output)
296 log_error("Connection '%s' on cell '%s' (type '%s') not recognised!\n", log_id(c.first), log_id(cell), log_id(cell->type));
297
298 if (is_input)
299 for (auto b : c.second) {
300 Wire *w = b.wire;
301 if (!w) continue;
302 // Do not add as PO if bit is already a PI
303 if (input_bits.count(b))
304 continue;
305 if (!w->port_output || !cell_known) {
306 SigBit I = sigmap(b);
307 if (I != b)
308 alias_map[b] = I;
309 output_bits.insert(b);
310 }
311 }
312 }
313
314 //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
315 }
316
317 dict<IdString, std::vector<IdString>> box_ports;
318 for (auto cell : box_list) {
319 log_assert(cell);
320
321 RTLIL::Module* box_module = module->design->module(cell->type);
322 log_assert(box_module);
323 log_assert(box_module->attributes.count(ID::abc9_box_id));
324
325 auto r = box_ports.insert(cell->type);
326 if (r.second) {
327 // Make carry in the last PI, and carry out the last PO
328 // since ABC requires it this way
329 IdString carry_in, carry_out;
330 for (const auto &port_name : box_module->ports) {
331 auto w = box_module->wire(port_name);
332 log_assert(w);
333 if (w->get_bool_attribute(ID::abc9_carry)) {
334 if (w->port_input) {
335 if (carry_in != IdString())
336 log_error("Module '%s' contains more than one 'abc9_carry' input port.\n", log_id(box_module));
337 carry_in = port_name;
338 }
339 if (w->port_output) {
340 if (carry_out != IdString())
341 log_error("Module '%s' contains more than one 'abc9_carry' output port.\n", log_id(box_module));
342 carry_out = port_name;
343 }
344 }
345 else
346 r.first->second.push_back(port_name);
347 }
348
349 if (carry_in != IdString() && carry_out == IdString())
350 log_error("Module '%s' contains an 'abc9_carry' input port but no output port.\n", log_id(box_module));
351 if (carry_in == IdString() && carry_out != IdString())
352 log_error("Module '%s' contains an 'abc9_carry' output port but no input port.\n", log_id(box_module));
353 if (carry_in != IdString()) {
354 r.first->second.push_back(carry_in);
355 r.first->second.push_back(carry_out);
356 }
357 }
358
359 for (auto port_name : r.first->second) {
360 auto w = box_module->wire(port_name);
361 log_assert(w);
362 auto rhs = cell->connections_.at(port_name, SigSpec());
363 rhs.append(Const(State::Sx, GetSize(w)-GetSize(rhs)));
364 if (w->port_input)
365 for (auto b : rhs) {
366 SigBit I = sigmap(b);
367 if (b == RTLIL::Sx)
368 b = State::S0;
369 else if (I != b) {
370 if (I == RTLIL::Sx)
371 alias_map[b] = State::S0;
372 else
373 alias_map[b] = I;
374 }
375 co_bits.emplace_back(b);
376 unused_bits.erase(I);
377 }
378 if (w->port_output)
379 for (const auto &b : rhs) {
380 SigBit O = sigmap(b);
381 if (O != b)
382 alias_map[O] = b;
383 ci_bits.emplace_back(b);
384 undriven_bits.erase(O);
385 }
386 }
387 }
388
389 for (auto bit : input_bits)
390 undriven_bits.erase(bit);
391 for (auto bit : output_bits)
392 unused_bits.erase(sigmap(bit));
393 for (auto bit : unused_bits)
394 undriven_bits.erase(bit);
395
396 // Make all undriven bits a primary input
397 for (auto bit : undriven_bits) {
398 input_bits.insert(bit);
399 undriven_bits.erase(bit);
400 }
401
402 if (holes_mode) {
403 struct sort_by_port_id {
404 bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
405 return a.wire->port_id < b.wire->port_id ||
406 (a.wire->port_id == b.wire->port_id && a.offset < b.offset);
407 }
408 };
409 input_bits.sort(sort_by_port_id());
410 output_bits.sort(sort_by_port_id());
411 }
412
413 aig_map[State::S0] = 0;
414 aig_map[State::S1] = 1;
415
416 for (const auto &bit : input_bits) {
417 aig_m++, aig_i++;
418 log_assert(!aig_map.count(bit));
419 aig_map[bit] = 2*aig_m;
420 }
421
422 for (const auto &i : ff_bits) {
423 const Cell *cell = i.second;
424 const SigBit &q = sigmap(cell->getPort(ID::Q));
425 aig_m++, aig_i++;
426 log_assert(!aig_map.count(q));
427 aig_map[q] = 2*aig_m;
428 }
429
430 for (auto &bit : ci_bits) {
431 aig_m++, aig_i++;
432 // 1'bx may exist here due to a box output
433 // that has been padded to its full width
434 if (bit == State::Sx)
435 continue;
436 log_assert(!aig_map.count(bit));
437 aig_map[bit] = 2*aig_m;
438 }
439
440 for (auto bit : co_bits) {
441 ordered_outputs[bit] = aig_o++;
442 aig_outputs.push_back(bit2aig(bit));
443 }
444
445 for (const auto &bit : output_bits) {
446 ordered_outputs[bit] = aig_o++;
447 int aig;
448 // Unlike bit2aig() which checks aig_map first for
449 // inout/scc bits, since aig_map will point to
450 // the PI, first attempt to find the NOT/AND driver
451 // before resorting to an aig_map lookup (which
452 // could be another PO)
453 if (input_bits.count(bit)) {
454 if (not_map.count(bit)) {
455 aig = bit2aig(not_map.at(bit)) ^ 1;
456 } else if (and_map.count(bit)) {
457 auto args = and_map.at(bit);
458 int a0 = bit2aig(args.first);
459 int a1 = bit2aig(args.second);
460 aig = mkgate(a0, a1);
461 }
462 else
463 aig = aig_map.at(bit);
464 }
465 else
466 aig = bit2aig(bit);
467 aig_outputs.push_back(aig);
468 }
469
470 for (auto &i : ff_bits) {
471 const SigBit &d = i.first;
472 aig_o++;
473 aig_outputs.push_back(aig_map.at(d));
474 }
475 }
476
477 void write_aiger(std::ostream &f, bool ascii_mode)
478 {
479 int aig_obc = aig_o;
480 int aig_obcj = aig_obc;
481 int aig_obcjf = aig_obcj;
482
483 log_assert(aig_m == aig_i + aig_l + aig_a);
484 log_assert(aig_obcjf == GetSize(aig_outputs));
485
486 f << stringf("%s %d %d %d %d %d", ascii_mode ? "aag" : "aig", aig_m, aig_i, aig_l, aig_o, aig_a);
487 f << stringf("\n");
488
489 if (ascii_mode)
490 {
491 for (int i = 0; i < aig_i; i++)
492 f << stringf("%d\n", 2*i+2);
493
494 for (int i = 0; i < aig_obc; i++)
495 f << stringf("%d\n", aig_outputs.at(i));
496
497 for (int i = aig_obc; i < aig_obcj; i++)
498 f << stringf("1\n");
499
500 for (int i = aig_obc; i < aig_obcj; i++)
501 f << stringf("%d\n", aig_outputs.at(i));
502
503 for (int i = aig_obcj; i < aig_obcjf; i++)
504 f << stringf("%d\n", aig_outputs.at(i));
505
506 for (int i = 0; i < aig_a; i++)
507 f << stringf("%d %d %d\n", 2*(aig_i+aig_l+i)+2, aig_gates.at(i).first, aig_gates.at(i).second);
508 }
509 else
510 {
511 for (int i = 0; i < aig_obc; i++)
512 f << stringf("%d\n", aig_outputs.at(i));
513
514 for (int i = aig_obc; i < aig_obcj; i++)
515 f << stringf("1\n");
516
517 for (int i = aig_obc; i < aig_obcj; i++)
518 f << stringf("%d\n", aig_outputs.at(i));
519
520 for (int i = aig_obcj; i < aig_obcjf; i++)
521 f << stringf("%d\n", aig_outputs.at(i));
522
523 for (int i = 0; i < aig_a; i++) {
524 int lhs = 2*(aig_i+aig_l+i)+2;
525 int rhs0 = aig_gates.at(i).first;
526 int rhs1 = aig_gates.at(i).second;
527 int delta0 = lhs - rhs0;
528 int delta1 = rhs0 - rhs1;
529 aiger_encode(f, delta0);
530 aiger_encode(f, delta1);
531 }
532 }
533
534 f << "c";
535
536 auto write_buffer = [](std::stringstream &buffer, int i32) {
537 int32_t i32_be = to_big_endian(i32);
538 buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
539 };
540 std::stringstream h_buffer;
541 auto write_h_buffer = std::bind(write_buffer, std::ref(h_buffer), std::placeholders::_1);
542 write_h_buffer(1);
543 log_debug("ciNum = %d\n", GetSize(input_bits) + GetSize(ff_bits) + GetSize(ci_bits));
544 write_h_buffer(input_bits.size() + ff_bits.size() + ci_bits.size());
545 log_debug("coNum = %d\n", GetSize(output_bits) + GetSize(ff_bits) + GetSize(co_bits));
546 write_h_buffer(output_bits.size() + GetSize(ff_bits) + GetSize(co_bits));
547 log_debug("piNum = %d\n", GetSize(input_bits) + GetSize(ff_bits));
548 write_h_buffer(input_bits.size() + ff_bits.size());
549 log_debug("poNum = %d\n", GetSize(output_bits) + GetSize(ff_bits));
550 write_h_buffer(output_bits.size() + ff_bits.size());
551 log_debug("boxNum = %d\n", GetSize(box_list));
552 write_h_buffer(box_list.size());
553
554 auto write_buffer_float = [](std::stringstream &buffer, float f32) {
555 buffer.write(reinterpret_cast<const char*>(&f32), sizeof(f32));
556 };
557 std::stringstream i_buffer;
558 auto write_i_buffer = std::bind(write_buffer_float, std::ref(i_buffer), std::placeholders::_1);
559 for (auto bit : input_bits)
560 write_i_buffer(arrival_times.at(bit, 0));
561 //std::stringstream o_buffer;
562 //auto write_o_buffer = std::bind(write_buffer_float, std::ref(o_buffer), std::placeholders::_1);
563 //for (auto bit : output_bits)
564 // write_o_buffer(0);
565
566 if (!box_list.empty() || !ff_bits.empty()) {
567 dict<IdString, std::tuple<int,int,int>> cell_cache;
568
569 int box_count = 0;
570 for (auto cell : box_list) {
571 log_assert(cell);
572
573 RTLIL::Module* box_module = module->design->module(cell->type);
574 log_assert(box_module);
575
576 IdString derived_type;
577 if (cell->parameters.empty())
578 derived_type = cell->type;
579 else
580 derived_type = box_module->derive(module->design, cell->parameters);
581 box_module = box_module->design->module(derived_type);
582 log_assert(box_module);
583
584 auto r = cell_cache.insert(derived_type);
585 auto &v = r.first->second;
586 if (r.second) {
587 int box_inputs = 0, box_outputs = 0;
588 for (auto port_name : box_module->ports) {
589 RTLIL::Wire *w = box_module->wire(port_name);
590 log_assert(w);
591 if (w->port_input)
592 box_inputs += GetSize(w);
593 if (w->port_output)
594 box_outputs += GetSize(w);
595 }
596
597 std::get<0>(v) = box_inputs;
598 std::get<1>(v) = box_outputs;
599 std::get<2>(v) = box_module->attributes.at(ID::abc9_box_id).as_int();
600 }
601
602 write_h_buffer(std::get<0>(v));
603 write_h_buffer(std::get<1>(v));
604 write_h_buffer(std::get<2>(v));
605 write_h_buffer(box_count++);
606 }
607
608 std::stringstream r_buffer;
609 auto write_r_buffer = std::bind(write_buffer, std::ref(r_buffer), std::placeholders::_1);
610 log_debug("flopNum = %d\n", GetSize(ff_bits));
611 write_r_buffer(ff_bits.size());
612
613 std::stringstream s_buffer;
614 auto write_s_buffer = std::bind(write_buffer, std::ref(s_buffer), std::placeholders::_1);
615 write_s_buffer(ff_bits.size());
616
617 dict<SigBit, int> clk_to_mergeability;
618
619 bool nonzero_warned = false;
620 for (const auto &i : ff_bits) {
621 const SigBit &d = i.first;
622 const Cell *cell = i.second;
623
624 log_assert(cell->type.in(ID($_DFF_N_), ID($_DFF_P_)));
625
626 SigBit clock = sigmap(cell->getPort(ID::C));
627 auto r = clk_to_mergeability.insert(std::make_pair(clock, clk_to_mergeability.size() + 1));
628 int mergeability = r.first->second;
629 log_assert(mergeability > 0);
630 if (cell->type == ID($_DFF_N_))
631 write_r_buffer(-mergeability);
632 else if (cell->type == ID($_DFF_P_))
633 write_r_buffer(mergeability);
634 else log_abort();
635
636 Const init = cell->attributes.at(ID::abc9_init, State::Sx);
637 log_assert(GetSize(init) == 1);
638 if (init == State::S1) {
639 if (!nonzero_warned) {
640 log_warning("Module '%s' contains $_DFF_[NP]_ cell with non-zero initial state -- unsupported by ABC9.\n", log_id(module));
641 nonzero_warned = true;
642 }
643 write_s_buffer(1);
644 }
645 else if (init == State::S0)
646 write_s_buffer(0);
647 else {
648 log_assert(init == State::Sx);
649 write_s_buffer(0);
650 }
651
652 // Use arrival time from output of flop box
653 write_i_buffer(arrival_times.at(d, 0));
654 //write_o_buffer(0);
655 }
656
657 f << "r";
658 std::string buffer_str = r_buffer.str();
659 int32_t buffer_size_be = to_big_endian(buffer_str.size());
660 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
661 f.write(buffer_str.data(), buffer_str.size());
662
663 f << "s";
664 buffer_str = s_buffer.str();
665 buffer_size_be = to_big_endian(buffer_str.size());
666 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
667 f.write(buffer_str.data(), buffer_str.size());
668
669 RTLIL::Module *holes_module = module->design->module(stringf("%s$holes", module->name.c_str()));
670 if (holes_module) {
671 std::stringstream a_buffer;
672 XAigerWriter writer(holes_module, false /* dff_mode */, true /* holes_mode */);
673 writer.write_aiger(a_buffer, false /*ascii_mode*/);
674
675 f << "a";
676 std::string buffer_str = a_buffer.str();
677 int32_t buffer_size_be = to_big_endian(buffer_str.size());
678 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
679 f.write(buffer_str.data(), buffer_str.size());
680 }
681 }
682
683 f << "h";
684 std::string buffer_str = h_buffer.str();
685 int32_t buffer_size_be = to_big_endian(buffer_str.size());
686 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
687 f.write(buffer_str.data(), buffer_str.size());
688
689 f << "i";
690 buffer_str = i_buffer.str();
691 buffer_size_be = to_big_endian(buffer_str.size());
692 f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
693 f.write(buffer_str.data(), buffer_str.size());
694 //f << "o";
695 //buffer_str = o_buffer.str();
696 //buffer_size_be = to_big_endian(buffer_str.size());
697 //f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
698 //f.write(buffer_str.data(), buffer_str.size());
699
700 f << stringf("Generated by %s\n", yosys_version_str);
701
702 module->design->scratchpad_set_int("write_xaiger.num_ands", and_map.size());
703 module->design->scratchpad_set_int("write_xaiger.num_wires", aig_map.size());
704 module->design->scratchpad_set_int("write_xaiger.num_inputs", input_bits.size());
705 module->design->scratchpad_set_int("write_xaiger.num_outputs", output_bits.size());
706 }
707
708 void write_map(std::ostream &f)
709 {
710 dict<int, string> input_lines;
711 dict<int, string> output_lines;
712
713 for (auto wire : module->wires())
714 {
715 SigSpec sig = sigmap(wire);
716
717 for (int i = 0; i < GetSize(wire); i++)
718 {
719 RTLIL::SigBit b(wire, i);
720 if (input_bits.count(b)) {
721 int a = aig_map.at(b);
722 log_assert((a & 1) == 0);
723 input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, wire->start_offset+i, log_id(wire));
724 }
725
726 if (output_bits.count(b)) {
727 int o = ordered_outputs.at(b);
728 output_lines[o] += stringf("output %d %d %s\n", o - GetSize(co_bits), wire->start_offset+i, log_id(wire));
729 continue;
730 }
731 }
732 }
733
734 input_lines.sort();
735 for (auto &it : input_lines)
736 f << it.second;
737 log_assert(input_lines.size() == input_bits.size());
738
739 int box_count = 0;
740 for (auto cell : box_list)
741 f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
742
743 output_lines.sort();
744 for (auto &it : output_lines)
745 f << it.second;
746 log_assert(output_lines.size() == output_bits.size());
747 }
748 };
749
750 struct XAigerBackend : public Backend {
751 XAigerBackend() : Backend("xaiger", "write design to XAIGER file") { }
752 void help() YS_OVERRIDE
753 {
754 // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
755 log("\n");
756 log(" write_xaiger [options] [filename]\n");
757 log("\n");
758 log("Write the top module (according to the (* top *) attribute or if only one module\n");
759 log("is currently selected) to an XAIGER file. Any non $_NOT_, $_AND_, $_DFF_N_,\n");
760 log(" $_DFF_P_, or non (* abc9_box_id *) cells will be converted into psuedo-inputs and\n");
761 log("pseudo-outputs. Whitebox contents will be taken from the '<module-name>$holes'\n");
762 log("module, if it exists.\n");
763 log("\n");
764 log(" -ascii\n");
765 log(" write ASCII version of AIGER format\n");
766 log("\n");
767 log(" -map <filename>\n");
768 log(" write an extra file with port and box symbols\n");
769 log("\n");
770 log(" -dff\n");
771 log(" write $_DFF_[NP]_ cells\n");
772 log("\n");
773 }
774 void execute(std::ostream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
775 {
776 bool ascii_mode = false, dff_mode = false;
777 std::string map_filename;
778
779 log_header(design, "Executing XAIGER backend.\n");
780
781 size_t argidx;
782 for (argidx = 1; argidx < args.size(); argidx++)
783 {
784 if (args[argidx] == "-ascii") {
785 ascii_mode = true;
786 continue;
787 }
788 if (map_filename.empty() && args[argidx] == "-map" && argidx+1 < args.size()) {
789 map_filename = args[++argidx];
790 continue;
791 }
792 if (args[argidx] == "-dff") {
793 dff_mode = true;
794 continue;
795 }
796 break;
797 }
798 extra_args(f, filename, args, argidx, !ascii_mode);
799
800 Module *top_module = design->top_module();
801
802 if (top_module == nullptr)
803 log_error("Can't find top module in current design!\n");
804
805 if (!design->selected_whole_module(top_module))
806 log_cmd_error("Can't handle partially selected module %s!\n", log_id(top_module));
807
808 if (!top_module->processes.empty())
809 log_error("Found unmapped processes in module %s: unmapped processes are not supported in XAIGER backend!\n", log_id(top_module));
810 if (!top_module->memories.empty())
811 log_error("Found unmapped memories in module %s: unmapped memories are not supported in XAIGER backend!\n", log_id(top_module));
812
813 XAigerWriter writer(top_module, dff_mode);
814 writer.write_aiger(*f, ascii_mode);
815
816 if (!map_filename.empty()) {
817 std::ofstream mapf;
818 mapf.open(map_filename.c_str(), std::ofstream::trunc);
819 if (mapf.fail())
820 log_error("Can't open file `%s' for writing: %s\n", map_filename.c_str(), strerror(errno));
821 writer.write_map(mapf);
822 }
823 }
824 } XAigerBackend;
825
826 PRIVATE_NAMESPACE_END