Renamed extend() to extend_xx(), changed most users to extend_u0()
[yosys.git] / kernel / rtlil.cc
index 7832861823c535833666f6505ac88906e5dc2a93..0e8078df6db12298bc9fc31b98415429f03e41d0 100644 (file)
  *
  */
 
-#include "kernel/compatibility.h"
-#include "kernel/rtlil.h"
-#include "kernel/log.h"
+#include "kernel/yosys.h"
+#include "kernel/macc.h"
 #include "frontends/verilog/verilog_frontend.h"
 #include "backends/ilang/ilang_backend.h"
 
 #include <string.h>
 #include <algorithm>
 
-int RTLIL::autoidx = 1;
+YOSYS_NAMESPACE_BEGIN
+
+RTLIL::IdString::destruct_guard_t RTLIL::IdString::destruct_guard;
+std::vector<int> RTLIL::IdString::global_refcount_storage_;
+std::vector<char*> RTLIL::IdString::global_id_storage_;
+std::map<char*, int, RTLIL::IdString::char_ptr_cmp> RTLIL::IdString::global_id_index_;
+std::vector<int> RTLIL::IdString::global_free_idx_list_;
 
 RTLIL::Const::Const()
 {
@@ -61,6 +66,13 @@ RTLIL::Const::Const(RTLIL::State bit, int width)
                bits.push_back(bit);
 }
 
+RTLIL::Const::Const(const std::vector<bool> &bits)
+{
+       flags = RTLIL::CONST_FLAG_NONE;
+       for (auto b : bits)
+               this->bits.push_back(b ? RTLIL::S1 : RTLIL::S0);
+}
+
 bool RTLIL::Const::operator <(const RTLIL::Const &other) const
 {
        if (bits.size() != other.bits.size())
@@ -89,12 +101,15 @@ bool RTLIL::Const::as_bool() const
        return false;
 }
 
-int RTLIL::Const::as_int() const
+int RTLIL::Const::as_int(bool is_signed) const
 {
-       int ret = 0;
+       int32_t ret = 0;
        for (size_t i = 0; i < bits.size() && i < 32; i++)
                if (bits[i] == RTLIL::S1)
                        ret |= 1 << i;
+       if (is_signed && bits.back() == RTLIL::S1)
+               for (size_t i = bits.size(); i < 32; i++)
+                       ret |= 1 << i;
        return ret;
 }
 
@@ -219,6 +234,12 @@ void RTLIL::Selection::optimize(RTLIL::Design *design)
        }
 }
 
+RTLIL::Design::Design()
+{
+       refcount_modules_ = 0;
+       selection_stack.push_back(RTLIL::Selection());
+}
+
 RTLIL::Design::~Design()
 {
        for (auto it = modules_.begin(); it != modules_.end(); it++)
@@ -240,19 +261,94 @@ void RTLIL::Design::add(RTLIL::Module *module)
        log_assert(modules_.count(module->name) == 0);
        log_assert(refcount_modules_ == 0);
        modules_[module->name] = module;
+       module->design = this;
+
+       for (auto mon : monitors)
+               mon->notify_module_add(module);
 }
 
 RTLIL::Module *RTLIL::Design::addModule(RTLIL::IdString name)
 {
        log_assert(modules_.count(name) == 0);
        log_assert(refcount_modules_ == 0);
-       modules_[name] = new RTLIL::Module;
-       modules_[name]->name = name;
-       return modules_[name];
+
+       RTLIL::Module *module = new RTLIL::Module;
+       modules_[name] = module;
+       module->design = this;
+       module->name = name;
+
+       for (auto mon : monitors)
+               mon->notify_module_add(module);
+
+       return module;
+}
+
+void RTLIL::Design::scratchpad_unset(std::string varname)
+{
+       scratchpad.erase(varname);
+}
+
+void RTLIL::Design::scratchpad_set_int(std::string varname, int value)
+{
+       scratchpad[varname] = stringf("%d", value);
+}
+
+void RTLIL::Design::scratchpad_set_bool(std::string varname, bool value)
+{
+       scratchpad[varname] = value ? "true" : "false";
+}
+
+void RTLIL::Design::scratchpad_set_string(std::string varname, std::string value)
+{
+       scratchpad[varname] = value;
+}
+
+int RTLIL::Design::scratchpad_get_int(std::string varname, int default_value) const
+{
+       if (scratchpad.count(varname) == 0)
+               return default_value;
+
+       std::string str = scratchpad.at(varname);
+
+       if (str == "0" || str == "false")
+               return 0;
+
+       if (str == "1" || str == "true")
+               return 1;
+
+       char *endptr = nullptr;
+       long int parsed_value = strtol(str.c_str(), &endptr, 10);
+       return *endptr ? default_value : parsed_value;
+}
+
+bool RTLIL::Design::scratchpad_get_bool(std::string varname, bool default_value) const
+{
+       if (scratchpad.count(varname) == 0)
+               return default_value;
+
+       std::string str = scratchpad.at(varname);
+
+       if (str == "0" || str == "false")
+               return false;
+
+       if (str == "1" || str == "true")
+               return true;
+
+       return default_value;
+}
+
+std::string RTLIL::Design::scratchpad_get_string(std::string varname, std::string default_value) const
+{
+       if (scratchpad.count(varname) == 0)
+               return default_value;
+       return scratchpad.at(varname);
 }
 
 void RTLIL::Design::remove(RTLIL::Module *module)
 {
+       for (auto mon : monitors)
+               mon->notify_module_del(module);
+
        log_assert(modules_.at(module->name) == module);
        modules_.erase(module->name);
        delete module;
@@ -262,8 +358,9 @@ void RTLIL::Design::check()
 {
 #ifndef NDEBUG
        for (auto &it : modules_) {
+               log_assert(this == it.second->design);
                log_assert(it.first == it.second->name);
-               log_assert(it.first.size() > 0 && (it.first[0] == '\\' || it.first[0] == '$'));
+               log_assert(!it.first.empty());
                it.second->check();
        }
 #endif
@@ -316,8 +413,41 @@ bool RTLIL::Design::selected_whole_module(RTLIL::Module *mod) const
        return selected_whole_module(mod->name);
 }
 
+std::vector<RTLIL::Module*> RTLIL::Design::selected_modules() const
+{
+       std::vector<RTLIL::Module*> result;
+       result.reserve(modules_.size());
+       for (auto &it : modules_)
+               if (selected_module(it.first))
+                       result.push_back(it.second);
+       return result;
+}
+
+std::vector<RTLIL::Module*> RTLIL::Design::selected_whole_modules() const
+{
+       std::vector<RTLIL::Module*> result;
+       result.reserve(modules_.size());
+       for (auto &it : modules_)
+               if (selected_whole_module(it.first))
+                       result.push_back(it.second);
+       return result;
+}
+
+std::vector<RTLIL::Module*> RTLIL::Design::selected_whole_modules_warn() const
+{
+       std::vector<RTLIL::Module*> result;
+       result.reserve(modules_.size());
+       for (auto &it : modules_)
+               if (selected_whole_module(it.first))
+                       result.push_back(it.second);
+               else if (selected_module(it.first))
+                       log_warning("Ignoring partially selected module %s.\n", log_id(it.first));
+       return result;
+}
+
 RTLIL::Module::Module()
 {
+       design = nullptr;
        refcount_wires_ = 0;
        refcount_cells_ = 0;
 }
@@ -356,17 +486,12 @@ namespace {
 
                void error(int linenr)
                {
-                       char *ptr;
-                       size_t size;
-
-                       FILE *f = open_memstream(&ptr, &size);
-                       ILANG_BACKEND::dump_cell(f, "  ", cell);
-                       fputc(0, f);
-                       fclose(f);
+                       std::stringstream buf;
+                       ILANG_BACKEND::dump_cell(buf, "  ", cell);
 
                        log_error("Found error in internal cell %s%s%s (%s) at %s:%d:\n%s",
                                        module ? module->name.c_str() : "", module ? "." : "",
-                                       cell->name.c_str(), cell->type.c_str(), __FILE__, linenr, ptr);
+                                       cell->name.c_str(), cell->type.c_str(), __FILE__, linenr, buf.str().c_str());
                }
 
                int param(const char *name)
@@ -396,9 +521,9 @@ namespace {
 
                void port(const char *name, int width)
                {
-                       if (!cell->has(name))
+                       if (!cell->hasPort(name))
                                error(__LINE__);
-                       if (cell->get(name).size() != width)
+                       if (cell->getPort(name).size() != width)
                                error(__LINE__);
                        expected_ports.insert(name);
                }
@@ -427,27 +552,27 @@ namespace {
 
                        for (const char *p = ports; *p; p++) {
                                char portname[3] = { '\\', *p, 0 };
-                               if (!cell->has(portname))
+                               if (!cell->hasPort(portname))
                                        error(__LINE__);
-                               if (cell->get(portname).size() != 1)
+                               if (cell->getPort(portname).size() != 1)
                                        error(__LINE__);
                        }
 
                        for (auto &conn : cell->connections()) {
-                               if (conn.first.size() != 2 || conn.first.at(0) != '\\')
+                               if (conn.first.size() != 2 || conn.first[0] != '\\')
                                        error(__LINE__);
-                               if (strchr(ports, conn.first.at(1)) == NULL)
+                               if (strchr(ports, conn.first[1]) == NULL)
                                        error(__LINE__);
                        }
                }
 
                void check()
                {
-                       if (cell->type[0] != '$' || cell->type.substr(0, 3) == "$__" || cell->type.substr(0, 8) == "$paramod" ||
+                       if (cell->type.substr(0, 1) != "$" || cell->type.substr(0, 3) == "$__" || cell->type.substr(0, 8) == "$paramod" ||
                                        cell->type.substr(0, 9) == "$verific$" || cell->type.substr(0, 7) == "$array:" || cell->type.substr(0, 8) == "$extern:")
                                return;
 
-                       if (cell->type == "$not" || cell->type == "$pos" || cell->type == "$bu0" || cell->type == "$neg") {
+                       if (cell->type.in("$not", "$pos", "$neg")) {
                                param_bool("\\A_SIGNED");
                                port("\\A", param("\\A_WIDTH"));
                                port("\\Y", param("\\Y_WIDTH"));
@@ -455,7 +580,7 @@ namespace {
                                return;
                        }
 
-                       if (cell->type == "$and" || cell->type == "$or" || cell->type == "$xor" || cell->type == "$xnor") {
+                       if (cell->type.in("$and", "$or", "$xor", "$xnor")) {
                                param_bool("\\A_SIGNED");
                                param_bool("\\B_SIGNED");
                                port("\\A", param("\\A_WIDTH"));
@@ -465,8 +590,7 @@ namespace {
                                return;
                        }
 
-                       if (cell->type == "$reduce_and" || cell->type == "$reduce_or" || cell->type == "$reduce_xor" ||
-                                       cell->type == "$reduce_xnor" || cell->type == "$reduce_bool") {
+                       if (cell->type.in("$reduce_and", "$reduce_or", "$reduce_xor", "$reduce_xnor", "$reduce_bool")) {
                                param_bool("\\A_SIGNED");
                                port("\\A", param("\\A_WIDTH"));
                                port("\\Y", param("\\Y_WIDTH"));
@@ -474,7 +598,7 @@ namespace {
                                return;
                        }
 
-                       if (cell->type == "$shl" || cell->type == "$shr" || cell->type == "$sshl" || cell->type == "$sshr") {
+                       if (cell->type.in("$shl", "$shr", "$sshl", "$sshr", "$shift", "$shiftx")) {
                                param_bool("\\A_SIGNED");
                                param_bool("\\B_SIGNED");
                                port("\\A", param("\\A_WIDTH"));
@@ -484,8 +608,7 @@ namespace {
                                return;
                        }
 
-                       if (cell->type == "$lt" || cell->type == "$le" || cell->type == "$eq" || cell->type == "$ne" ||
-                                       cell->type == "$eqx" || cell->type == "$nex" || cell->type == "$ge" || cell->type == "$gt") {
+                       if (cell->type.in("$lt", "$le", "$eq", "$ne", "$eqx", "$nex", "$ge", "$gt")) {
                                param_bool("\\A_SIGNED");
                                param_bool("\\B_SIGNED");
                                port("\\A", param("\\A_WIDTH"));
@@ -495,8 +618,7 @@ namespace {
                                return;
                        }
 
-                       if (cell->type == "$add" || cell->type == "$sub" || cell->type == "$mul" || cell->type == "$div" ||
-                                       cell->type == "$mod" || cell->type == "$pow") {
+                       if (cell->type.in("$add", "$sub", "$mul", "$div", "$mod", "$pow")) {
                                param_bool("\\A_SIGNED");
                                param_bool("\\B_SIGNED");
                                port("\\A", param("\\A_WIDTH"));
@@ -506,6 +628,50 @@ namespace {
                                return;
                        }
 
+                       if (cell->type == "$fa") {
+                               port("\\A", param("\\WIDTH"));
+                               port("\\B", param("\\WIDTH"));
+                               port("\\C", param("\\WIDTH"));
+                               port("\\X", param("\\WIDTH"));
+                               port("\\Y", param("\\WIDTH"));
+                               check_expected();
+                               return;
+                       }
+
+                       if (cell->type == "$lcu") {
+                               port("\\P", param("\\WIDTH"));
+                               port("\\G", param("\\WIDTH"));
+                               port("\\CI", 1);
+                               port("\\CO", param("\\WIDTH"));
+                               check_expected();
+                               return;
+                       }
+
+                       if (cell->type == "$alu") {
+                               param_bool("\\A_SIGNED");
+                               param_bool("\\B_SIGNED");
+                               port("\\A", param("\\A_WIDTH"));
+                               port("\\B", param("\\B_WIDTH"));
+                               port("\\CI", 1);
+                               port("\\BI", 1);
+                               port("\\X", param("\\Y_WIDTH"));
+                               port("\\Y", param("\\Y_WIDTH"));
+                               port("\\CO", param("\\Y_WIDTH"));
+                               check_expected();
+                               return;
+                       }
+
+                       if (cell->type == "$macc") {
+                               param("\\CONFIG");
+                               param("\\CONFIG_WIDTH");
+                               port("\\A", param("\\A_WIDTH"));
+                               port("\\B", param("\\B_WIDTH"));
+                               port("\\Y", param("\\Y_WIDTH"));
+                               check_expected();
+                               Macc().from_cell(cell);
+                               return;
+                       }
+
                        if (cell->type == "$logic_not") {
                                param_bool("\\A_SIGNED");
                                port("\\A", param("\\A_WIDTH"));
@@ -551,7 +717,7 @@ namespace {
                                return;
                        }
 
-                       if (cell->type == "$pmux" || cell->type == "$safe_pmux") {
+                       if (cell->type == "$pmux") {
                                port("\\A", param("\\WIDTH"));
                                port("\\B", param("\\WIDTH") * param("\\S_WIDTH"));
                                port("\\S", param("\\S_WIDTH"));
@@ -562,8 +728,8 @@ namespace {
 
                        if (cell->type == "$lut") {
                                param("\\LUT");
-                               port("\\I", param("\\WIDTH"));
-                               port("\\O", 1);
+                               port("\\A", param("\\WIDTH"));
+                               port("\\Y", 1);
                                check_expected();
                                return;
                        }
@@ -587,6 +753,17 @@ namespace {
                                return;
                        }
 
+                       if (cell->type == "$dffe") {
+                               param_bool("\\CLK_POLARITY");
+                               param_bool("\\EN_POLARITY");
+                               port("\\CLK", 1);
+                               port("\\EN", 1);
+                               port("\\D", param("\\WIDTH"));
+                               port("\\Q", param("\\WIDTH"));
+                               check_expected();
+                               return;
+                       }
+
                        if (cell->type == "$dffsr") {
                                param_bool("\\CLK_POLARITY");
                                param_bool("\\SET_POLARITY");
@@ -705,11 +882,19 @@ namespace {
                                return;
                        }
 
-                       if (cell->type == "$_INV_") { check_gate("AY"); return; }
-                       if (cell->type == "$_AND_") { check_gate("ABY"); return; }
-                       if (cell->type == "$_OR_")  { check_gate("ABY"); return; }
-                       if (cell->type == "$_XOR_") { check_gate("ABY"); return; }
-                       if (cell->type == "$_MUX_") { check_gate("ABSY"); return; }
+                       if (cell->type == "$_BUF_")  { check_gate("AY"); return; }
+                       if (cell->type == "$_NOT_")  { check_gate("AY"); return; }
+                       if (cell->type == "$_AND_")  { check_gate("ABY"); return; }
+                       if (cell->type == "$_NAND_") { check_gate("ABY"); return; }
+                       if (cell->type == "$_OR_")   { check_gate("ABY"); return; }
+                       if (cell->type == "$_NOR_")  { check_gate("ABY"); return; }
+                       if (cell->type == "$_XOR_")  { check_gate("ABY"); return; }
+                       if (cell->type == "$_XNOR_") { check_gate("ABY"); return; }
+                       if (cell->type == "$_MUX_")  { check_gate("ABSY"); return; }
+                       if (cell->type == "$_AOI3_") { check_gate("ABCY"); return; }
+                       if (cell->type == "$_OAI3_") { check_gate("ABCY"); return; }
+                       if (cell->type == "$_AOI4_") { check_gate("ABCDY"); return; }
+                       if (cell->type == "$_OAI4_") { check_gate("ABCDY"); return; }
 
                        if (cell->type == "$_SR_NN_") { check_gate("SRQ"); return; }
                        if (cell->type == "$_SR_NP_") { check_gate("SRQ"); return; }
@@ -719,6 +904,11 @@ namespace {
                        if (cell->type == "$_DFF_N_") { check_gate("DQC"); return; }
                        if (cell->type == "$_DFF_P_") { check_gate("DQC"); return; }
 
+                       if (cell->type == "$_DFFE_NN_") { check_gate("DQCE"); return; }
+                       if (cell->type == "$_DFFE_NP_") { check_gate("DQCE"); return; }
+                       if (cell->type == "$_DFFE_PN_") { check_gate("DQCE"); return; }
+                       if (cell->type == "$_DFFE_PP_") { check_gate("DQCE"); return; }
+
                        if (cell->type == "$_DFF_NN0_") { check_gate("DQCR"); return; }
                        if (cell->type == "$_DFF_NN1_") { check_gate("DQCR"); return; }
                        if (cell->type == "$_DFF_NP0_") { check_gate("DQCR"); return; }
@@ -758,47 +948,59 @@ namespace {
 void RTLIL::Module::check()
 {
 #ifndef NDEBUG
+       std::vector<bool> ports_declared;
        for (auto &it : wires_) {
+               log_assert(this == it.second->module);
                log_assert(it.first == it.second->name);
-               log_assert(it.first.size() > 0 && (it.first[0] == '\\' || it.first[0] == '$'));
+               log_assert(!it.first.empty());
                log_assert(it.second->width >= 0);
                log_assert(it.second->port_id >= 0);
-               for (auto &it2 : it.second->attributes) {
-                       log_assert(it2.first.size() > 0 && (it2.first[0] == '\\' || it2.first[0] == '$'));
-               }
+               for (auto &it2 : it.second->attributes)
+                       log_assert(!it2.first.empty());
+               if (it.second->port_id) {
+                       log_assert(GetSize(ports) >= it.second->port_id);
+                       log_assert(ports.at(it.second->port_id-1) == it.first);
+                       log_assert(it.second->port_input || it.second->port_output);
+                       if (GetSize(ports_declared) < it.second->port_id)
+                               ports_declared.resize(it.second->port_id);
+                       log_assert(ports_declared[it.second->port_id-1] == false);
+                       ports_declared[it.second->port_id-1] = true;
+               } else
+                       log_assert(!it.second->port_input && !it.second->port_output);
        }
+       for (auto port_declared : ports_declared)
+               log_assert(port_declared == true);
+       log_assert(GetSize(ports) == GetSize(ports_declared));
 
        for (auto &it : memories) {
                log_assert(it.first == it.second->name);
-               log_assert(it.first.size() > 0 && (it.first[0] == '\\' || it.first[0] == '$'));
+               log_assert(!it.first.empty());
                log_assert(it.second->width >= 0);
                log_assert(it.second->size >= 0);
-               for (auto &it2 : it.second->attributes) {
-                       log_assert(it2.first.size() > 0 && (it2.first[0] == '\\' || it2.first[0] == '$'));
-               }
+               for (auto &it2 : it.second->attributes)
+                       log_assert(!it2.first.empty());
        }
 
        for (auto &it : cells_) {
+               log_assert(this == it.second->module);
                log_assert(it.first == it.second->name);
-               log_assert(it.first.size() > 0 && (it.first[0] == '\\' || it.first[0] == '$'));
-               log_assert(it.second->type.size() > 0 && (it.second->type[0] == '\\' || it.second->type[0] == '$'));
+               log_assert(!it.first.empty());
+               log_assert(!it.second->type.empty());
                for (auto &it2 : it.second->connections()) {
-                       log_assert(it2.first.size() > 0 && (it2.first[0] == '\\' || it2.first[0] == '$'));
+                       log_assert(!it2.first.empty());
                        it2.second.check();
                }
-               for (auto &it2 : it.second->attributes) {
-                       log_assert(it2.first.size() > 0 && (it2.first[0] == '\\' || it2.first[0] == '$'));
-               }
-               for (auto &it2 : it.second->parameters) {
-                       log_assert(it2.first.size() > 0 && (it2.first[0] == '\\' || it2.first[0] == '$'));
-               }
+               for (auto &it2 : it.second->attributes)
+                       log_assert(!it2.first.empty());
+               for (auto &it2 : it.second->parameters)
+                       log_assert(!it2.first.empty());
                InternalCellChecker checker(this, it.second);
                checker.check();
        }
 
        for (auto &it : processes) {
                log_assert(it.first == it.second->name);
-               log_assert(it.first.size() > 0 && (it.first[0] == '\\' || it.first[0] == '$'));
+               log_assert(!it.first.empty());
                // FIXME: More checks here..
        }
 
@@ -808,9 +1010,8 @@ void RTLIL::Module::check()
                it.second.check();
        }
 
-       for (auto &it : attributes) {
-               log_assert(it.first.size() > 0 && (it.first[0] == '\\' || it.first[0] == '$'));
-       }
+       for (auto &it : attributes)
+               log_assert(!it.first.empty());
 #endif
 }
 
@@ -854,6 +1055,7 @@ void RTLIL::Module::cloneInto(RTLIL::Module *new_mod) const
        RewriteSigSpecWorker rewriteSigSpecWorker;
        rewriteSigSpecWorker.mod = new_mod;
        new_mod->rewrite_sigspecs(rewriteSigSpecWorker);
+       new_mod->fixup_ports();
 }
 
 RTLIL::Module *RTLIL::Module::clone() const
@@ -864,12 +1066,57 @@ RTLIL::Module *RTLIL::Module::clone() const
        return new_mod;
 }
 
+bool RTLIL::Module::has_memories() const
+{
+       return !memories.empty();
+}
+
+bool RTLIL::Module::has_processes() const
+{
+       return !processes.empty();
+}
+
+bool RTLIL::Module::has_memories_warn() const
+{
+       if (!memories.empty())
+               log_warning("Ignoring module %s because it contains memories (run 'memory' command first).\n", log_id(this));
+       return !memories.empty();
+}
+
+bool RTLIL::Module::has_processes_warn() const
+{
+       if (!processes.empty())
+               log_warning("Ignoring module %s because it contains processes (run 'proc' command first).\n", log_id(this));
+       return !processes.empty();
+}
+
+std::vector<RTLIL::Wire*> RTLIL::Module::selected_wires() const
+{
+       std::vector<RTLIL::Wire*> result;
+       result.reserve(wires_.size());
+       for (auto &it : wires_)
+               if (design->selected(this, it.second))
+                       result.push_back(it.second);
+       return result;
+}
+
+std::vector<RTLIL::Cell*> RTLIL::Module::selected_cells() const
+{
+       std::vector<RTLIL::Cell*> result;
+       result.reserve(wires_.size());
+       for (auto &it : cells_)
+               if (design->selected(this, it.second))
+                       result.push_back(it.second);
+       return result;
+}
+
 void RTLIL::Module::add(RTLIL::Wire *wire)
 {
        log_assert(!wire->name.empty());
        log_assert(count_id(wire->name) == 0);
        log_assert(refcount_wires_ == 0);
        wires_[wire->name] = wire;
+       wire->module = this;
 }
 
 void RTLIL::Module::add(RTLIL::Cell *cell)
@@ -878,6 +1125,7 @@ void RTLIL::Module::add(RTLIL::Cell *cell)
        log_assert(count_id(cell->name) == 0);
        log_assert(refcount_cells_ == 0);
        cells_[cell->name] = cell;
+       cell->module = this;
 }
 
 namespace {
@@ -901,7 +1149,7 @@ namespace {
 #if 0
 void RTLIL::Module::remove(RTLIL::Wire *wire)
 {
-       std::set<RTLIL::Wire*> wires_;
+       std::setPort<RTLIL::Wire*> wires_;
        wires_.insert(wire);
        remove(wires_);
 }
@@ -925,6 +1173,9 @@ void RTLIL::Module::remove(const std::set<RTLIL::Wire*> &wires)
 
 void RTLIL::Module::remove(RTLIL::Cell *cell)
 {
+       while (!cell->connections_.empty())
+               cell->unsetPort(cell->connections_.begin()->first);
+
        log_assert(cells_.count(cell->name) != 0);
        log_assert(refcount_cells_ == 0);
        cells_.erase(cell->name);
@@ -960,6 +1211,58 @@ void RTLIL::Module::rename(RTLIL::IdString old_name, RTLIL::IdString new_name)
                log_abort();
 }
 
+void RTLIL::Module::swap_names(RTLIL::Wire *w1, RTLIL::Wire *w2)
+{
+       log_assert(wires_[w1->name] == w1);
+       log_assert(wires_[w2->name] == w2);
+       log_assert(refcount_wires_ == 0);
+
+       wires_.erase(w1->name);
+       wires_.erase(w2->name);
+
+       std::swap(w1->name, w2->name);
+
+       wires_[w1->name] = w1;
+       wires_[w2->name] = w2;
+}
+
+void RTLIL::Module::swap_names(RTLIL::Cell *c1, RTLIL::Cell *c2)
+{
+       log_assert(cells_[c1->name] == c1);
+       log_assert(cells_[c2->name] == c2);
+       log_assert(refcount_cells_ == 0);
+
+       cells_.erase(c1->name);
+       cells_.erase(c2->name);
+
+       std::swap(c1->name, c2->name);
+
+       cells_[c1->name] = c1;
+       cells_[c2->name] = c2;
+}
+
+RTLIL::IdString RTLIL::Module::uniquify(RTLIL::IdString name)
+{
+       int index = 0;
+       return uniquify(name, index);
+}
+
+RTLIL::IdString RTLIL::Module::uniquify(RTLIL::IdString name, int &index)
+{
+       if (index == 0) {
+               if (count_id(name) == 0)
+                       return name;
+               index++;
+       }
+
+       while (1) {
+               RTLIL::IdString new_name = stringf("%s_%d", name.c_str(), index);
+               if (count_id(new_name) == 0)
+                       return new_name;
+               index++;
+       }
+}
+
 static bool fixup_ports_compare(const RTLIL::Wire *a, const RTLIL::Wire *b)
 {
        if (a->port_id && !b->port_id)
@@ -974,12 +1277,31 @@ static bool fixup_ports_compare(const RTLIL::Wire *a, const RTLIL::Wire *b)
 
 void RTLIL::Module::connect(const RTLIL::SigSig &conn)
 {
+       for (auto mon : monitors)
+               mon->notify_connect(this, conn);
+
+       if (design)
+               for (auto mon : design->monitors)
+                       mon->notify_connect(this, conn);
+
        connections_.push_back(conn);
 }
 
 void RTLIL::Module::connect(const RTLIL::SigSpec &lhs, const RTLIL::SigSpec &rhs)
 {
-       connections_.push_back(RTLIL::SigSig(lhs, rhs));
+       connect(RTLIL::SigSig(lhs, rhs));
+}
+
+void RTLIL::Module::new_connections(const std::vector<RTLIL::SigSig> &new_conn)
+{
+       for (auto mon : monitors)
+               mon->notify_connect(this, new_conn);
+
+       if (design)
+               for (auto mon : design->monitors)
+                       mon->notify_connect(this, new_conn);
+
+       connections_ = new_conn;
 }
 
 const std::vector<RTLIL::SigSig> &RTLIL::Module::connections() const
@@ -998,8 +1320,12 @@ void RTLIL::Module::fixup_ports()
                        w.second->port_id = 0;
 
        std::sort(all_ports.begin(), all_ports.end(), fixup_ports_compare);
-       for (size_t i = 0; i < all_ports.size(); i++)
+
+       ports.clear();
+       for (size_t i = 0; i < all_ports.size(); i++) {
+               ports.push_back(all_ports[i]->name);
                all_ports[i]->port_id = i+1;
+       }
 }
 
 RTLIL::Wire *RTLIL::Module::addWire(RTLIL::IdString name, int width)
@@ -1019,6 +1345,7 @@ RTLIL::Wire *RTLIL::Module::addWire(RTLIL::IdString name, const RTLIL::Wire *oth
        wire->port_id = other->port_id;
        wire->port_input = other->port_input;
        wire->port_output = other->port_output;
+       wire->upto = other->upto;
        wire->attributes = other->attributes;
        return wire;
 }
@@ -1043,15 +1370,12 @@ RTLIL::Cell *RTLIL::Module::addCell(RTLIL::IdString name, const RTLIL::Cell *oth
 
 #define DEF_METHOD(_func, _y_size, _type) \
        RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_y, bool is_signed) { \
-               RTLIL::Cell *cell = new RTLIL::Cell;                \
-               cell->name = name;                                  \
-               cell->type = _type;                                 \
+               RTLIL::Cell *cell = addCell(name, _type);           \
                cell->parameters["\\A_SIGNED"] = is_signed;         \
-               cell->parameters["\\A_WIDTH"] = sig_a.size();        \
-               cell->parameters["\\Y_WIDTH"] = sig_y.size();        \
-               cell->set("\\A", sig_a);                   \
-               cell->set("\\Y", sig_y);                   \
-               add(cell);                                          \
+               cell->parameters["\\A_WIDTH"] = sig_a.size();       \
+               cell->parameters["\\Y_WIDTH"] = sig_y.size();       \
+               cell->setPort("\\A", sig_a);                        \
+               cell->setPort("\\Y", sig_y);                        \
                return cell;                                        \
        } \
        RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig_a, bool is_signed) { \
@@ -1061,7 +1385,6 @@ RTLIL::Cell *RTLIL::Module::addCell(RTLIL::IdString name, const RTLIL::Cell *oth
        }
 DEF_METHOD(Not,        sig_a.size(), "$not")
 DEF_METHOD(Pos,        sig_a.size(), "$pos")
-DEF_METHOD(Bu0,        sig_a.size(), "$bu0")
 DEF_METHOD(Neg,        sig_a.size(), "$neg")
 DEF_METHOD(ReduceAnd,  1, "$reduce_and")
 DEF_METHOD(ReduceOr,   1, "$reduce_or")
@@ -1073,18 +1396,15 @@ DEF_METHOD(LogicNot,   1, "$logic_not")
 
 #define DEF_METHOD(_func, _y_size, _type) \
        RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_y, bool is_signed) { \
-               RTLIL::Cell *cell = new RTLIL::Cell;                \
-               cell->name = name;                                  \
-               cell->type = _type;                                 \
+               RTLIL::Cell *cell = addCell(name, _type);           \
                cell->parameters["\\A_SIGNED"] = is_signed;         \
                cell->parameters["\\B_SIGNED"] = is_signed;         \
-               cell->parameters["\\A_WIDTH"] = sig_a.size();        \
-               cell->parameters["\\B_WIDTH"] = sig_b.size();        \
-               cell->parameters["\\Y_WIDTH"] = sig_y.size();        \
-               cell->set("\\A", sig_a);                   \
-               cell->set("\\B", sig_b);                   \
-               cell->set("\\Y", sig_y);                   \
-               add(cell);                                          \
+               cell->parameters["\\A_WIDTH"] = sig_a.size();       \
+               cell->parameters["\\B_WIDTH"] = sig_b.size();       \
+               cell->parameters["\\Y_WIDTH"] = sig_y.size();       \
+               cell->setPort("\\A", sig_a);                        \
+               cell->setPort("\\B", sig_b);                        \
+               cell->setPort("\\Y", sig_y);                        \
                return cell;                                        \
        } \
        RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, bool is_signed) { \
@@ -1100,6 +1420,8 @@ DEF_METHOD(Shl,      sig_a.size(), "$shl")
 DEF_METHOD(Shr,      sig_a.size(), "$shr")
 DEF_METHOD(Sshl,     sig_a.size(), "$sshl")
 DEF_METHOD(Sshr,     sig_a.size(), "$sshr")
+DEF_METHOD(Shift,    sig_a.size(), "$shift")
+DEF_METHOD(Shiftx,   sig_a.size(), "$shiftx")
 DEF_METHOD(Lt,       1, "$lt")
 DEF_METHOD(Le,       1, "$le")
 DEF_METHOD(Eq,       1, "$eq")
@@ -1119,330 +1441,316 @@ DEF_METHOD(LogicOr,  1, "$logic_or")
 
 #define DEF_METHOD(_func, _type, _pmux) \
        RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_s, RTLIL::SigSpec sig_y) { \
-               RTLIL::Cell *cell = new RTLIL::Cell;                     \
-               cell->name = name;                                       \
-               cell->type = _type;                                      \
+               RTLIL::Cell *cell = addCell(name, _type);                 \
                cell->parameters["\\WIDTH"] = sig_a.size();               \
-               cell->parameters["\\WIDTH"] = sig_b.size();               \
                if (_pmux) cell->parameters["\\S_WIDTH"] = sig_s.size();  \
-               cell->set("\\A", sig_a);                        \
-               cell->set("\\B", sig_b);                        \
-               cell->set("\\S", sig_s);                        \
-               cell->set("\\Y", sig_y);                        \
-               add(cell);                                               \
-               return cell;                                             \
+               cell->setPort("\\A", sig_a);                              \
+               cell->setPort("\\B", sig_b);                              \
+               cell->setPort("\\S", sig_s);                              \
+               cell->setPort("\\Y", sig_y);                              \
+               return cell;                                              \
        } \
        RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_s) { \
                RTLIL::SigSpec sig_y = addWire(NEW_ID, sig_a.size());     \
-               add ## _func(name, sig_a, sig_b, sig_s, sig_y);          \
-               return sig_y;                                            \
+               add ## _func(name, sig_a, sig_b, sig_s, sig_y);           \
+               return sig_y;                                             \
        }
 DEF_METHOD(Mux,      "$mux",        0)
 DEF_METHOD(Pmux,     "$pmux",       1)
-DEF_METHOD(SafePmux, "$safe_pmux",  1)
 #undef DEF_METHOD
 
 #define DEF_METHOD_2(_func, _type, _P1, _P2) \
-       RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig1, RTLIL::SigSpec sig2) { \
-               RTLIL::Cell *cell = new RTLIL::Cell;        \
-               cell->name = name;                          \
-               cell->type = _type;                         \
-               cell->set("\\" #_P1, sig1);                 \
-               cell->set("\\" #_P2, sig2);                 \
-               add(cell);                                  \
-               return cell;                                \
+       RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2) { \
+               RTLIL::Cell *cell = addCell(name, _type);         \
+               cell->setPort("\\" #_P1, sig1);                   \
+               cell->setPort("\\" #_P2, sig2);                   \
+               return cell;                                      \
        } \
-       RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig1) { \
-               RTLIL::SigSpec sig2 = addWire(NEW_ID);      \
-               add ## _func(name, sig1, sig2);             \
-               return sig2;                                \
+       RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1) { \
+               RTLIL::SigBit sig2 = addWire(NEW_ID);            \
+               add ## _func(name, sig1, sig2);                   \
+               return sig2;                                      \
        }
 #define DEF_METHOD_3(_func, _type, _P1, _P2, _P3) \
-       RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig1, RTLIL::SigSpec sig2, RTLIL::SigSpec sig3) { \
-               RTLIL::Cell *cell = new RTLIL::Cell;        \
-               cell->name = name;                          \
-               cell->type = _type;                         \
-               cell->set("\\" #_P1, sig1);                 \
-               cell->set("\\" #_P2, sig2);                 \
-               cell->set("\\" #_P3, sig3);                 \
-               add(cell);                                  \
-               return cell;                                \
+       RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3) { \
+               RTLIL::Cell *cell = addCell(name, _type);         \
+               cell->setPort("\\" #_P1, sig1);                   \
+               cell->setPort("\\" #_P2, sig2);                   \
+               cell->setPort("\\" #_P3, sig3);                   \
+               return cell;                                      \
        } \
-       RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig1, RTLIL::SigSpec sig2) { \
-               RTLIL::SigSpec sig3 = addWire(NEW_ID);      \
-               add ## _func(name, sig1, sig2, sig3);       \
-               return sig3;                                \
+       RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2) { \
+               RTLIL::SigBit sig3 = addWire(NEW_ID);            \
+               add ## _func(name, sig1, sig2, sig3);             \
+               return sig3;                                      \
        }
 #define DEF_METHOD_4(_func, _type, _P1, _P2, _P3, _P4) \
-       RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigSpec sig1, RTLIL::SigSpec sig2, RTLIL::SigSpec sig3, RTLIL::SigSpec sig4) { \
-               RTLIL::Cell *cell = new RTLIL::Cell;        \
-               cell->name = name;                          \
-               cell->type = _type;                         \
-               cell->set("\\" #_P1, sig1);                 \
-               cell->set("\\" #_P2, sig2);                 \
-               cell->set("\\" #_P3, sig3);                 \
-               cell->set("\\" #_P4, sig4);                 \
-               add(cell);                                  \
-               return cell;                                \
+       RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, RTLIL::SigBit sig4) { \
+               RTLIL::Cell *cell = addCell(name, _type);         \
+               cell->setPort("\\" #_P1, sig1);                   \
+               cell->setPort("\\" #_P2, sig2);                   \
+               cell->setPort("\\" #_P3, sig3);                   \
+               cell->setPort("\\" #_P4, sig4);                   \
+               return cell;                                      \
        } \
-       RTLIL::SigSpec RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigSpec sig1, RTLIL::SigSpec sig2, RTLIL::SigSpec sig3) { \
-               RTLIL::SigSpec sig4 = addWire(NEW_ID);      \
-               add ## _func(name, sig1, sig2, sig3, sig4); \
-               return sig4;                                \
+       RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3) { \
+               RTLIL::SigBit sig4 = addWire(NEW_ID);            \
+               add ## _func(name, sig1, sig2, sig3, sig4);       \
+               return sig4;                                      \
        }
-DEF_METHOD_2(InvGate, "$_INV_", A, Y)
-DEF_METHOD_3(AndGate, "$_AND_", A, B, Y)
-DEF_METHOD_3(OrGate,  "$_OR_",  A, B, Y)
-DEF_METHOD_3(XorGate, "$_XOR_", A, B, Y)
-DEF_METHOD_4(MuxGate, "$_MUX_", A, B, S, Y)
+#define DEF_METHOD_5(_func, _type, _P1, _P2, _P3, _P4, _P5) \
+       RTLIL::Cell* RTLIL::Module::add ## _func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, RTLIL::SigBit sig4, RTLIL::SigBit sig5) { \
+               RTLIL::Cell *cell = addCell(name, _type);         \
+               cell->setPort("\\" #_P1, sig1);                   \
+               cell->setPort("\\" #_P2, sig2);                   \
+               cell->setPort("\\" #_P3, sig3);                   \
+               cell->setPort("\\" #_P4, sig4);                   \
+               cell->setPort("\\" #_P5, sig5);                   \
+               return cell;                                      \
+       } \
+       RTLIL::SigBit RTLIL::Module::_func(RTLIL::IdString name, RTLIL::SigBit sig1, RTLIL::SigBit sig2, RTLIL::SigBit sig3, RTLIL::SigBit sig4) { \
+               RTLIL::SigBit sig5 = addWire(NEW_ID);            \
+               add ## _func(name, sig1, sig2, sig3, sig4, sig5); \
+               return sig5;                                      \
+       }
+DEF_METHOD_2(NotGate,  "$_NOT_",  A, Y)
+DEF_METHOD_3(AndGate,  "$_AND_",  A, B, Y)
+DEF_METHOD_3(NandGate, "$_NAND_", A, B, Y)
+DEF_METHOD_3(OrGate,   "$_OR_",   A, B, Y)
+DEF_METHOD_3(NorGate,  "$_NOR_",  A, B, Y)
+DEF_METHOD_3(XorGate,  "$_XOR_",  A, B, Y)
+DEF_METHOD_3(XnorGate, "$_XNOR_", A, B, Y)
+DEF_METHOD_4(MuxGate,  "$_MUX_",  A, B, S, Y)
+DEF_METHOD_4(Aoi3Gate, "$_AOI3_", A, B, C, Y)
+DEF_METHOD_4(Oai3Gate, "$_OAI3_", A, B, C, Y)
+DEF_METHOD_5(Aoi4Gate, "$_AOI4_", A, B, C, D, Y)
+DEF_METHOD_5(Oai4Gate, "$_OAI4_", A, B, C, D, Y)
 #undef DEF_METHOD_2
 #undef DEF_METHOD_3
 #undef DEF_METHOD_4
+#undef DEF_METHOD_5
 
 RTLIL::Cell* RTLIL::Module::addPow(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_y, bool a_signed, bool b_signed)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$pow";
+       RTLIL::Cell *cell = addCell(name, "$pow");
        cell->parameters["\\A_SIGNED"] = a_signed;
        cell->parameters["\\B_SIGNED"] = b_signed;
        cell->parameters["\\A_WIDTH"] = sig_a.size();
        cell->parameters["\\B_WIDTH"] = sig_b.size();
        cell->parameters["\\Y_WIDTH"] = sig_y.size();
-       cell->set("\\A", sig_a);
-       cell->set("\\B", sig_b);
-       cell->set("\\Y", sig_y);
-       add(cell);
+       cell->setPort("\\A", sig_a);
+       cell->setPort("\\B", sig_b);
+       cell->setPort("\\Y", sig_y);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addSlice(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_y, RTLIL::Const offset)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$slice";
+       RTLIL::Cell *cell = addCell(name, "$slice");
        cell->parameters["\\A_WIDTH"] = sig_a.size();
        cell->parameters["\\Y_WIDTH"] = sig_y.size();
        cell->parameters["\\OFFSET"] = offset;
-       cell->set("\\A", sig_a);
-       cell->set("\\Y", sig_y);
-       add(cell);
+       cell->setPort("\\A", sig_a);
+       cell->setPort("\\Y", sig_y);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addConcat(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_b, RTLIL::SigSpec sig_y)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$concat";
+       RTLIL::Cell *cell = addCell(name, "$concat");
        cell->parameters["\\A_WIDTH"] = sig_a.size();
        cell->parameters["\\B_WIDTH"] = sig_b.size();
-       cell->set("\\A", sig_a);
-       cell->set("\\B", sig_b);
-       cell->set("\\Y", sig_y);
-       add(cell);
+       cell->setPort("\\A", sig_a);
+       cell->setPort("\\B", sig_b);
+       cell->setPort("\\Y", sig_y);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addLut(RTLIL::IdString name, RTLIL::SigSpec sig_i, RTLIL::SigSpec sig_o, RTLIL::Const lut)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$lut";
+       RTLIL::Cell *cell = addCell(name, "$lut");
        cell->parameters["\\LUT"] = lut;
        cell->parameters["\\WIDTH"] = sig_i.size();
-       cell->set("\\I", sig_i);
-       cell->set("\\O", sig_o);
-       add(cell);
+       cell->setPort("\\A", sig_i);
+       cell->setPort("\\Y", sig_o);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addAssert(RTLIL::IdString name, RTLIL::SigSpec sig_a, RTLIL::SigSpec sig_en)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$assert";
-       cell->set("\\A", sig_a);
-       cell->set("\\EN", sig_en);
-       add(cell);
+       RTLIL::Cell *cell = addCell(name, "$assert");
+       cell->setPort("\\A", sig_a);
+       cell->setPort("\\EN", sig_en);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addSr(RTLIL::IdString name, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr, RTLIL::SigSpec sig_q, bool set_polarity, bool clr_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$sr";
+       RTLIL::Cell *cell = addCell(name, "$sr");
        cell->parameters["\\SET_POLARITY"] = set_polarity;
        cell->parameters["\\CLR_POLARITY"] = clr_polarity;
        cell->parameters["\\WIDTH"] = sig_q.size();
-       cell->set("\\SET", sig_set);
-       cell->set("\\CLR", sig_clr);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       cell->setPort("\\SET", sig_set);
+       cell->setPort("\\CLR", sig_clr);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
-RTLIL::Cell* RTLIL::Module::addDff(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_d,   RTLIL::SigSpec sig_q, bool clk_polarity)
+RTLIL::Cell* RTLIL::Module::addDff(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$dff";
+       RTLIL::Cell *cell = addCell(name, "$dff");
        cell->parameters["\\CLK_POLARITY"] = clk_polarity;
        cell->parameters["\\WIDTH"] = sig_q.size();
-       cell->set("\\CLK", sig_clk);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       cell->setPort("\\CLK", sig_clk);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
+       return cell;
+}
+
+RTLIL::Cell* RTLIL::Module::addDffe(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool en_polarity)
+{
+       RTLIL::Cell *cell = addCell(name, "$dffe");
+       cell->parameters["\\CLK_POLARITY"] = clk_polarity;
+       cell->parameters["\\EN_POLARITY"] = en_polarity;
+       cell->parameters["\\WIDTH"] = sig_q.size();
+       cell->setPort("\\CLK", sig_clk);
+       cell->setPort("\\EN", sig_en);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addDffsr(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
                RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool set_polarity, bool clr_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$dffsr";
+       RTLIL::Cell *cell = addCell(name, "$dffsr");
        cell->parameters["\\CLK_POLARITY"] = clk_polarity;
        cell->parameters["\\SET_POLARITY"] = set_polarity;
        cell->parameters["\\CLR_POLARITY"] = clr_polarity;
        cell->parameters["\\WIDTH"] = sig_q.size();
-       cell->set("\\CLK", sig_clk);
-       cell->set("\\SET", sig_set);
-       cell->set("\\CLR", sig_clr);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       cell->setPort("\\CLK", sig_clk);
+       cell->setPort("\\SET", sig_set);
+       cell->setPort("\\CLR", sig_clr);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addAdff(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_arst, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q,
                RTLIL::Const arst_value, bool clk_polarity, bool arst_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$adff";
+       RTLIL::Cell *cell = addCell(name, "$adff");
        cell->parameters["\\CLK_POLARITY"] = clk_polarity;
        cell->parameters["\\ARST_POLARITY"] = arst_polarity;
        cell->parameters["\\ARST_VALUE"] = arst_value;
        cell->parameters["\\WIDTH"] = sig_q.size();
-       cell->set("\\CLK", sig_clk);
-       cell->set("\\ARST", sig_arst);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       cell->setPort("\\CLK", sig_clk);
+       cell->setPort("\\ARST", sig_arst);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addDlatch(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$dlatch";
+       RTLIL::Cell *cell = addCell(name, "$dlatch");
        cell->parameters["\\EN_POLARITY"] = en_polarity;
        cell->parameters["\\WIDTH"] = sig_q.size();
-       cell->set("\\EN", sig_en);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       cell->setPort("\\EN", sig_en);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addDlatchsr(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
                RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity, bool set_polarity, bool clr_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = "$dlatchsr";
+       RTLIL::Cell *cell = addCell(name, "$dlatchsr");
        cell->parameters["\\EN_POLARITY"] = en_polarity;
        cell->parameters["\\SET_POLARITY"] = set_polarity;
        cell->parameters["\\CLR_POLARITY"] = clr_polarity;
        cell->parameters["\\WIDTH"] = sig_q.size();
-       cell->set("\\EN", sig_en);
-       cell->set("\\SET", sig_set);
-       cell->set("\\CLR", sig_clr);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       cell->setPort("\\EN", sig_en);
+       cell->setPort("\\SET", sig_set);
+       cell->setPort("\\CLR", sig_clr);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addDffGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = stringf("$_DFF_%c_", clk_polarity ? 'P' : 'N');
-       cell->set("\\C", sig_clk);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       RTLIL::Cell *cell = addCell(name, stringf("$_DFF_%c_", clk_polarity ? 'P' : 'N'));
+       cell->setPort("\\C", sig_clk);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
+       return cell;
+}
+
+RTLIL::Cell* RTLIL::Module::addDffeGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool en_polarity)
+{
+       RTLIL::Cell *cell = addCell(name, stringf("$_DFFE_%c%c_", clk_polarity ? 'P' : 'N', en_polarity ? 'P' : 'N'));
+       cell->setPort("\\C", sig_clk);
+       cell->setPort("\\E", sig_en);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addDffsrGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
                RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool clk_polarity, bool set_polarity, bool clr_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = stringf("$_DFFSR_%c%c%c_", clk_polarity ? 'P' : 'N', set_polarity ? 'P' : 'N', clr_polarity ? 'P' : 'N');
-       cell->set("\\C", sig_clk);
-       cell->set("\\S", sig_set);
-       cell->set("\\R", sig_clr);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       RTLIL::Cell *cell = addCell(name, stringf("$_DFFSR_%c%c%c_", clk_polarity ? 'P' : 'N', set_polarity ? 'P' : 'N', clr_polarity ? 'P' : 'N'));
+       cell->setPort("\\C", sig_clk);
+       cell->setPort("\\S", sig_set);
+       cell->setPort("\\R", sig_clr);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addAdffGate(RTLIL::IdString name, RTLIL::SigSpec sig_clk, RTLIL::SigSpec sig_arst, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q,
                bool arst_value, bool clk_polarity, bool arst_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = stringf("$_DFF_%c%c%c_", clk_polarity ? 'P' : 'N', arst_polarity ? 'P' : 'N', arst_value ? '1' : '0');
-       cell->set("\\C", sig_clk);
-       cell->set("\\R", sig_arst);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       RTLIL::Cell *cell = addCell(name, stringf("$_DFF_%c%c%c_", clk_polarity ? 'P' : 'N', arst_polarity ? 'P' : 'N', arst_value ? '1' : '0'));
+       cell->setPort("\\C", sig_clk);
+       cell->setPort("\\R", sig_arst);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addDlatchGate(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = stringf("$_DLATCH_%c_", en_polarity ? 'P' : 'N');
-       cell->set("\\E", sig_en);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       RTLIL::Cell *cell = addCell(name, stringf("$_DLATCH_%c_", en_polarity ? 'P' : 'N'));
+       cell->setPort("\\E", sig_en);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 RTLIL::Cell* RTLIL::Module::addDlatchsrGate(RTLIL::IdString name, RTLIL::SigSpec sig_en, RTLIL::SigSpec sig_set, RTLIL::SigSpec sig_clr,
                RTLIL::SigSpec sig_d, RTLIL::SigSpec sig_q, bool en_polarity, bool set_polarity, bool clr_polarity)
 {
-       RTLIL::Cell *cell = new RTLIL::Cell;
-       cell->name = name;
-       cell->type = stringf("$_DLATCHSR_%c%c%c_", en_polarity ? 'P' : 'N', set_polarity ? 'P' : 'N', clr_polarity ? 'P' : 'N');
-       cell->set("\\E", sig_en);
-       cell->set("\\S", sig_set);
-       cell->set("\\R", sig_clr);
-       cell->set("\\D", sig_d);
-       cell->set("\\Q", sig_q);
-       add(cell);
+       RTLIL::Cell *cell = addCell(name, stringf("$_DLATCHSR_%c%c%c_", en_polarity ? 'P' : 'N', set_polarity ? 'P' : 'N', clr_polarity ? 'P' : 'N'));
+       cell->setPort("\\E", sig_en);
+       cell->setPort("\\S", sig_set);
+       cell->setPort("\\R", sig_clr);
+       cell->setPort("\\D", sig_d);
+       cell->setPort("\\Q", sig_q);
        return cell;
 }
 
 
 RTLIL::Wire::Wire()
 {
+       module = nullptr;
        width = 1;
        start_offset = 0;
        port_id = 0;
        port_input = false;
        port_output = false;
+       upto = false;
 }
 
 RTLIL::Memory::Memory()
@@ -1451,22 +1759,54 @@ RTLIL::Memory::Memory()
        size = 0;
 }
 
-bool RTLIL::Cell::has(RTLIL::IdString portname)
+RTLIL::Cell::Cell() : module(nullptr)
+{
+}
+
+bool RTLIL::Cell::hasPort(RTLIL::IdString portname) const
 {
        return connections_.count(portname) != 0;
 }
 
-void RTLIL::Cell::unset(RTLIL::IdString portname)
+void RTLIL::Cell::unsetPort(RTLIL::IdString portname)
 {
-       connections_.erase(portname);
+       RTLIL::SigSpec signal;
+       auto conn_it = connections_.find(portname);
+
+       if (conn_it != connections_.end())
+       {
+               for (auto mon : module->monitors)
+                       mon->notify_connect(this, conn_it->first, conn_it->second, signal);
+
+               if (module->design)
+                       for (auto mon : module->design->monitors)
+                               mon->notify_connect(this, conn_it->first, conn_it->second, signal);
+
+               connections_.erase(conn_it);
+       }
 }
 
-void RTLIL::Cell::set(RTLIL::IdString portname, RTLIL::SigSpec signal)
+void RTLIL::Cell::setPort(RTLIL::IdString portname, RTLIL::SigSpec signal)
 {
-       connections_[portname] = signal;
+       auto conn_it = connections_.find(portname);
+
+       if (conn_it == connections_.end()) {
+               connections_[portname] = RTLIL::SigSpec();
+               conn_it = connections_.find(portname);
+               log_assert(conn_it != connections_.end());
+       }
+
+       for (auto mon : module->monitors)
+               mon->notify_connect(this, conn_it->first, conn_it->second, signal);
+
+       if (module->design)
+               for (auto mon : module->design->monitors)
+                       mon->notify_connect(this, conn_it->first, conn_it->second, signal);
+
+       conn_it->second = signal;
 }
 
-const RTLIL::SigSpec &RTLIL::Cell::get(RTLIL::IdString portname) const
+const RTLIL::SigSpec &RTLIL::Cell::getPort(RTLIL::IdString portname) const
 {
        return connections_.at(portname);
 }
@@ -1476,6 +1816,26 @@ const std::map<RTLIL::IdString, RTLIL::SigSpec> &RTLIL::Cell::connections() cons
        return connections_;
 }
 
+bool RTLIL::Cell::hasParam(RTLIL::IdString paramname) const
+{
+       return parameters.count(paramname) != 0;
+}
+
+void RTLIL::Cell::unsetParam(RTLIL::IdString paramname)
+{
+       parameters.erase(paramname);
+}
+
+void RTLIL::Cell::setParam(RTLIL::IdString paramname, RTLIL::Const value)
+{
+       parameters[paramname] = value;
+}
+
+const RTLIL::Const &RTLIL::Cell::getParam(RTLIL::IdString paramname) const
+{
+       return parameters.at(paramname);
+}
+
 void RTLIL::Cell::check()
 {
 #ifndef NDEBUG
@@ -1486,20 +1846,34 @@ void RTLIL::Cell::check()
 
 void RTLIL::Cell::fixup_parameters(bool set_a_signed, bool set_b_signed)
 {
-       if (type[0] != '$' || type.substr(0, 2) == "$_" || type.substr(0, 8) == "$paramod" ||
+       if (type.substr(0, 1) != "$" || type.substr(0, 2) == "$_" || type.substr(0, 8) == "$paramod" ||
                        type.substr(0, 9) == "$verific$" || type.substr(0, 7) == "$array:" || type.substr(0, 8) == "$extern:")
                return;
 
-       if (type == "$mux" || type == "$pmux" || type == "$safe_pmux")
-       {
-               parameters["\\WIDTH"] = SIZE(connections_["\\Y"]);
-               if (type == "$pmux" || type == "$safe_pmux")
-                       parameters["\\S_WIDTH"] = SIZE(connections_["\\S"]);
+       if (type == "$mux" || type == "$pmux") {
+               parameters["\\WIDTH"] = GetSize(connections_["\\Y"]);
+               if (type == "$pmux")
+                       parameters["\\S_WIDTH"] = GetSize(connections_["\\S"]);
                check();
                return;
        }
 
-       bool signedness_ab = type != "$slice" && type != "$concat";
+       if (type == "$lut") {
+               parameters["\\WIDTH"] = GetSize(connections_["\\A"]);
+               return;
+       }
+
+       if (type == "$fa") {
+               parameters["\\WIDTH"] = GetSize(connections_["\\Y"]);
+               return;
+       }
+
+       if (type == "$lcu") {
+               parameters["\\WIDTH"] = GetSize(connections_["\\CO"]);
+               return;
+       }
+
+       bool signedness_ab = !type.in("$slice", "$concat", "$macc");
 
        if (connections_.count("\\A")) {
                if (signedness_ab) {
@@ -1508,7 +1882,7 @@ void RTLIL::Cell::fixup_parameters(bool set_a_signed, bool set_b_signed)
                        else if (parameters.count("\\A_SIGNED") == 0)
                                parameters["\\A_SIGNED"] = false;
                }
-               parameters["\\A_WIDTH"] = SIZE(connections_["\\A"]);
+               parameters["\\A_WIDTH"] = GetSize(connections_["\\A"]);
        }
 
        if (connections_.count("\\B")) {
@@ -1518,11 +1892,11 @@ void RTLIL::Cell::fixup_parameters(bool set_a_signed, bool set_b_signed)
                        else if (parameters.count("\\B_SIGNED") == 0)
                                parameters["\\B_SIGNED"] = false;
                }
-               parameters["\\B_WIDTH"] = SIZE(connections_["\\B"]);
+               parameters["\\B_WIDTH"] = GetSize(connections_["\\B"]);
        }
 
        if (connections_.count("\\Y"))
-               parameters["\\Y_WIDTH"] = SIZE(connections_["\\Y"]);
+               parameters["\\Y_WIDTH"] = GetSize(connections_["\\Y"]);
 
        check();
 }
@@ -1537,8 +1911,8 @@ RTLIL::SigChunk::SigChunk()
 RTLIL::SigChunk::SigChunk(const RTLIL::Const &value)
 {
        wire = NULL;
-       data = value;
-       width = data.bits.size();
+       data = value.bits;
+       width = GetSize(data);
        offset = 0;
 }
 
@@ -1561,33 +1935,35 @@ RTLIL::SigChunk::SigChunk(RTLIL::Wire *wire, int offset, int width)
 RTLIL::SigChunk::SigChunk(const std::string &str)
 {
        wire = NULL;
-       data = RTLIL::Const(str);
-       width = data.bits.size();
+       data = RTLIL::Const(str).bits;
+       width = GetSize(data);
        offset = 0;
 }
 
 RTLIL::SigChunk::SigChunk(int val, int width)
 {
        wire = NULL;
-       data = RTLIL::Const(val, width);
-       this->width = data.bits.size();
+       data = RTLIL::Const(val, width).bits;
+       this->width = GetSize(data);
        offset = 0;
 }
 
 RTLIL::SigChunk::SigChunk(RTLIL::State bit, int width)
 {
        wire = NULL;
-       data = RTLIL::Const(bit, width);
-       this->width = data.bits.size();
+       data = RTLIL::Const(bit, width).bits;
+       this->width = GetSize(data);
        offset = 0;
 }
 
 RTLIL::SigChunk::SigChunk(RTLIL::SigBit bit)
 {
        wire = bit.wire;
+       offset = 0;
        if (wire == NULL)
-               data = RTLIL::Const(bit.data);
-       offset = bit.offset;
+               data = RTLIL::Const(bit.data).bits;
+       else
+               offset = bit.offset;
        width = 1;
 }
 
@@ -1600,7 +1976,7 @@ RTLIL::SigChunk RTLIL::SigChunk::extract(int offset, int length) const
                ret.width = length;
        } else {
                for (int i = 0; i < length; i++)
-                       ret.data.bits.push_back(data.bits[offset+i]);
+                       ret.data.push_back(data[offset+i]);
                ret.width = length;
        }
        return ret;
@@ -1621,16 +1997,12 @@ bool RTLIL::SigChunk::operator <(const RTLIL::SigChunk &other) const
        if (width != other.width)
                return width < other.width;
 
-       return data.bits < other.data.bits;
+       return data < other.data;
 }
 
 bool RTLIL::SigChunk::operator ==(const RTLIL::SigChunk &other) const
 {
-       if (wire != other.wire || width != other.width || offset != other.offset)
-               return false;
-       if (data.bits != other.data.bits)
-               return false;
-       return true;
+       return wire == other.wire && width == other.width && offset == other.offset && data == other.data;
 }
 
 bool RTLIL::SigChunk::operator !=(const RTLIL::SigChunk &other) const
@@ -1680,7 +2052,7 @@ const RTLIL::SigSpec &RTLIL::SigSpec::operator=(const RTLIL::SigSpec &other)
                for (auto &bit : other.bits_) {
                        if (last && bit.wire == last->wire) {
                                if (bit.wire == NULL) {
-                                       last->data.bits.push_back(bit.data);
+                                       last->data.push_back(bit.data);
                                        last->width++;
                                        continue;
                                } else if (last_end_offset == bit.offset) {
@@ -1817,6 +2189,16 @@ RTLIL::SigSpec::SigSpec(std::set<RTLIL::SigBit> bits)
        check();
 }
 
+RTLIL::SigSpec::SigSpec(bool bit)
+{
+       cover("kernel.rtlil.sigspec.init.bool");
+
+       width_ = 0;
+       hash_ = 0;
+       append_bit(bit);
+       check();
+}
+
 void RTLIL::SigSpec::pack() const
 {
        RTLIL::SigSpec *that = (RTLIL::SigSpec*)this;
@@ -1836,7 +2218,7 @@ void RTLIL::SigSpec::pack() const
        for (auto &bit : old_bits) {
                if (last && bit.wire == last->wire) {
                        if (bit.wire == NULL) {
-                               last->data.bits.push_back(bit.data);
+                               last->data.push_back(bit.data);
                                last->width++;
                                continue;
                        } else if (last_end_offset == bit.offset) {
@@ -1872,7 +2254,7 @@ void RTLIL::SigSpec::unpack() const
        that->hash_ = 0;
 }
 
-#define DJB2(_hash, _value) do { (_hash) = (((_hash) << 5) + (_hash)) + (_value); } while (0)
+#define DJB2(_hash, _value) (_hash) = (((_hash) << 5) + (_hash)) + (_value)
 
 void RTLIL::SigSpec::hash() const
 {
@@ -1887,11 +2269,10 @@ void RTLIL::SigSpec::hash() const
        that->hash_ = 5381;
        for (auto &c : that->chunks_)
                if (c.wire == NULL) {
-                       for (auto &v : c.data.bits)
+                       for (auto &v : c.data)
                                DJB2(that->hash_, v);
                } else {
-                       for (auto &v : c.wire->name)
-                               DJB2(that->hash_, v);
+                       DJB2(that->hash_, c.wire->name.index_);
                        DJB2(that->hash_, c.offset);
                        DJB2(that->hash_, c.width);
                }
@@ -1920,26 +2301,40 @@ void RTLIL::SigSpec::replace(const RTLIL::SigSpec &pattern, const RTLIL::SigSpec
 
 void RTLIL::SigSpec::replace(const RTLIL::SigSpec &pattern, const RTLIL::SigSpec &with, RTLIL::SigSpec *other) const
 {
-       cover("kernel.rtlil.sigspec.replace");
+       log_assert(pattern.width_ == with.width_);
 
-       unpack();
        pattern.unpack();
        with.unpack();
 
+       std::map<RTLIL::SigBit, RTLIL::SigBit> rules;
+
+       for (int i = 0; i < GetSize(pattern.bits_); i++)
+               if (pattern.bits_[i].wire != NULL)
+                       rules[pattern.bits_[i]] = with.bits_[i];
+
+       replace(rules, other);
+}
+
+void RTLIL::SigSpec::replace(const std::map<RTLIL::SigBit, RTLIL::SigBit> &rules)
+{
+       replace(rules, this);
+}
+
+void RTLIL::SigSpec::replace(const std::map<RTLIL::SigBit, RTLIL::SigBit> &rules, RTLIL::SigSpec *other) const
+{
+       cover("kernel.rtlil.sigspec.replace");
+
        log_assert(other != NULL);
        log_assert(width_ == other->width_);
-       other->unpack();
-
-       log_assert(pattern.width_ == with.width_);
 
-       std::map<RTLIL::SigBit, RTLIL::SigBit> pattern_map;
-       for (int i = 0; i < SIZE(pattern.bits_); i++)
-               if (pattern.bits_[i].wire != NULL)
-                       pattern_map[pattern.bits_[i]] = with.bits_[i];
+       unpack();
+       other->unpack();
 
-       for (int i = 0; i < SIZE(bits_); i++)
-               if (pattern_map.count(bits_[i]))
-                       other->bits_[i] = pattern_map.at(bits_[i]);
+       for (int i = 0; i < GetSize(bits_); i++) {
+               auto it = rules.find(bits_[i]);
+               if (it != rules.end())
+                       other->bits_[i] = it->second;
+       }
 
        other->check();
 }
@@ -1956,6 +2351,23 @@ void RTLIL::SigSpec::remove(const RTLIL::SigSpec &pattern, RTLIL::SigSpec *other
 }
 
 void RTLIL::SigSpec::remove2(const RTLIL::SigSpec &pattern, RTLIL::SigSpec *other)
+{
+       std::set<RTLIL::SigBit> pattern_bits = pattern.to_sigbit_set();
+       remove2(pattern_bits, other);
+}
+
+void RTLIL::SigSpec::remove(const std::set<RTLIL::SigBit> &pattern)
+{
+       remove2(pattern, NULL);
+}
+
+void RTLIL::SigSpec::remove(const std::set<RTLIL::SigBit> &pattern, RTLIL::SigSpec *other) const
+{
+       RTLIL::SigSpec tmp = *this;
+       tmp.remove2(pattern, other);
+}
+
+void RTLIL::SigSpec::remove2(const std::set<RTLIL::SigBit> &pattern, RTLIL::SigSpec *other)
 {
        if (other)
                cover("kernel.rtlil.sigspec.remove_other");
@@ -1969,55 +2381,62 @@ void RTLIL::SigSpec::remove2(const RTLIL::SigSpec &pattern, RTLIL::SigSpec *othe
                other->unpack();
        }
 
-       std::set<RTLIL::SigBit> pattern_bits = pattern.to_sigbit_set();
        std::vector<RTLIL::SigBit> new_bits, new_other_bits;
 
-       for (int i = 0; i < SIZE(bits_); i++) {
-               if (bits_[i].wire != NULL && pattern_bits.count(bits_[i]))
+       new_bits.resize(GetSize(bits_));
+       if (other != NULL)
+               new_other_bits.resize(GetSize(bits_));
+
+       int k = 0;
+       for (int i = 0; i < GetSize(bits_); i++) {
+               if (bits_[i].wire != NULL && pattern.count(bits_[i]))
                        continue;
                if (other != NULL)
-                       new_other_bits.push_back(other->bits_[i]);
-               new_bits.push_back(bits_[i]);
+                       new_other_bits[k] = other->bits_[i];
+               new_bits[k++] = bits_[i];
        }
 
+       new_bits.resize(k);
+       if (other != NULL)
+               new_other_bits.resize(k);
+
        bits_.swap(new_bits);
-       width_ = SIZE(bits_);
+       width_ = GetSize(bits_);
 
        if (other != NULL) {
                other->bits_.swap(new_other_bits);
-               other->width_ = SIZE(other->bits_);
+               other->width_ = GetSize(other->bits_);
        }
 
        check();
 }
 
-RTLIL::SigSpec RTLIL::SigSpec::extract(RTLIL::SigSpec pattern, const RTLIL::SigSpec *other) const
+RTLIL::SigSpec RTLIL::SigSpec::extract(const RTLIL::SigSpec &pattern, const RTLIL::SigSpec *other) const
+{
+       std::set<RTLIL::SigBit> pattern_bits = pattern.to_sigbit_set();
+       return extract(pattern_bits, other);
+}
+
+RTLIL::SigSpec RTLIL::SigSpec::extract(const std::set<RTLIL::SigBit> &pattern, const RTLIL::SigSpec *other) const
 {
        if (other)
                cover("kernel.rtlil.sigspec.extract_other");
        else
                cover("kernel.rtlil.sigspec.extract");
 
-       pack();
-       pattern.pack();
-
-       if (other != NULL)
-               other->pack();
-
        log_assert(other == NULL || width_ == other->width_);
 
-       std::set<RTLIL::SigBit> pat = pattern.to_sigbit_set();
        std::vector<RTLIL::SigBit> bits_match = to_sigbit_vector();
        RTLIL::SigSpec ret;
 
        if (other) {
                std::vector<RTLIL::SigBit> bits_other = other->to_sigbit_vector();
                for (int i = 0; i < width_; i++)
-                       if (bits_match[i].wire && pat.count(bits_match[i]))
+                       if (bits_match[i].wire && pattern.count(bits_match[i]))
                                ret.append_bit(bits_other[i]);
        } else {
                for (int i = 0; i < width_; i++)
-                       if (bits_match[i].wire && pat.count(bits_match[i]))
+                       if (bits_match[i].wire && pattern.count(bits_match[i]))
                                ret.append_bit(bits_match[i]);
        }
 
@@ -2049,7 +2468,7 @@ void RTLIL::SigSpec::remove_const()
                cover("kernel.rtlil.sigspec.remove_const.packed");
 
                std::vector<RTLIL::SigChunk> new_chunks;
-               new_chunks.reserve(SIZE(chunks_));
+               new_chunks.reserve(GetSize(chunks_));
 
                width_ = 0;
                for (auto &chunk : chunks_)
@@ -2123,8 +2542,8 @@ void RTLIL::SigSpec::append(const RTLIL::SigSpec &signal)
                {
                        auto &my_last_c = chunks_.back();
                        if (my_last_c.wire == NULL && other_c.wire == NULL) {
-                               auto &this_data = my_last_c.data.bits;
-                               auto &other_data = other_c.data.bits;
+                               auto &this_data = my_last_c.data;
+                               auto &other_data = other_c.data;
                                this_data.insert(this_data.end(), other_data.begin(), other_data.end());
                                my_last_c.width += other_c.width;
                        } else
@@ -2151,7 +2570,7 @@ void RTLIL::SigSpec::append_bit(const RTLIL::SigBit &bit)
                else
                        if (bit.wire == NULL)
                                if (chunks_.back().wire == NULL) {
-                                       chunks_.back().data.bits.push_back(bit.data);
+                                       chunks_.back().data.push_back(bit.data);
                                        chunks_.back().width++;
                                } else
                                        chunks_.push_back(bit);
@@ -2171,9 +2590,9 @@ void RTLIL::SigSpec::append_bit(const RTLIL::SigBit &bit)
        check();
 }
 
-void RTLIL::SigSpec::extend(int width, bool is_signed)
+void RTLIL::SigSpec::extend_xx(int width, bool is_signed)
 {
-       cover("kernel.rtlil.sigspec.extend");
+       cover("kernel.rtlil.sigspec.extend_xx");
 
        pack();
 
@@ -2181,10 +2600,9 @@ void RTLIL::SigSpec::extend(int width, bool is_signed)
                remove(width, width_ - width);
        
        if (width_ < width) {
-               RTLIL::SigSpec padding = width_ > 0 ? extract(width_ - 1, 1) : RTLIL::SigSpec(RTLIL::State::S0);
-               if (!is_signed && padding != RTLIL::SigSpec(RTLIL::State::Sx) && padding != RTLIL::SigSpec(RTLIL::State::Sz) &&
-                               padding != RTLIL::SigSpec(RTLIL::State::Sa) && padding != RTLIL::SigSpec(RTLIL::State::Sm))
-                       padding = RTLIL::SigSpec(RTLIL::State::S0);
+               RTLIL::SigBit padding = width_ > 0 ? (*this)[width_ - 1] : RTLIL::State::S0;
+               if (!is_signed && (padding == RTLIL::State::S1 || padding.wire))
+                       padding = RTLIL::State::S0;
                while (width_ < width)
                        append(padding);
        }
@@ -2200,9 +2618,9 @@ void RTLIL::SigSpec::extend_u0(int width, bool is_signed)
                remove(width, width_ - width);
        
        if (width_ < width) {
-               RTLIL::SigSpec padding = width_ > 0 ? extract(width_ - 1, 1) : RTLIL::SigSpec(RTLIL::State::S0);
+               RTLIL::SigBit padding = width_ > 0 ? (*this)[width_ - 1] : RTLIL::State::S0;
                if (!is_signed)
-                       padding = RTLIL::SigSpec(RTLIL::State::S0);
+                       padding = RTLIL::State::S0;
                while (width_ < width)
                        append(padding);
        }
@@ -2237,14 +2655,14 @@ void RTLIL::SigSpec::check() const
                                if (i > 0)
                                        log_assert(chunks_[i-1].wire != NULL);
                                log_assert(chunk.offset == 0);
-                               log_assert(chunk.data.bits.size() == (size_t)chunk.width);
+                               log_assert(chunk.data.size() == (size_t)chunk.width);
                        } else {
                                if (i > 0 && chunks_[i-1].wire == chunk.wire)
                                        log_assert(chunk.offset != chunks_[i-1].offset + chunks_[i-1].width);
                                log_assert(chunk.offset >= 0);
                                log_assert(chunk.width >= 0);
                                log_assert(chunk.offset + chunk.width <= chunk.wire->width);
-                               log_assert(chunk.data.bits.size() == 0);
+                               log_assert(chunk.data.size() == 0);
                        }
                        w += chunk.width;
                }
@@ -2255,7 +2673,7 @@ void RTLIL::SigSpec::check() const
        {
                cover("kernel.rtlil.sigspec.check.unpacked");
 
-               log_assert(width_ == SIZE(bits_));
+               log_assert(width_ == GetSize(bits_));
                log_assert(chunks_.empty());
        }
 }
@@ -2330,7 +2748,7 @@ bool RTLIL::SigSpec::is_wire() const
        cover("kernel.rtlil.sigspec.is_wire");
 
        pack();
-       return SIZE(chunks_) == 1 && chunks_[0].wire && chunks_[0].wire->width == width_;
+       return GetSize(chunks_) == 1 && chunks_[0].wire && chunks_[0].wire->width == width_;
 }
 
 bool RTLIL::SigSpec::is_chunk() const
@@ -2338,7 +2756,7 @@ bool RTLIL::SigSpec::is_chunk() const
        cover("kernel.rtlil.sigspec.is_chunk");
 
        pack();
-       return SIZE(chunks_) == 1;
+       return GetSize(chunks_) == 1;
 }
 
 bool RTLIL::SigSpec::is_fully_const() const
@@ -2360,8 +2778,8 @@ bool RTLIL::SigSpec::is_fully_def() const
        for (auto it = chunks_.begin(); it != chunks_.end(); it++) {
                if (it->width > 0 && it->wire != NULL)
                        return false;
-               for (size_t i = 0; i < it->data.bits.size(); i++)
-                       if (it->data.bits[i] != RTLIL::State::S0 && it->data.bits[i] != RTLIL::State::S1)
+               for (size_t i = 0; i < it->data.size(); i++)
+                       if (it->data[i] != RTLIL::State::S0 && it->data[i] != RTLIL::State::S1)
                                return false;
        }
        return true;
@@ -2375,8 +2793,8 @@ bool RTLIL::SigSpec::is_fully_undef() const
        for (auto it = chunks_.begin(); it != chunks_.end(); it++) {
                if (it->width > 0 && it->wire != NULL)
                        return false;
-               for (size_t i = 0; i < it->data.bits.size(); i++)
-                       if (it->data.bits[i] != RTLIL::State::Sx && it->data.bits[i] != RTLIL::State::Sz)
+               for (size_t i = 0; i < it->data.size(); i++)
+                       if (it->data[i] != RTLIL::State::Sx && it->data[i] != RTLIL::State::Sz)
                                return false;
        }
        return true;
@@ -2389,8 +2807,8 @@ bool RTLIL::SigSpec::has_marked_bits() const
        pack();
        for (auto it = chunks_.begin(); it != chunks_.end(); it++)
                if (it->width > 0 && it->wire == NULL) {
-                       for (size_t i = 0; i < it->data.bits.size(); i++)
-                               if (it->data.bits[i] == RTLIL::State::Sm)
+                       for (size_t i = 0; i < it->data.size(); i++)
+                               if (it->data[i] == RTLIL::State::Sm)
                                        return true;
                }
        return false;
@@ -2401,20 +2819,20 @@ bool RTLIL::SigSpec::as_bool() const
        cover("kernel.rtlil.sigspec.as_bool");
 
        pack();
-       log_assert(is_fully_const() && SIZE(chunks_) <= 1);
+       log_assert(is_fully_const() && GetSize(chunks_) <= 1);
        if (width_)
-               return chunks_[0].data.as_bool();
+               return RTLIL::Const(chunks_[0].data).as_bool();
        return false;
 }
 
-int RTLIL::SigSpec::as_int() const
+int RTLIL::SigSpec::as_int(bool is_signed) const
 {
        cover("kernel.rtlil.sigspec.as_int");
 
        pack();
-       log_assert(is_fully_const() && SIZE(chunks_) <= 1);
+       log_assert(is_fully_const() && GetSize(chunks_) <= 1);
        if (width_)
-               return chunks_[0].data.as_int();
+               return RTLIL::Const(chunks_[0].data).as_int(is_signed);
        return 0;
 }
 
@@ -2430,7 +2848,7 @@ std::string RTLIL::SigSpec::as_string() const
                        for (int j = 0; j < chunk.width; j++)
                                str += "?";
                else
-                       str += chunk.data.as_string();
+                       str += RTLIL::Const(chunk.data).as_string();
        }
        return str;
 }
@@ -2440,7 +2858,7 @@ RTLIL::Const RTLIL::SigSpec::as_const() const
        cover("kernel.rtlil.sigspec.as_const");
 
        pack();
-       log_assert(is_fully_const() && SIZE(chunks_) <= 1);
+       log_assert(is_fully_const() && GetSize(chunks_) <= 1);
        if (width_)
                return chunks_[0].data;
        return RTLIL::Const();
@@ -2507,6 +2925,22 @@ std::vector<RTLIL::SigBit> RTLIL::SigSpec::to_sigbit_vector() const
        return bits_;
 }
 
+std::map<RTLIL::SigBit, RTLIL::SigBit> RTLIL::SigSpec::to_sigbit_map(const RTLIL::SigSpec &other) const
+{
+       cover("kernel.rtlil.sigspec.to_sigbit_map");
+
+       unpack();
+       other.unpack();
+
+       log_assert(width_ == other.width_);
+
+       std::map<RTLIL::SigBit, RTLIL::SigBit> new_map;
+       for (int i = 0; i < width_; i++)
+               new_map[bits_[i]] = other.bits_[i];
+
+       return new_map;
+}
+
 RTLIL::SigBit RTLIL::SigSpec::to_single_sigbit() const
 {
        cover("kernel.rtlil.sigspec.to_single_sigbit");
@@ -2550,7 +2984,7 @@ bool RTLIL::SigSpec::parse(RTLIL::SigSpec &sig, RTLIL::Module *module, std::stri
                if (netname.size() == 0)
                        continue;
 
-               if ('0' <= netname[0] && netname[0] <= '9') {
+               if (('0' <= netname[0] && netname[0] <= '9') || netname[0] == '\'') {
                        cover("kernel.rtlil.sigspec.parse.const");
                        AST::get_line_num = sigspec_parse_get_dummy_line_num;
                        AST::AstNode *ast = VERILOG_FRONTEND::const2ast(netname);
@@ -2595,7 +3029,10 @@ bool RTLIL::SigSpec::parse(RTLIL::SigSpec &sig, RTLIL::Module *module, std::stri
                        sigspec_parse_split(index_tokens, indices.substr(1, indices.size()-2), ':');
                        if (index_tokens.size() == 1) {
                                cover("kernel.rtlil.sigspec.parse.bit_sel");
-                               sig.append(RTLIL::SigSpec(wire, atoi(index_tokens.at(0).c_str())));
+                               int a = atoi(index_tokens.at(0).c_str());
+                               if (a < 0 || a >= wire->width)
+                                       return false;
+                               sig.append(RTLIL::SigSpec(wire, a));
                        } else {
                                cover("kernel.rtlil.sigspec.parse.part_sel");
                                int a = atoi(index_tokens.at(0).c_str());
@@ -2604,6 +3041,10 @@ bool RTLIL::SigSpec::parse(RTLIL::SigSpec &sig, RTLIL::Module *module, std::stri
                                        int tmp = a;
                                        a = b, b = tmp;
                                }
+                               if (a < 0 || a >= wire->width)
+                                       return false;
+                               if (b < 0 || b >= wire->width)
+                                       return false;
                                sig.append(RTLIL::SigSpec(wire, a, b-a+1));
                        }
                } else
@@ -2649,7 +3090,7 @@ bool RTLIL::SigSpec::parse_rhs(const RTLIL::SigSpec &lhs, RTLIL::SigSpec &sig, R
 
        if (lhs.chunks_.size() == 1) {
                char *p = (char*)str.c_str(), *endptr;
-               long long int val = strtoll(p, &endptr, 10);
+               long int val = strtol(p, &endptr, 10);
                if (endptr && endptr != p && *endptr == 0) {
                        sig = RTLIL::SigSpec(val, lhs.width_);
                        cover("kernel.rtlil.sigspec.parse.rhs_dec");
@@ -2726,3 +3167,5 @@ RTLIL::Process *RTLIL::Process::clone() const
        return new_proc;
 }
 
+YOSYS_NAMESPACE_END
+