Fix for abc9_test022
[yosys.git] / backends / aiger / xaiger.cc
index db0395d280dda18b8fcf53abfa6c5f62ec316862..2ffd460dd8c8949ecab95e93c1f3621beabbd845 100644 (file)
@@ -20,6 +20,8 @@
 
 #include "kernel/yosys.h"
 #include "kernel/sigtools.h"
+#include "kernel/celltypes.h"
+#include "kernel/utils.h"
 
 USING_YOSYS_NAMESPACE
 PRIVATE_NAMESPACE_BEGIN
@@ -46,9 +48,9 @@ struct XAigerWriter
        pool<SigBit> input_bits, output_bits;
        dict<SigBit, SigBit> not_map, ff_map, alias_map;
        dict<SigBit, pair<SigBit, SigBit>> and_map;
-       pool<SigBit> initstate_bits;
-       pool<SigBit> ci_bits, co_bits;
-       dict<IdString, unsigned> type_map;
+       //pool<SigBit> initstate_bits;
+       vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int>> ci_bits;
+       vector<std::tuple<SigBit,RTLIL::Cell*,RTLIL::IdString,int,int>> co_bits;
 
        vector<pair<int, int>> aig_gates;
        vector<int> aig_latchin, aig_latchinit, aig_outputs;
@@ -58,8 +60,10 @@ struct XAigerWriter
        dict<SigBit, int> ordered_outputs;
        dict<SigBit, int> ordered_latches;
 
-       dict<SigBit, int> init_inputs;
-       int initstate_ff = 0;
+       vector<Cell*> box_list;
+
+       //dict<SigBit, int> init_inputs;
+       //int initstate_ff = 0;
 
        int mkgate(int a0, int a1)
        {
@@ -74,10 +78,10 @@ struct XAigerWriter
                {
                        aig_map[bit] = -1;
 
-                       if (initstate_bits.count(bit)) {
-                               log_assert(initstate_ff > 0);
-                               aig_map[bit] = initstate_ff;
-                       } else
+                       //if (initstate_bits.count(bit)) {
+                       //      log_assert(initstate_ff > 0);
+                       //      aig_map[bit] = initstate_ff;
+                       //} else
                        if (not_map.count(bit)) {
                                int a = bit2aig(not_map.at(bit)) ^ 1;
                                aig_map[bit] = a;
@@ -100,7 +104,7 @@ struct XAigerWriter
                return aig_map.at(bit);
        }
 
-       XAigerWriter(Module *module, bool zinit_mode, bool imode, bool omode, bool bmode) : module(module), zinit_mode(zinit_mode), sigmap(module)
+       XAigerWriter(Module *module, bool zinit_mode, bool imode, bool omode, bool bmode, bool holes_mode=false) : module(module), zinit_mode(zinit_mode), sigmap(module)
        {
                pool<SigBit> undriven_bits;
                pool<SigBit> unused_bits;
@@ -130,6 +134,8 @@ struct XAigerWriter
                                                init_map[initsig[i]] = initval[i] == State::S1;
                        }
 
+                       bool keep = wire->attributes.count("\\keep");
+
                        for (int i = 0; i < GetSize(wire); i++)
                        {
                                SigBit wirebit(wire, i);
@@ -148,8 +154,10 @@ struct XAigerWriter
 
                                if (wire->port_input)
                                        input_bits.insert(bit);
+                               else if (keep)
+                                       input_bits.insert(wirebit);
 
-                               if (wire->port_output) {
+                               if (wire->port_output || keep) {
                                        if (bit != wirebit)
                                                alias_map[wirebit] = bit;
                                        output_bits.insert(wirebit);
@@ -157,17 +165,56 @@ struct XAigerWriter
                        }
                }
 
-               for (auto bit : input_bits) {
+               for (auto bit : input_bits)
                        undriven_bits.erase(bit);
-                       // Erase POs that are also PIs
-                       output_bits.erase(bit);
-               }
 
                for (auto bit : output_bits)
-                       unused_bits.erase(bit);
+                       if (!bit.wire->port_input)
+                               unused_bits.erase(bit);
+
+               dict<SigBit, pool<IdString>> bit_drivers, bit_users;
+               TopoSort<IdString, RTLIL::sort_by_id_str> toposort;
+               bool abc_box_seen = false;
 
                for (auto cell : module->cells())
                {
+                       RTLIL::Module* inst_module = module->design->module(cell->type);
+                       bool known_type = yosys_celltypes.cell_known(cell->type);
+
+                       if (!holes_mode) {
+                               toposort.node(cell->name);
+                               for (const auto &conn : cell->connections())
+                               {
+                                       if (!cell->type.in("$_NOT_", "$_AND_")) {
+                                               if (known_type) {
+                                                       if (conn.first.in("\\Q", "\\CTRL_OUT", "\\RD_DATA"))
+                                                               continue;
+                                                       if (cell->type == "$memrd" && conn.first == "\\DATA")
+                                                               continue;
+                                               }
+
+                                               if (inst_module) {
+                                                       RTLIL::Wire* inst_module_port = inst_module->wire(conn.first);
+                                                       log_assert(inst_module_port);
+
+                                                       if (inst_module_port->attributes.count("\\abc_flop_q"))
+                                                               continue;
+                                               }
+                                       }
+
+                                       if (cell->input(conn.first)) {
+                                               // Ignore inout for the sake of topographical ordering
+                                               if (cell->output(conn.first)) continue;
+                                               for (auto bit : sigmap(conn.second))
+                                                       bit_users[bit].insert(cell->name);
+                                       }
+
+                                       if (cell->output(conn.first))
+                                               for (auto bit : sigmap(conn.second))
+                                                       bit_drivers[bit].insert(cell->name);
+                               }
+                       }
+
                        if (cell->type == "$_NOT_")
                        {
                                SigBit A = sigmap(cell->getPort("\\A").as_bit());
@@ -200,58 +247,156 @@ struct XAigerWriter
                                continue;
                        }
 
-                       if (cell->type == "$initstate")
-                       {
-                               SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
-                               undriven_bits.erase(Y);
-                               initstate_bits.insert(Y);
-                               continue;
+                       //if (cell->type == "$initstate")
+                       //{
+                       //      SigBit Y = sigmap(cell->getPort("\\Y").as_bit());
+                       //      undriven_bits.erase(Y);
+                       //      initstate_bits.insert(Y);
+                       //      continue;
+                       //}
+
+                       if (inst_module && inst_module->attributes.count("\\abc_box_id")) {
+                               abc_box_seen = true;
+                       }
+                       else {
+                               for (const auto &c : cell->connections()) {
+                                       if (c.second.is_fully_const()) continue;
+                                       for (auto b : c.second.bits()) {
+                                               Wire *w = b.wire;
+                                               if (!w) continue;
+                                               auto is_input = cell->input(c.first);
+                                               auto is_output = cell->output(c.first);
+                                               log_assert(is_input || is_output);
+                                               if (is_input) {
+                                                       if (!w->port_input) {
+                                                               SigBit I = sigmap(b);
+                                                               if (I != b)
+                                                                       alias_map[b] = I;
+                                                               output_bits.insert(b);
+                                                               unused_bits.erase(b);
+                                                       }
+                                               }
+                                               if (is_output) {
+                                                       input_bits.insert(b);
+                                                       SigBit O = sigmap(b);
+                                                       if (O != b)
+                                                               alias_map[O] = b;
+                                                       undriven_bits.erase(O);
+                                               }
+                                       }
+                               }
                        }
 
-                       for (const auto &c : cell->connections()) {
-                               if (c.second.is_fully_const()) continue;
-                               for (auto b : c.second.bits()) {
-                                       Wire *w = b.wire;
-                                       if (!w) continue;
-                                       if (cell->input(c.first)) {
-                                               if (!w->port_input) {
+                       //log_warning("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
+               }
+
+               if (abc_box_seen) {
+                       for (auto &it : bit_users)
+                               if (bit_drivers.count(it.first))
+                                       for (auto driver_cell : bit_drivers.at(it.first))
+                                       for (auto user_cell : it.second)
+                                               toposort.edge(driver_cell, user_cell);
+
+                       toposort.sort();
+                       for (auto cell_name : toposort.sorted) {
+                               RTLIL::Cell *cell = module->cell(cell_name);
+                               RTLIL::Module* box_module = module->design->module(cell->type);
+                               if (!box_module || !box_module->attributes.count("\\abc_box_id"))
+                                       continue;
+
+                               // Fully pad all unused input connections of this box cell with S0
+                               // Fully pad all undriven output connections of this box cell with anonymous wires
+                               // NB: Assume box_module->ports are sorted alphabetically
+                               //     (as RTLIL::Module::fixup_ports() would do)
+                               for (const auto &port_name : box_module->ports) {
+                                       RTLIL::Wire* w = box_module->wire(port_name);
+                                       log_assert(w);
+                                       auto it = cell->connections_.find(port_name);
+                                       if (w->port_input) {
+                                               RTLIL::SigSpec rhs;
+                                               if (it != cell->connections_.end()) {
+                                                       if (GetSize(it->second) < GetSize(w))
+                                                               it->second.append(RTLIL::SigSpec(RTLIL::S0, GetSize(w)-GetSize(it->second)));
+                                                       rhs = it->second;
+                                               }
+                                               else {
+                                                       rhs = RTLIL::SigSpec(RTLIL::S0, GetSize(w));
+                                                       cell->setPort(port_name, rhs);
+                                               }
+
+                                               int offset = 0;
+                                               for (const auto &b : rhs.bits()) {
                                                        SigBit I = sigmap(b);
                                                        if (I != b)
                                                                alias_map[b] = I;
-                                                       if (!output_bits.count(b))
-                                                               co_bits.insert(b);
+                                                       co_bits.emplace_back(b, cell, port_name, offset++, 0);
+                                                       unused_bits.erase(b);
                                                }
                                        }
-                                       else if (cell->output(c.first)) {
-                                               SigBit O = sigmap(b);
-                                               if (!input_bits.count(O) && !output_bits.count(O))
-                                                       ci_bits.insert(O);
+                                       if (w->port_output) {
+                                               RTLIL::SigSpec rhs;
+                                               auto it = cell->connections_.find(w->name);
+                                               if (it != cell->connections_.end()) {
+                                                       if (GetSize(it->second) < GetSize(w))
+                                                               it->second.append(module->addWire(NEW_ID, GetSize(w)-GetSize(it->second)));
+                                                       rhs = it->second;
+                                               }
+                                               else {
+                                                       rhs = module->addWire(NEW_ID, GetSize(w));
+                                                       cell->setPort(port_name, rhs);
+                                               }
+
+                                               int offset = 0;
+                                               for (const auto &b : rhs.bits()) {
+                                                       ci_bits.emplace_back(b, cell, port_name, offset++);
+                                                       SigBit O = sigmap(b);
+                                                       if (O != b)
+                                                               alias_map[O] = b;
+                                                       undriven_bits.erase(O);
+                                               }
                                        }
-                                       else log_abort();
                                }
-                               if (!type_map.count(cell->type))
-                                       type_map[cell->type] = type_map.size()+1;
+                               box_list.emplace_back(cell);
                        }
-                       //log_error("Unsupported cell type: %s (%s)\n", log_id(cell->type), log_id(cell));
+
+                       // TODO: Free memory from toposort, bit_drivers, bit_users
                }
 
-               // Do some CI/CO post-processing:
-               // Erase all POs and COs that are undriven
-               for (auto bit : undriven_bits) {
-                       co_bits.erase(bit);
-                       output_bits.erase(bit);
+               for (auto bit : input_bits) {
+                       RTLIL::Wire *wire = bit.wire;
+                       // If encountering an inout port, or a keep-ed wire, then create a new wire
+                       // with $inout.out suffix, make it a PO driven by the existing inout, and
+                       // inherit existing inout's drivers
+                       if ((wire->port_input && wire->port_output && !undriven_bits.count(bit))
+                                       || wire->attributes.count("\\keep")) {
+                               log_assert(input_bits.count(bit) && output_bits.count(bit));
+                               RTLIL::Wire *new_wire = module->wire(wire->name.str() + "$inout.out");
+                               if (!new_wire)
+                                       new_wire = module->addWire(wire->name.str() + "$inout.out", GetSize(wire));
+                               SigBit new_bit(new_wire, bit.offset);
+                               module->connect(new_bit, bit);
+                               if (not_map.count(bit))
+                                       not_map[new_bit] = not_map.at(bit);
+                               else if (and_map.count(bit))
+                                       and_map[new_bit] = and_map.at(bit);
+                               else if (alias_map.count(bit))
+                                       alias_map[new_bit] = alias_map.at(bit);
+                               else
+                                       //log_abort();
+                                       alias_map[new_bit] = bit;
+                               output_bits.erase(bit);
+                               output_bits.insert(new_bit);
+                       }
                }
-               // Erase all CIs that are also COs
-               for (auto bit : co_bits)
-                       ci_bits.erase(bit);
-               // CIs cannot be undriven
-               for (auto bit : ci_bits)
-                       undriven_bits.erase(bit);
 
+               // Erase all POs that are undriven
+               if (!holes_mode)
+                       for (auto bit : undriven_bits)
+                               output_bits.erase(bit);
                for (auto bit : unused_bits)
                        undriven_bits.erase(bit);
 
-               if (!undriven_bits.empty()) {
+               if (!undriven_bits.empty() && !holes_mode) {
                        undriven_bits.sort();
                        for (auto bit : undriven_bits) {
                                log_warning("Treating undriven bit %s.%s like $anyseq.\n", log_id(module), log_signal(bit));
@@ -261,8 +406,20 @@ struct XAigerWriter
                }
 
                init_map.sort();
-               input_bits.sort();
-               output_bits.sort();
+               if (holes_mode) {
+                       struct sort_by_port_id {
+                               bool operator()(const RTLIL::SigBit& a, const RTLIL::SigBit& b) const {
+                                       return a.wire->port_id < b.wire->port_id;
+                               }
+                       };
+                       input_bits.sort(sort_by_port_id());
+                       output_bits.sort(sort_by_port_id());
+               }
+               else {
+                       input_bits.sort();
+                       output_bits.sort();
+               }
+
                not_map.sort();
                ff_map.sort();
                and_map.sort();
@@ -270,29 +427,29 @@ struct XAigerWriter
                aig_map[State::S0] = 0;
                aig_map[State::S1] = 1;
 
-               for (auto bit : ci_bits) {
+               for (auto bit : input_bits) {
                        aig_m++, aig_i++;
                        aig_map[bit] = 2*aig_m;
                }
 
-               for (auto bit : input_bits) {
+               for (auto &c : ci_bits) {
                        aig_m++, aig_i++;
-                       aig_map[bit] = 2*aig_m;
+                       aig_map[std::get<0>(c)] = 2*aig_m;
                }
 
                if (imode && input_bits.empty()) {
                        aig_m++, aig_i++;
                }
 
-               if (zinit_mode)
-               {
-                       for (auto it : ff_map) {
-                               if (init_map.count(it.first))
-                                       continue;
-                               aig_m++, aig_i++;
-                               init_inputs[it.first] = 2*aig_m;
-                       }
-               }
+               //if (zinit_mode)
+               //{
+               //      for (auto it : ff_map) {
+               //              if (init_map.count(it.first))
+               //                      continue;
+               //              aig_m++, aig_i++;
+               //              init_inputs[it.first] = 2*aig_m;
+               //      }
+               //}
 
                for (auto it : ff_map) {
                        aig_m++, aig_l++;
@@ -304,29 +461,29 @@ struct XAigerWriter
                                aig_latchinit.push_back(init_map.at(it.first) ? 1 : 0);
                }
 
-               if (!initstate_bits.empty() || !init_inputs.empty()) {
-                       aig_m++, aig_l++;
-                       initstate_ff = 2*aig_m+1;
-                       aig_latchinit.push_back(0);
-               }
-
-               if (zinit_mode)
-               {
-                       for (auto it : ff_map)
-                       {
-                               int l = ordered_latches[it.first];
-
-                               if (aig_latchinit.at(l) == 1)
-                                       aig_map[it.first] ^= 1;
-
-                               if (aig_latchinit.at(l) == 2)
-                               {
-                                       int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
-                                       int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
-                                       aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
-                               }
-                       }
-               }
+               //if (!initstate_bits.empty() || !init_inputs.empty()) {
+               //      aig_m++, aig_l++;
+               //      initstate_ff = 2*aig_m+1;
+               //      aig_latchinit.push_back(0);
+               //}
+
+               //if (zinit_mode)
+               //{
+               //      for (auto it : ff_map)
+               //      {
+               //              int l = ordered_latches[it.first];
+
+               //              if (aig_latchinit.at(l) == 1)
+               //                      aig_map[it.first] ^= 1;
+
+               //              if (aig_latchinit.at(l) == 2)
+               //              {
+               //                      int gated_ffout = mkgate(aig_map[it.first], initstate_ff^1);
+               //                      int gated_initin = mkgate(init_inputs[it.first], initstate_ff);
+               //                      aig_map[it.first] = mkgate(gated_ffout^1, gated_initin^1)^1;
+               //              }
+               //      }
+               //}
 
                for (auto it : ff_map) {
                        int a = bit2aig(it.second);
@@ -337,22 +494,22 @@ struct XAigerWriter
                                aig_latchin.push_back(a);
                }
 
-               if (!initstate_bits.empty() || !init_inputs.empty())
-                       aig_latchin.push_back(1);
+               //if (!initstate_bits.empty() || !init_inputs.empty())
+               //      aig_latchin.push_back(1);
 
-               for (auto bit : co_bits) {
-                       aig_o++;
-                       ordered_outputs[bit] = aig_o-1;
+               for (auto &c : co_bits) {
+                       RTLIL::SigBit bit = std::get<0>(c);
+                       std::get<4>(c) = aig_o++;
+                       ordered_outputs[bit] = std::get<4>(c);
                        aig_outputs.push_back(bit2aig(bit));
                }
 
                for (auto bit : output_bits) {
-                       aig_o++;
-                       ordered_outputs[bit] = aig_o-1;
+                       ordered_outputs[bit] = aig_o++;
                        aig_outputs.push_back(bit2aig(bit));
                }
 
-               if (omode && output_bits.empty() && co_bits.empty()) {
+               if (omode && output_bits.empty()) {
                        aig_o++;
                        aig_outputs.push_back(0);
                }
@@ -455,7 +612,7 @@ struct XAigerWriter
                                for (int i = 0; i < GetSize(wire); i++)
                                {
                                        RTLIL::SigBit b(wire, i);
-                                       if (input_bits.count(b) || ci_bits.count(b)) {
+                                       if (input_bits.count(b)) {
                                                int a = aig_map.at(sig[i]);
                                                log_assert((a & 1) == 0);
                                                if (GetSize(wire) != 1)
@@ -464,7 +621,7 @@ struct XAigerWriter
                                                        symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("%s", log_id(wire)));
                                        }
 
-                                       if (output_bits.count(b) || co_bits.count(b)) {
+                                       if (output_bits.count(b)) {
                                                int o = ordered_outputs.at(b);
                                                output_seen = !miter_mode;
                                                if (GetSize(wire) != 1)
@@ -473,14 +630,14 @@ struct XAigerWriter
                                                        symbols[stringf("%c%d", miter_mode ? 'b' : 'o', o)].push_back(stringf("%s", log_id(wire)));
                                        }
 
-                                       if (init_inputs.count(sig[i])) {
-                                               int a = init_inputs.at(sig[i]);
-                                               log_assert((a & 1) == 0);
-                                               if (GetSize(wire) != 1)
-                                                       symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
-                                               else
-                                                       symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
-                                       }
+                                       //if (init_inputs.count(sig[i])) {
+                                       //      int a = init_inputs.at(sig[i]);
+                                       //      log_assert((a & 1) == 0);
+                                       //      if (GetSize(wire) != 1)
+                                       //              symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s[%d]", log_id(wire), i));
+                                       //      else
+                                       //              symbols[stringf("i%d", (a >> 1)-1)].push_back(stringf("init:%s", log_id(wire)));
+                                       //}
 
                                        if (ordered_latches.count(sig[i])) {
                                                int l = ordered_latches.at(sig[i]);
@@ -507,7 +664,165 @@ struct XAigerWriter
                        }
                }
 
-               f << stringf("c\nGenerated by %s\n", yosys_version_str);
+               f << "c";
+
+               if (!box_list.empty()) {
+                       std::stringstream h_buffer;
+                       auto write_h_buffer = [&h_buffer](int i32) {
+                               // TODO: Don't assume we're on little endian
+#ifdef _WIN32
+                               int i32_be = _byteswap_ulong(i32);
+#else
+                               int i32_be = __builtin_bswap32(i32);
+#endif
+                               h_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
+                       };
+                       int num_outputs = output_bits.size();
+                       if (omode && num_outputs == 0)
+                               num_outputs = 1;
+                       write_h_buffer(1);
+                       write_h_buffer(input_bits.size() + ci_bits.size());
+                       write_h_buffer(num_outputs + co_bits.size());
+                       write_h_buffer(input_bits.size());
+                       write_h_buffer(num_outputs);
+                       write_h_buffer(box_list.size());
+
+                       RTLIL::Module *holes_module = nullptr;
+                       holes_module = module->design->addModule("\\__holes__");
+                       log_assert(holes_module);
+
+                       int port_id = 1;
+                       int box_count = 0;
+                       for (auto cell : box_list) {
+                               RTLIL::Module* box_module = module->design->module(cell->type);
+                               int box_inputs = 0, box_outputs = 0;
+                               Cell *holes_cell = nullptr;
+                               if (box_module->get_bool_attribute("\\whitebox"))
+                                       holes_cell = holes_module->addCell(cell->name, cell->type);
+
+                               RTLIL::Wire *holes_wire;
+                               // TODO: Only sort once
+                               box_module->wires_.sort(RTLIL::sort_by_id_str());
+                               for (const auto w : box_module->wires()) {
+                                       RTLIL::SigSpec port_wire;
+                                       if (w->port_input) {
+                                               for (int i = 0; i < GetSize(w); i++) {
+                                                       box_inputs++;
+                                                       holes_wire = holes_module->wire(stringf("\\i%d", box_inputs));
+                                                       if (!holes_wire) {
+                                                               holes_wire = holes_module->addWire(stringf("\\i%d", box_inputs));
+                                                               holes_wire->port_input = true;
+                                                               holes_wire->port_id = port_id++;
+                                                               holes_module->ports.push_back(holes_wire->name);
+                                                       }
+                                                       if (holes_cell)
+                                                               port_wire.append(holes_wire);
+                                               }
+                                               if (!port_wire.empty())
+                                                       holes_cell->setPort(w->name, port_wire);
+                                       }
+                                       if (w->port_output) {
+                                               box_outputs += GetSize(w);
+                                               for (int i = 0; i < GetSize(w); i++) {
+                                                       if (GetSize(w) == 1)
+                                                               holes_wire = holes_module->addWire(stringf("%s.%s", cell->name.c_str(), w->name.c_str()));
+                                                       else
+                                                               holes_wire = holes_module->addWire(stringf("%s.%s[%d]", cell->name.c_str(), w->name.c_str(), i));
+                                                       holes_wire->port_output = true;
+                                                       holes_wire->port_id = port_id++;
+                                                       holes_module->ports.push_back(holes_wire->name);
+                                                       if (holes_cell)
+                                                               port_wire.append(holes_wire);
+                                                       else
+                                                               holes_module->connect(holes_wire, RTLIL::S0);
+                                               }
+                                               if (!port_wire.empty())
+                                                       holes_cell->setPort(w->name, port_wire);
+                                       }
+                               }
+
+                               write_h_buffer(box_inputs);
+                               write_h_buffer(box_outputs);
+                               write_h_buffer(box_module->attributes.at("\\abc_box_id").as_int());
+                               write_h_buffer(box_count++);
+                       }
+
+                       f << "h";
+                       std::string buffer_str = h_buffer.str();
+                       // TODO: Don't assume we're on little endian
+#ifdef _WIN32
+                       int buffer_size_be = _byteswap_ulong(buffer_str.size());
+#else
+                       int buffer_size_be = __builtin_bswap32(buffer_str.size());
+#endif
+                       f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
+                       f.write(buffer_str.data(), buffer_str.size());
+
+                       if (holes_module) {
+                               // NB: fixup_ports() will sort ports by name
+                               //holes_module->fixup_ports();
+                               holes_module->check();
+
+                               holes_module->design->selection_stack.emplace_back(false);
+                               RTLIL::Selection& sel = holes_module->design->selection_stack.back();
+                               sel.select(holes_module);
+
+                               // TODO: Should not need to opt_merge if we only instantiate
+                               //       each box type once...
+                               Pass::call(holes_module->design, "opt_merge -share_all");
+
+                               Pass::call(holes_module->design, "flatten -wb");
+
+                               // TODO: Should techmap all lib_whitebox-es once
+                               //Pass::call(holes_module->design, "techmap");
+
+                               Pass::call(holes_module->design, "aigmap");
+                               Pass::call(holes_module->design, "clean -purge");
+
+                               holes_module->design->selection_stack.pop_back();
+
+                               std::stringstream a_buffer;
+                               XAigerWriter writer(holes_module, false /*zinit_mode*/, false /*imode*/, false /*omode*/, false /*bmode*/, true /* holes_mode */);
+                               writer.write_aiger(a_buffer, false /*ascii_mode*/, false /*miter_mode*/, false /*symbols_mode*/, false /*omode*/);
+
+                               f << "a";
+                               std::string buffer_str = a_buffer.str();
+                               // TODO: Don't assume we're on little endian
+#ifdef _WIN32
+                               int buffer_size_be = _byteswap_ulong(buffer_str.size());
+#else
+                               int buffer_size_be = __builtin_bswap32(buffer_str.size());
+#endif
+                               f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
+                               f.write(buffer_str.data(), buffer_str.size());
+                               holes_module->design->remove(holes_module);
+                       }
+
+                       std::stringstream r_buffer;
+                       auto write_r_buffer = [&r_buffer](int i32) {
+                               // TODO: Don't assume we're on little endian
+#ifdef _WIN32
+                               int i32_be = _byteswap_ulong(i32);
+#else
+                               int i32_be = __builtin_bswap32(i32);
+#endif
+                               r_buffer.write(reinterpret_cast<const char*>(&i32_be), sizeof(i32_be));
+                       };
+                       write_r_buffer(0);
+
+                       f << "r";
+                       buffer_str = r_buffer.str();
+                       // TODO: Don't assume we're on little endian
+#ifdef _WIN32
+                       buffer_size_be = _byteswap_ulong(buffer_str.size());
+#else
+                       buffer_size_be = __builtin_bswap32(buffer_str.size());
+#endif
+                       f.write(reinterpret_cast<const char*>(&buffer_size_be), sizeof(buffer_size_be));
+                       f.write(buffer_str.data(), buffer_str.size());
+               }
+
+               f << stringf("Generated by %s\n", yosys_version_str);
        }
 
        void write_map(std::ostream &f, bool verbose_map, bool omode)
@@ -528,25 +843,24 @@ struct XAigerWriter
                        for (int i = 0; i < GetSize(wire); i++)
                        {
                                RTLIL::SigBit b(wire, i);
-                               if (input_bits.count(b) || ci_bits.count(b)) {
-                                       int a = aig_map.at(sig[i]);
+                               if (input_bits.count(b)) {
+                                       int a = aig_map.at(b);
                                        log_assert((a & 1) == 0);
                                        input_lines[a] += stringf("input %d %d %s\n", (a >> 1)-1, i, log_id(wire));
-                                       continue;
                                }
 
-                               if (output_bits.count(b) || co_bits.count(b)) {
+                               if (output_bits.count(b)) {
                                        int o = ordered_outputs.at(b);
-                                       output_lines[o] += stringf("output %d %d %s\n", o, i, log_id(wire));
+                                       output_lines[o] += stringf("output %lu %d %s\n", o - co_bits.size(), i, log_id(wire));
                                        continue;
                                }
 
-                               if (init_inputs.count(sig[i])) {
-                                       int a = init_inputs.at(sig[i]);
-                                       log_assert((a & 1) == 0);
-                                       init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
-                                       continue;
-                               }
+                               //if (init_inputs.count(sig[i])) {
+                               //      int a = init_inputs.at(sig[i]);
+                               //      log_assert((a & 1) == 0);
+                               //      init_lines[a] += stringf("init %d %d %s\n", (a >> 1)-1, i, log_id(wire));
+                               //      continue;
+                               //}
 
                                if (ordered_latches.count(sig[i])) {
                                        int l = ordered_latches.at(sig[i]);
@@ -570,18 +884,22 @@ struct XAigerWriter
                input_lines.sort();
                for (auto &it : input_lines)
                        f << it.second;
-               log_assert(input_lines.size() == input_bits.size() + ci_bits.size());
+               log_assert(input_lines.size() == input_bits.size());
 
                init_lines.sort();
                for (auto &it : init_lines)
                        f << it.second;
 
+               int box_count = 0;
+               for (auto cell : box_list)
+                       f << stringf("box %d %d %s\n", box_count++, 0, log_id(cell->name));
+
                output_lines.sort();
                for (auto &it : output_lines)
                        f << it.second;
-               log_assert(output_lines.size() == output_bits.size() + co_bits.size());
-               if (omode && output_lines.empty())
-                       f << "output 0 0 __dummy_o__\n";
+               log_assert(output_lines.size() == output_bits.size());
+               if (omode && output_bits.empty())
+                       f << "output " << output_lines.size() << " 0 __dummy_o__\n";
 
                latch_lines.sort();
                for (auto &it : latch_lines)
@@ -605,7 +923,7 @@ struct XAigerBackend : public Backend {
                log("all unsupported cells will be converted into psuedo-inputs and pseudo-outputs.\n");
                log("\n");
                log("    -ascii\n");
-               log("        write ASCII version of AGIER format\n");
+               log("        write ASCII version of AIGER format\n");
                log("\n");
                log("    -zinit\n");
                log("        convert FFs to zero-initialized FFs, adding additional inputs for\n");